hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
f76aa2dadb4f84b5feb0f6813b631b0059d6d8a9
2,071
package com.spring.dao; import java.math.BigInteger; import java.util.List; import org.apache.ibatis.annotations.Param; import com.spring.model.WeldingMachine; import tk.mybatis.mapper.common.Mapper; public interface WeldingMachineMapper extends Mapper<WeldingMachine>{ List<WeldingMachine> getWeldingMachineAll(@Param("parent") BigInteger parent,@Param("str") String str); List<WeldingMachine> AllMachine(@Param("wid")BigInteger wid); List<WeldingMachine> getEquipmentno(); void addWeldingMachine(WeldingMachine wm); void editWeldingMachine(WeldingMachine wm); void deleteWeldingMachine(@Param("wid")BigInteger wid); BigInteger getWeldingMachineByEno(@Param("eno")String eno); int getEquipmentnoCount(@Param("eno")String eno); List<WeldingMachine> findAllweldmachine(); int getEquipmentidCount(@Param("eid")String eid); int getGatheridCount(@Param("itemid")BigInteger itemid,@Param("gather")String gather); WeldingMachine getWeldingMachineById(@Param("wid")BigInteger wid); void editstatus(@Param("wid")BigInteger wid,@Param("status")int status); void deleteByInsf(@Param("insfId")BigInteger insfId); List<WeldingMachine> getWeldingMachineByInsf(@Param("insfId")BigInteger insfId); BigInteger getIdByGatherid(@Param("gatherid")BigInteger gatherid); void editGatherid(@Param("wid")BigInteger wid); BigInteger getMachineCountByManu(@Param("mid")BigInteger mid,@Param("id")BigInteger id); void deleteHistory(@Param("wid")BigInteger wid); void addfactoryType(WeldingMachine wm); void addquamethod(WeldingMachine wm); void deletefactory(@Param("statusId")BigInteger statusId); void deletequamethod(@Param("statusId")BigInteger statusId); List<WeldingMachine> getAllMachine(); List<WeldingMachine> getMachineByIns(@Param("id")BigInteger id); List<WeldingMachine> getMachineGather(); List<WeldingMachine> getMachineModel(); List<WeldingMachine> getlibarary(); void deletelibrary(@Param("id")BigInteger id); void addlibrary(WeldingMachine wm); void editlibrary(WeldingMachine wm); }
27.986486
104
0.775471
d4c6768bf3b74d08f0f1e25870add3268d5c0cbd
828
package l03.impostoRenda; import java.util.Scanner; public class ImpostoRecolhido { public static void main(String[] args) { Contador c = new Contador(); Scanner input = new Scanner(System.in); int controle = 0; float impostoRecolhido = 0; System.out.print("Quantidade de funcionários: "); int funcionarios = input.nextInt(); System.out.println(""); do { Trabalhador t = new Trabalhador(); System.out.print("Salário bruto: "); t.setSalarioBruto(input.nextFloat()); System.out.print("Dependentes: "); t.setDependentes(input.nextInt()); System.out.println(""); controle++; impostoRecolhido += c.calcularIR(t); } while (controle < funcionarios); input.close(); System.out.printf("O total de imposto pago pela empresa é de R$ %.2f.", impostoRecolhido); } }
23.657143
92
0.67029
1c0c9997f88401497c2b44661a38ba59045ebda3
1,925
package net.paperpixel.fk.kube; import net.paperpixel.fk.core.FKConstants; import java.awt.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public enum KubeType { INACTIVE_KUBE("inactive", InactiveKube.class.getName(), FKConstants.INACTIVE_KUBE_COLOR), EFFECT_KUBE("effect", EffectKube.class.getName(), FKConstants.EFFECT_KUBE_COLOR), NOTE_KUBE("note", NoteKube.class.getName(), FKConstants.NOTE_KUBE_COLOR), // IDLE_KUBE("idle", IdleKube.class.getName(), FKConstants.IDLE_KUBE_COLOR), LOOP_KUBE("loop", LoopKube.class.getName(), FKConstants.LOOP_KUBE_COLOR); String name; String className; Color color; KubeType(String theName, String theClassName, Color theColor) { name = theName; className = theClassName; color = theColor; } // Joli ! public AbstractKube getInstance(int theLine, int theCol) { try { Class myClass = (Class) Class.forName(className); Constructor myConstructor = myClass.getDeclaredConstructor(int.class, int.class); AbstractKube myKube = (AbstractKube) myConstructor.newInstance(theLine, theCol); myKube.setType(this); myKube.setColor(KubeWall.getRandomColor()); return myKube; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } public Color getColor() { return color; } public void setColor(Color theColor) { color = theColor; } public String getName() { return name; } }
31.048387
93
0.64987
141baf2eded6a1eb4bbdb1447099f1ec48f19542
416
package com.derek.mall.coupon.dao; import com.derek.mall.coupon.entity.CouponSpuCategoryRelationEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 优惠券分类关联 * * @author derek * @email derek_mcp@163.com * @date 2020-12-22 15:06:31 */ @Mapper public interface CouponSpuCategoryRelationDao extends BaseMapper<CouponSpuCategoryRelationEntity> { }
23.111111
99
0.788462
8084522b0593b335b60a07305d51c36158b7aca0
4,995
package com.example.umang.calculator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import static android.R.attr.value; public class MainActivity extends AppCompatActivity { String answer = ""; double two= 0, result=0; char sign; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void equalTo(View view) { if(answer !="") { result = computeInfixExpr(answer); if (result % 1 == 0) { answer = String.valueOf((int) result); } else { answer = String.format("%.6f", result); answer = removeTrailingZeros(answer); } displayMessage(answer); } } public void one(View view) { answer += "1"; displayMessage(answer); } public void two(View view) { answer += "2"; displayMessage(answer); } public void three(View view) { answer += "3"; displayMessage(answer); } public void four(View view) { answer += "4"; displayMessage(answer); } public void five(View view) { answer += "5"; displayMessage(answer); } public void six(View view) { answer += "6"; displayMessage(answer); } public void seven(View view) { answer += "7"; displayMessage(answer); } public void eight(View view) { answer += "8"; displayMessage(answer); } public void nine(View view) { answer += "9"; displayMessage(answer); } public void zero(View view) { answer += "0"; displayMessage(answer); } public void ac(View view) { answer = ""; displayMessage(String.valueOf(0)); } public void divide(View view) { answer += " / "; displayMessage(answer); } public void plus(View view) { answer += " + "; displayMessage(answer); } public void multiply(View view) { answer += " x "; displayMessage(answer); } public void minus(View view) { answer += " - "; displayMessage(answer); } public void dot(View view) { answer += "."; displayMessage(answer); } public void back(View view) { String str = answer; if (str != null && str.length() > 0) { if(str.charAt(str.length() - 1) == ' ') str = str.substring(0, str.length() - 3); else str = str.substring(0, str.length() - 1); } answer = str; displayMessage(answer); } public void displayMessage(String answer) { TextView answerView = (TextView) findViewById(R.id.answer_view); answerView.setText(answer); } public String removeTrailingZeros(String str ){ if (str == null){ return null;} char[] chars = str.toCharArray();int length,index ;length = str.length(); index = length -1; for (; index >=0;index--) { if (chars[index] != '0'){ break;} } return (index == length-1) ? str :str.substring(0,index+1); } public double computeInfixExpr(String input) { String[] expr = input.split(" "); int i = 0; double operRight=0; double operLeft = Double.valueOf(expr[i++]); while (i < expr.length) { String operator = expr[i++]; if(i!=expr.length) operRight = Double.valueOf(expr[i++]); switch (operator) { case "x": operLeft = operLeft * operRight; break; case "/": operLeft = operLeft / operRight; break; case "+": case "-": while (i < expr.length) { String operator2 = expr[i++]; if (operator2.equals("+") || operator2.equals("-")) { i--; break; } if (operator2.equals("x")) { operRight = operRight * Double.valueOf(expr[i++]); } if (operator2.equals("/")) { operRight = operRight / Double.valueOf(expr[i++]); } } if (operator.equals("+")) operLeft = operLeft + operRight; else operLeft = operLeft - operRight; } } return operLeft; } }
23.450704
81
0.471672
19a03b24c753c857409c39c7dbc215ac9f3d0b67
9,162
package wyjc.builder; import static wyc.lang.WhileyFile.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import wybs.lang.NameResolver; import wyc.lang.WhileyFile; import wyc.lang.WhileyFile.Decl; import wyc.lang.WhileyFile.Expr; import wyc.lang.WhileyFile.Type; import wyil.type.TypeSystem; import wyjc.core.JavaFile; import wyjc.core.JavaFile.Declaration; import wyjc.core.JavaFile.Term; /** * <p> * Translate a type test expression. This is a complex procedure which may need * to recursively explore the value being tested. Initially, it will employ an * inline test whereever possible. For example, consider this case: * </p> * * <pre> * function f(int|null x) -> (int r): * if x is int: * ... * </pre> * * <p> * Here, we can translate <code>x is int</code> into * <code>x instanceof BigInteger</code>. However, not all tests can be * translated inline. For example, consider this test: * </p> * * <pre> * function f(any[] xs) -> (int r): * if xs is int[]: * ... * </pre> * * <p> * This necessarily requires iterating every element of <code>xs</code> to check * whether or not it's a BigInteger. This test translates into * <code>isType$ia(xs)</code>, defined as: * </p> * * <pre> * private static boolean isType$ia(Object[] xs) { * for (int i = 0; i != xs.length; ++i) { * if (!xs[i] instanceof BigInteger) { * return false; * } * } * return true; * } * </pre> * <p> * Observe that there are optimisations which can be employed. For example, * consider this case: * </p> * * <pre> * function f(int|(int[]) xs) -> (int r): * if xs is int[]: * ... * </pre> * <p> * Here, we can translate the test into <code>!(xs instanceof BigInteger)</code> * based on the type information we have available. * </p> * * @param expr * @param parent * @return */ public class TypeTestGenerator implements CodeGenerator<Expr.Is> { private TypeSystem typeSystem; private HashMap<Type,JavaFile.Method> declarations = new HashMap<>(); public TypeTestGenerator(TypeSystem typeSystem) { this.typeSystem = typeSystem; } /** * <p> * Generate a test method for a given type. For example, if we had * <code>x is int[]</code> then we would generate the following: * </p> * * <pre> * boolean is$1(Object o) { * if(o is Object[]) { * Object[] tmp = (Object[]) o; * for(int i=0;i!=tmp.length;++i) { * if(!tmp[i] instanceof BigInteger) { * return false; * } * } * return true; * } * } * </pre> * * <p> * <b>NOTE:</b> One of the limitations of this implementation is that it does * not take into account knowledge of the variables type. For example, if we * knew x had type <code>any[]</code> then the input parameter to the method * above could be <code>Object[]</code> already. * </p> * * @param type * @param id * @return */ public Term generate(WhileyFile.Type type, JavaFile.Term operand) { JavaFile.Block body; // First, attempt inline translation (if possible) switch (type.getOpcode()) { case TYPE_null: // Translate "x is null" as "x == null" in Java. return new JavaFile.Operator(JavaFile.Operator.Kind.EQ, operand, new JavaFile.Constant(null)); case TYPE_bool: return new JavaFile.InstanceOf(operand, JAVA_LANG_BOOLEAN); case TYPE_byte: return new JavaFile.InstanceOf(operand, JAVA_LANG_BYTE); case TYPE_int: return new JavaFile.InstanceOf(operand, JAVA_MATH_BIGINTEGER); case TYPE_array: body = generateTypeTest((Type.Array) type); break; case TYPE_record: body = generateTypeTest((Type.Record) type); break; case TYPE_nominal: body = generateTypeTest((Type.Nominal) type); break; default: throw new IllegalArgumentException("invalid type argument"); } // At this point, we need a more complex translation. Therefore, we generate an // external type test method and return an invocation to that, rather than // inlining the test. JavaFile.Method method = new JavaFile.Method("is$" + type.getIndex(), JavaFile.BOOLEAN); method.getParameters().add(new JavaFile.VariableDeclaration(JAVA_LANG_OBJECT, "o")); method.getModifiers().add(JavaFile.Modifier.PRIVATE); method.getModifiers().add(JavaFile.Modifier.STATIC); method.setBody(body); declarations.put(type, method); return new JavaFile.Invoke(null, method.getName(), operand); } private JavaFile.Block generateTypeTest(Type.Record type) { List<JavaFile.Term> stmts = new ArrayList<>(); JavaFile.Term var_r = new JavaFile.VariableAccess("r"); JavaFile.Term var_v = new JavaFile.VariableAccess("v"); Tuple<Decl.Variable> fields = type.getFields(); for (int i = 0; i != fields.size(); ++i) { Decl.Variable field = fields.get(i); JavaFile.Term fieldTest = new JavaFile.Invoke(var_v, "has", new JavaFile.Constant(field.getName().get())); JavaFile.Term access = new JavaFile.Invoke(var_v, "get", new JavaFile.Constant(field.getName().get())); JavaFile.Term typeTest = generate(field.getType(), access); JavaFile.Term rhs = and(fieldTest, typeTest); rhs = (i != 0) ? and(var_r, rhs) : rhs; JavaFile.Assignment stmt = new JavaFile.Assignment(var_r, rhs); stmts.add(stmt); } return generateTestTemplate(WHILEY_RECORD, stmts); } private JavaFile.Block generateTypeTest(Type.Array type) { List<JavaFile.Term> stmts = new ArrayList<>(); JavaFile.Term var_r = new JavaFile.VariableAccess("r"); JavaFile.Term var_v = new JavaFile.VariableAccess("v"); JavaFile.VariableDeclaration initialiser = new JavaFile.VariableDeclaration(JavaFile.INT, "i", new JavaFile.Constant(0)); JavaFile.Term var_i = new JavaFile.VariableAccess("i"); JavaFile.Term length = new JavaFile.FieldAccess(var_v, "length"); JavaFile.Term condition = new JavaFile.Operator(JavaFile.Operator.Kind.LT, var_i, length); JavaFile.Term increment = new JavaFile.Assignment(var_i, new JavaFile.Operator(JavaFile.Operator.Kind.ADD, var_i, new JavaFile.Constant(1))); JavaFile.Term access = new JavaFile.ArrayAccess(var_v, var_i); JavaFile.Term assignment = new JavaFile.Assignment(var_r, and(var_r, generate(type.getElement(),access))); JavaFile.Block body = new JavaFile.Block(); body.getTerms().add(assignment); stmts.add(new JavaFile.Assignment(var_r, new JavaFile.Constant(true))); stmts.add(new JavaFile.For(initialiser, condition, increment, body)); return generateTestTemplate(WHILEY_ARRAY, stmts); } private JavaFile.Block generateTypeTest(Type.Nominal type) { try { Decl.Type decl = typeSystem.resolveExactly(type.getName(), Decl.Type.class); // FIXME: problem here with recursive definitions. // FIXME: problem here with type invariants JavaFile.Block block = new JavaFile.Block(); JavaFile.Term var_o = new JavaFile.VariableAccess("o"); JavaFile.Term condition = generate(decl.getVariableDeclaration().getType(), var_o); block.getTerms().add(new JavaFile.Return(condition)); return block; } catch (NameResolver.ResolutionError e) { throw new RuntimeException(e); } } /** * Generate a test template which looks like this: * * <pre> * boolean r = false; * if(o instanceof TYPE) { * Type v = (Type) o; * ... * } * return r; * </pre> * * Here, the TYPE and the true branch contents are parameters. * * @param terms * @return */ private JavaFile.Block generateTestTemplate(JavaFile.Type type,List<JavaFile.Term> terms) { JavaFile.Block block = new JavaFile.Block(); JavaFile.Term var_r = new JavaFile.VariableAccess("r"); block.getTerms().add(new JavaFile.VariableDeclaration(JavaFile.BOOLEAN, "r", new JavaFile.Constant(false))); JavaFile.Term var_o = new JavaFile.VariableAccess("o"); JavaFile.Term condition = new JavaFile.InstanceOf(var_o, type); // True Branch JavaFile.Block trueBranch = new JavaFile.Block(); trueBranch.getTerms() .add(new JavaFile.VariableDeclaration(type, "v", new JavaFile.Cast(type, var_o))); trueBranch.getTerms().addAll(terms); JavaFile.If stmt = new JavaFile.If(condition, trueBranch, null); block.getTerms().add(stmt); // False Branch block.getTerms().add(new JavaFile.Return(var_r)); return block; } @Override public Collection<? extends Declaration> generateSupplementaryDeclarations() { return declarations.values(); } private static JavaFile.Term and(JavaFile.Term lhs, JavaFile.Term rhs) { if (lhs == null) { return rhs; } else { return new JavaFile.Operator(JavaFile.Operator.Kind.AND, lhs, rhs); } } private static JavaFile.Reference JAVA_MATH_BIGINTEGER = new JavaFile.Reference("BigInteger"); private static JavaFile.Reference JAVA_LANG_OBJECT = new JavaFile.Reference("Object"); private static JavaFile.Reference JAVA_LANG_BOOLEAN = new JavaFile.Reference("Boolean"); private static JavaFile.Reference JAVA_LANG_BYTE = new JavaFile.Reference("Byte"); private static final JavaFile.Reference WHILEY_RECORD = new JavaFile.Reference("Wy", "Struct"); private static final JavaFile.Array WHILEY_ARRAY = new JavaFile.Array(new JavaFile.Reference("Object")); }
34.704545
123
0.699301
dd4e46dfdea86c00d172d2e0e800d746e1508ab1
16,503
package cz.destil.settleup.util; import android.content.Context; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import cz.destil.settleup.R; import cz.destil.settleup.data.Preferences; import cz.destil.settleup.data.Preferences.PrefType; import cz.destil.settleup.data.model.Currency; import cz.destil.settleup.data.model.Currency.Currencies; import cz.destil.settleup.data.model.Member; import cz.destil.settleup.data.model.Member.Members; import cz.destil.settleup.data.model.Payment; /** * Debt calculator - calculates who should pay how much to who with optional * tolerance value * * @author David Vavra */ public class DebtCalculator { public static int MAX_MEMBERS_FOR_OPTIMAL = 15; /** * Main algorithm, calculates who should send how much to who It optimizes * basic algorithm * * @param members List of members with their credit and debts * @param tolerance Money value nobody cares about * @return List of Hashmaps encoding transactions */ public static synchronized List<Debt> calculate(List<Member> members, BigDecimal tolerance, String currency) { List<Debt> results = new LinkedList<Debt>(); // reset members for (Member member : members) { member.removedFromCalculation = false; } // remove members where debts are too small (1-pairs) for (Member member : members) { if (BigDecimals.isFirstSmallerOrEqual(member.getBalanceInCalculation().abs(), tolerance)) { member.removedFromCalculation = true; } } // safety check if (Members.getSizeInCalculation(members) == 1) { return results; } // for 18 and more members alghoritm would take long time, so using just // basic alghoritm if (Members.getSizeInCalculation(members) <= MAX_MEMBERS_FOR_OPTIMAL) { // find n-pairs, starting at 2-pairs, deal with them using basic // algorithm and remove them int n = 2; while (n < Members.getSizeInCalculation(members) - 1) { CombinationGenerator generator = new CombinationGenerator(Members.getSizeInCalculation(members), n); boolean nPairFound = false; while (generator.hasMore()) { BigDecimal sum = BigDecimal.ZERO; int[] combination = generator.getNext(); for (int i = 0; i < combination.length; i++) { sum = sum.add(Members.getMemberInCalculation(members, combination[i]).getBalanceInCalculation()); } if (BigDecimals.isFirstSmallerOrEqual(sum.abs(), tolerance)) { // found n-pair - deal with them List<Member> pairedMembers = new LinkedList<Member>(); for (int i = 0; i < combination.length; i++) { pairedMembers.add(Members.getMemberInCalculation(members, combination[i])); } List<Debt> values = basicDebts(pairedMembers, tolerance, currency); results.addAll(values); // remove all paired from calculation for (Member pairedMember : pairedMembers) { pairedMember.removedFromCalculation = true; } nPairFound = true; } if (nPairFound) { break; } } if (!nPairFound) { n++; } } } // deal with what is left after removing n-pairs List<Debt> values = basicDebts(members, tolerance, currency); results.addAll(values); return results; } /** * Calculates how much each member paid and spent from the payments. */ public static synchronized BigDecimal updateBalances(Context c, List<Member> members, List<Payment> payments, String currency) { if (members.size() == 0) { return BigDecimal.ZERO; } // reset members for (Member member : members) { member.paid = BigDecimal.ZERO; member.spent = BigDecimal.ZERO; member.gave = BigDecimal.ZERO; member.received = BigDecimal.ZERO; } long groupId = members.get(0).groupId; HashMap<Long, Member> idsToMembers = new HashMap<Long, Member>(); for (Member member : members) { idsToMembers.put(member.id, member); } BigDecimal total = BigDecimal.ZERO; // for all payments for (Payment payment : payments) { if (!payment.converted && !payment.getCurrency().equals(currency)) { continue; } if (payment.forWho == null || payment.whoPaid == null) { continue; } boolean settlement = (payment.transfer || payment.purpose.equals(c.getString(R.string.debt_settlement)) || payment.purpose .equals(c.getString(R.string.paypal_settlement))); // update paid & gave value int missingMembers = 1; for (int i = 0; i < payment.whoPaid.size(); i++) { long whoPaid = payment.whoPaid.get(i); // hack when member is missing from payments if (idsToMembers.get(whoPaid) == null) { Member newMember = new Member(whoPaid, c.getString(R.string.missing_member) + " " + missingMembers, "", groupId, null); members.add(newMember); idsToMembers.put(whoPaid, newMember); missingMembers++; } if (settlement) { if (payment.converted) { idsToMembers.get(whoPaid).gave = idsToMembers.get(whoPaid).gave.add(payment.convertedAmounts.get(i)); } else { idsToMembers.get(whoPaid).gave = idsToMembers.get(whoPaid).gave.add(payment.amounts.get(i)); } } else { if (payment.converted) { idsToMembers.get(whoPaid).paid = idsToMembers.get(whoPaid).paid.add(payment.convertedAmounts.get(i)); } else { idsToMembers.get(whoPaid).paid = idsToMembers.get(whoPaid).paid.add(payment.amounts.get(i)); } } } // update spent & received values BigDecimal sumOfWeights = BigDecimal.ZERO; for (double weight : payment.weights) { sumOfWeights = sumOfWeights.add(new BigDecimal(weight)); } BigDecimal amountForOnePerson; if (payment.converted) { amountForOnePerson = BigDecimals.safeDivide(payment.getConvertedAmount(), sumOfWeights); } else { amountForOnePerson = BigDecimals.safeDivide(payment.getAmount(), sumOfWeights); } int i = 0; for (long id : payment.forWho) { // hack when member is missing from payments if (idsToMembers.get(id) == null) { Member newMember = new Member(id, c.getString(R.string.missing_member) + " " + missingMembers, "", groupId, null); members.add(newMember); idsToMembers.put(id, newMember); missingMembers++; } BigDecimal weightedAmount = amountForOnePerson.multiply(new BigDecimal(payment.weights.get(i))); if (settlement) { idsToMembers.get(id).received = idsToMembers.get(id).received.add(weightedAmount); } else { idsToMembers.get(id).spent = idsToMembers.get(id).spent.add(weightedAmount); } i++; } // Total - all payments without debts and Paypal if (!settlement) { if (payment.converted) { total = total.add(payment.getConvertedAmount()); } else { total = total.add(payment.getAmount()); } } } // copy it into calculation values for (Member member : members) { member.paidInCalculation = member.paid; member.spentInCalculation = member.spent; } return total; } /** * Not-optimal debts algorithm - it calculates debts with N-1 transactions * * @param members List of members with their credit and debts * @param tolerance Money value nobody cares about * @return List of Hashmaps encoding transactions */ private static synchronized List<Debt> basicDebts(List<Member> members, BigDecimal tolerance, String currency) { List<Debt> debts = new LinkedList<Debt>(); int resolvedMembers = 0; while (resolvedMembers < Members.getSizeInCalculation(members)) { // transaction is from lowes balance to highest balance Collections.sort(members); Member sender = Members.getMemberInCalculation(members, 0); Member recipient = Members.getLastMemberInCalculation(members); BigDecimal senderShouldSend = sender.getBalanceInCalculation().abs(); BigDecimal recipientShouldReceive = recipient.getBalanceInCalculation().abs(); BigDecimal amount; if (BigDecimals.isFirstLarger(senderShouldSend, recipientShouldReceive)) { amount = recipientShouldReceive; } else { amount = senderShouldSend; } sender.spentInCalculation = sender.spentInCalculation.subtract(amount); recipient.paidInCalculation = recipient.paidInCalculation.subtract(amount); Debt debt = new Debt(sender, recipient, amount, currency); debts.add(debt); // delete members who are settled senderShouldSend = sender.getBalanceInCalculation().abs(); recipientShouldReceive = recipient.getBalanceInCalculation().abs(); if (BigDecimals.isFirstSmallerOrEqual(senderShouldSend, tolerance)) { resolvedMembers++; } if (BigDecimals.isFirstSmallerOrEqual(recipientShouldReceive, tolerance)) { resolvedMembers++; } } // limit transactions by tolerance Iterator<Debt> iterator = debts.iterator(); while (iterator.hasNext()) { Debt debt = iterator.next(); if (BigDecimals.isFirstSmallerOrEqual(debt.amount, tolerance)) { iterator.remove(); } } return debts; } /** * Converts list of payments into common currency. * * @return if it's possible */ public static synchronized List<String> getConvertedCurrencies(List<Payment> payments, Context c) { // reset for (Payment payment : payments) { payment.converted = false; } String singleCurrency = Preferences.getString(PrefType.SINGLE_CURRENCY, c); if (!singleCurrency.equals(Preferences.MULTIPLE_CURRENCIES)) { for (Payment payment : payments) { if (payment.getCurrency().equals(singleCurrency)) { // already converted payment.convertedAmounts = payment.amounts; } else { Currency currency = Currencies.getByCode(payment.getCurrency()); if (currency == null || currency.exchangeRate <= 0 || !currency.exchangeCode.equals(singleCurrency)) { // not enough exchange rates, aborting for (Payment payment2 : payments) { payment2.converted = false; } return Currencies.getDistinctCurrencies(payments); } payment.convertedAmounts = new ArrayList<BigDecimal>(); for (BigDecimal amount : payment.amounts) { payment.convertedAmounts.add(BigDecimals.safeDivide(amount, new BigDecimal(currency.exchangeRate))); } } payment.convertedCurrency = singleCurrency; payment.converted = true; } // return only single currency List<String> justOne = new ArrayList<String>(); justOne.add(singleCurrency); return justOne; } return Currencies.getDistinctCurrencies(payments); } /** * Generates transactions which doesn't transfer any debt between people. */ public synchronized static List<Debt> simpleDebts(List<Payment> payments, List<Member> members, String currency, Context c) { List<Debt> transactions = new ArrayList<Debt>(); // traverse all payments and reverse them into debt for (Payment payment : payments) { if (!payment.converted && !payment.getCurrency().equals(currency)) { continue; } // calculate paid, spent for just one payment List<Payment> singlePayment = new ArrayList<Payment>(); singlePayment.add(payment); updateBalances(c, members, singlePayment, currency); // generate transactions using basicDebts List<Debt> debts = calculate(members, BigDecimal.ZERO, currency); // merge debts for (Debt debt : debts) { boolean found = false; Iterator<Debt> iterator = transactions.iterator(); while (iterator.hasNext()) { Debt transaction = iterator.next(); // add same debts if (debt.from.equals(transaction.from) && debt.to.equals(transaction.to)) { BigDecimal addition = transaction.amount.add(debt.amount); transaction.amount = addition; found = true; break; } // subtract opposite debts else if (debt.from.equals(transaction.to) && debt.to.equals(transaction.from)) { BigDecimal subtraction = transaction.amount.subtract(debt.amount); if (BigDecimals.isNegative(subtraction)) { // debt is negative = other way around subtraction = subtraction.negate(); transaction.to = debt.to; transaction.from = debt.from; } //if (subtraction < DOUBLE_PRECISION_TOLERANCE) { // iterator.remove(); //} else { transaction.amount = subtraction; //} found = true; break; } } if (!found) { transactions.add(debt); } } } return transactions; } /** * Class for representing debt transaction. * * @author Destil */ public static class Debt implements Comparable<Debt> { public Member from; public Member to; public BigDecimal amount; public String currency; public Debt(Member from, Member to, BigDecimal amount, String currency) { this.from = from; this.to = to; this.amount = amount; this.currency = currency; } @Override public int compareTo(Debt another) { return this.from.name.compareTo(another.from.name); } @Override public String toString() { return from.name + " -> " + to.name + ": " + amount + " " + currency; } } }
42.864935
134
0.547961
ddf990d8d71495167b1d87f6cac99795086de66c
1,873
/* * © Crown Copyright 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.nhs.hdn.common.http.client.connectionConfigurations; import org.jetbrains.annotations.NotNull; import uk.nhs.hdn.common.reflection.toString.AbstractToString; import java.net.HttpURLConnection; import java.util.Arrays; import static uk.nhs.hdn.common.VariableArgumentsHelper.copyOf; public final class CombinedConnectionConfiguration extends AbstractToString implements ConnectionConfiguration { @NotNull private final ConnectionConfiguration[] connectionConfigurations; public CombinedConnectionConfiguration(@NotNull final ConnectionConfiguration... connectionConfigurations) { this.connectionConfigurations = copyOf(connectionConfigurations); } @Override public void configure(@NotNull final HttpURLConnection httpConnection) { for (final ConnectionConfiguration connectionConfiguration : connectionConfigurations) { connectionConfiguration.configure(httpConnection); } } @NotNull public CombinedConnectionConfiguration with(@NotNull final ConnectionConfiguration connectionConfiguration) { final int length = connectionConfigurations.length; final ConnectionConfiguration[] copy = Arrays.copyOf(connectionConfigurations, length + 1); copy[length] = connectionConfiguration; return new CombinedConnectionConfiguration(copy); } }
34.054545
110
0.802456
b422414976723f5c23ac4ff187d8edbbd04e9063
326
package pl.kania.etd.graph.drop; import lombok.Value; @Value class SimpleDoubleValue implements HasValue<SimpleDoubleValue> { double value; @Override public int compareTo(SimpleDoubleValue o) { if (o == null) { return -1; } return Double.compare(value, o.getValue()); } }
20.375
64
0.634969
d4470c5c03f37c18cf1c89c53ca47a926857e5cd
1,835
// 2 package com.oddcc.leetcode.editor.cn; import com.oddcc.leetcode.editor.cn.common.ListNode; public class AddTwoNumbers { public static void main(String[] args) { Solution solution = new AddTwoNumbers().new Solution(); // ListNode n1 = solution.addTwoNumbers(new ListNode(0), new ListNode(0)); // ListNode n2 = solution.addTwoNumbers(new ListNode(2, new ListNode(4, new ListNode(3))), new ListNode(5, new ListNode(6, new ListNode(4)))); ListNode n3 = solution.addTwoNumbers(new ListNode(9, new ListNode(9, new ListNode(9))), new ListNode(9, new ListNode(9))); System.out.println("success"); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { // 模拟手动加法,需要注意的有几个,1是循环结束后,如果还有carry要记得处理,2是空指针的处理,3是循环开始和循环结束的条件 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; ListNode ans = null; ListNode n = null; while (l1 != null || l2 != null) { int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; if (sum >= 10) { carry = 1; sum = sum - 10; } else { carry = 0; } if (n == null) { ans = new ListNode(sum); n = ans; } else { n.next = new ListNode(sum); n = n.next; } l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } if (carry == 1) { n.next = new ListNode(carry); } return ans; } } //leetcode submit region end(Prohibit modification and deletion) }
37.44898
149
0.502997
6c741bf46ac4f6c036e4b2c681d97e5d4f2b3b56
2,212
package cn.hutool.core.comparator; import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import java.io.Serializable; import java.util.Comparator; import java.util.List; /** * 版本比较器<br> * 比较两个版本的大小<br> * 排序时版本从小到大排序,即比较时小版本在前,大版本在后<br> * 支持如:1.3.20.8,6.82.20160101,8.5a/8.5c等版本形式<br> * 参考:https://www.cnblogs.com/shihaiming/p/6286575.html * * @author Looly * @since 4.0.2 */ public class VersionComparator implements Comparator<String>, Serializable { private static final long serialVersionUID = 8083701245147495562L; /** 单例 */ public static final VersionComparator INSTANCE = new VersionComparator(); /** * 默认构造 */ public VersionComparator() { } // ----------------------------------------------------------------------------------------------------- /** * 比较两个版本<br> * null版本排在最小:即: * <pre> * compare(null, "v1") &lt; 0 * compare("v1", "v1") = 0 * compare(null, null) = 0 * compare("v1", null) &gt; 0 * compare("1.0.0", "1.0.2") &lt; 0 * compare("1.0.2", "1.0.2a") &lt; 0 * compare("1.13.0", "1.12.1c") &gt; 0 * compare("V0.0.20170102", "V0.0.20170101") &gt; 0 * </pre> * * @param version1 版本1 * @param version2 版本2 */ @Override public int compare(String version1, String version2) { if(ObjectUtil.equal(version1, version2)) { return 0; } if (version1 == null && version2 == null) { return 0; } else if (version1 == null) {// null视为最小版本,排在前 return -1; } else if (version2 == null) { return 1; } final List<String> v1s = StrUtil.split(version1, CharUtil.DOT); final List<String> v2s = StrUtil.split(version2, CharUtil.DOT); int diff = 0; int minLength = Math.min(v1s.size(), v2s.size());// 取最小长度值 String v1; String v2; for (int i = 0; i < minLength; i++) { v1 = v1s.get(i); v2 = v2s.get(i); // 先比较长度 diff = v1.length() - v2.length(); if (0 == diff) { diff = v1.compareTo(v2); } if(diff != 0) { //已有结果,结束 break; } } // 如果已经分出大小,则直接返回,如果未分出大小,则再比较位数,有子版本的为大; return (diff != 0) ? diff : v1s.size() - v2s.size(); } }
24.853933
106
0.56736
d4b56703e693a7f8507d89ed79ab93de92666080
313
package reinmind.strategy; public class Item { String upCode; int price; public Item(String upCode, int price) { this.upCode = upCode; this.price = price; } public String getUpCode() { return upCode; } public int getPrice() { return price; } }
14.904762
43
0.571885
2ac6c88915513b6f3de81ebbb3c5b268499721f6
2,769
/* * (C) Copyright 2014-2015 Nuxeo SA (http://nuxeo.com/) and others. * * 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: * Thierry Delprat * Florent Guillaume */ package org.nuxeo.ecm.core.redis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.core.redis.contribs.RedisUIDSequencer; import org.nuxeo.ecm.core.test.CoreFeature; import org.nuxeo.ecm.core.uidgen.UIDGeneratorService; import org.nuxeo.ecm.core.uidgen.UIDSequencer; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; @RunWith(FeaturesRunner.class) @Features({ CoreFeature.class, RedisFeature.class }) @Deploy("org.nuxeo.ecm.core.redis.tests:test-uidsequencer-contrib.xml") public class TestRedisUIDSequencer { @Inject protected UIDGeneratorService service; @Test public void testRedisUIDSequencer() throws Exception { UIDSequencer sequencer = service.getSequencer("redisSequencer"); assertNotNull(sequencer); assertTrue(sequencer instanceof RedisUIDSequencer); sequencer.init(); // not correctly done in tests TODO fix this assertEquals(1L, sequencer.getNextLong("A")); assertEquals(2L, sequencer.getNextLong("A")); assertEquals(1, sequencer.getNext("B")); assertEquals(3L, sequencer.getNextLong("A")); assertEquals(2, sequencer.getNext("B")); sequencer.initSequence("A", 100000L); assertEquals(100001L, sequencer.getNextLong("A")); } @Test public void testBlockOfSequences() { UIDSequencer seq = service.getSequencer(); String key = "blockKey"; int size = 1000; seq.initSequence(key, 0L); List<Long> block = seq.getNextBlock(key, size); assertNotNull(block); assertEquals(size, block.size()); assertTrue(block.get(0) < block.get(1)); assertTrue(block.get(size - 2) < block.get(size - 1)); assertTrue(block.get(size - 1) < seq.getNextLong(key)); } }
35.050633
75
0.711809
2ad2b51c5c43764ff36cd35ccc7880e179432637
195
package io.vertx.zero.marshal.reliable; interface Rules { /** **/ String REQUIRED = "required"; /** **/ String TYPED = "typed"; /** **/ String FORBIDDEN = "forbidden"; }
17.727273
39
0.558974
2219d1069f17f359fad07b04c6fb1ab2b5bc2f3f
2,384
package org.rongji.dfish.misc.pinyin; import java.util.HashMap; import java.util.Map; class KeyValuePair { KeyValuePair(char c){ key=c; } public FindResult match(char[] content, int begin, int end) { char c=content[end]; FindResult result=new FindResult(FindResult.STATE_UNMATCH,begin,end); if(children==null){ return result; } KeyValuePair p=children.get(c); if(p==null){ return result; }else{ if(p.wordFinish){ result.state=FindResult.STATE_MATCH; result.end=end; result.begin=end-1; result.replaceTo=p.replaceTo; //找到一个匹配项,如果没有更长的将使用这个匹配项。 //不能直接return; } if(p.children!=null){ if(end-1>begin){ FindResult subMatch=p.match(content, begin, end-1); if(subMatch.state==FindResult.STATE_MATCH){ result.state=FindResult.STATE_MATCH; result.end=end; result.begin=subMatch.begin; result.replaceTo=subMatch.replaceTo; return result; } } } } return result; } public void setKeyValue(String keyWord, String replaceTo) { setKeyValue(keyWord.toCharArray(),-1,keyWord.length()-1,replaceTo); } void setKeyValue(char[] charArray,int begin,int end, String replaceTo) { if(end-begin<=0)return; if(children==null){ children=new HashMap<Character , KeyValuePair>(); } char c=charArray[end]; KeyValuePair sub=children.get(c); if(sub==null){ sub=new KeyValuePair(c); children.put(c, sub); } if( end-begin ==1){ sub.wordFinish=true; sub.replaceTo=replaceTo; }else{ sub.setKeyValue(charArray, begin,end-1,replaceTo); } } char key; boolean wordFinish; String replaceTo; HashMap<Character , KeyValuePair> children; public void show() { StringBuilder sb=new StringBuilder(); show(sb); System.out.println(sb); } void show(StringBuilder sb) { sb.append('{'); boolean begin=true; if(wordFinish){ if(begin){begin=false;}else{sb.append(',');} sb.append("\"replaceTo\":\""); sb.append(replaceTo); sb.append('\"'); } if(children!=null){ for(Map.Entry<Character , KeyValuePair> entry:children.entrySet()){ if(begin){begin=false;}else{sb.append(',');} sb.append('"'); sb.append(entry.getKey()); sb.append('"'); sb.append(':'); entry.getValue().show(sb); } } sb.append('}'); } }
24.326531
74
0.632131
9858be4d7a5b7fff4c67084a95906eefd0f2b759
765
package com.ad.miningobserver.exception.boundary; import com.ad.miningobserver.client.AbstractClient; import com.ad.miningobserver.exception.control.ExceptionPath; import com.ad.miningobserver.exception.entity.ExceptionError; import org.springframework.stereotype.Component; /** * Client interface for the exception package. */ @Component public class ExceptionClient extends AbstractClient { /** * POST exception errors to the remote server. * * @param exceptionError */ public boolean postException(final ExceptionError exceptionError) { final String endpoint = new ExceptionPath(super.containerPath) .buildExceptionPath(super.hostName); return super.postToEndpoint(endpoint, exceptionError); } }
30.6
71
0.754248
74c42d52b48dad2127867c63cb5c6a1563489628
7,088
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo 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, version 3. iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; import java.awt.Color; import igeo.gui.*; /** Cylinder surface class @author Satoru Sugihara */ public class ICylinder extends ISurface{ public IVecI pt1, pt2; public IDoubleI radius1, radius2; public ICylinder(IVecI pt1, IVecI pt2, double radius){ this(null,pt1,pt2,radius,radius); } public ICylinder(IServerI s, IVecI pt1, IVecI pt2, double radius){ this(s,pt1,pt2,radius,radius); } public ICylinder(IVecI pt1, IVecI pt2, double radius1, double radius2){ this(null,pt1,pt2,radius1,radius2); } public ICylinder(IVecI pt1, IVecI pt2, IDoubleI radius){ this(null,pt1,pt2,radius,radius); } public ICylinder(IServerI s, IVecI pt1, IVecI pt2, IDoubleI radius){ this(s,pt1,pt2,radius,radius); } public ICylinder(IServerI s, IVecI pt1, IVecI pt2, double radius1, double radius2){ this(s,pt1,pt2,new IDouble(radius1),new IDouble(radius2)); } public ICylinder(IVecI pt1, IVecI pt2, IDoubleI radius1, IDoubleI radius2){ this(null,pt1,pt2,radius1,radius2); } public ICylinder(IServerI s, IVecI pt1, IVecI pt2, IDoubleI radius1, IDoubleI radius2){ super(s); this.pt1 = pt1; this.pt2 = pt2; this.radius1 = radius1; this.radius2 = radius2; initCylinder(s); } public void initCylinder(IServerI s){ IVec p1 = pt1.get(); IVec p2 = pt2.get(); IVec normal = p2.diff(p1); IVec[][] cpts = new IVec[2][]; cpts[0] = ICircleGeo.circleCP(p1,normal,radius1.x()); cpts[1] = ICircleGeo.circleCP(p2,normal,radius2.x()); surface = new ISurfaceGeo(cpts, 1,ICircleGeo.circleDeg(), INurbsGeo.createKnots(1,2), ICircleGeo.circleKnots()); //IVec roll = normal.cross(IVec.zaxis); //cpts[0] = ICircleGeo.circleCPApprox(pt1,normal,roll,radius1,radius1); //cpts[1] = ICircleGeo.circleCPApprox(pt2,normal,roll,radius2,radius2); //surface = new ISurfaceGeo(cpts, 1, ICircleGeo.circleDeg()); super.initSurface(s); } /****************************************************************************** * IObject methods ******************************************************************************/ public ICylinder name(String nm){ super.name(nm); return this; } public ICylinder layer(ILayer l){ super.layer(l); return this; } public ICylinder layer(String l){ super.layer(l); return this; } public ICylinder attr(IAttribute at){ super.attr(at); return this; } public ICylinder hide(){ super.hide(); return this; } public ICylinder show(){ super.show(); return this; } public ICylinder clr(IColor c){ super.clr(c); return this; } public ICylinder clr(IColor c, int alpha){ super.clr(c,alpha); return this; } public ICylinder clr(IColor c, float alpha){ super.clr(c,alpha); return this; } public ICylinder clr(IColor c, double alpha){ super.clr(c,alpha); return this; } public ICylinder clr(Color c){ super.clr(c); return this; } public ICylinder clr(Color c, int alpha){ super.clr(c,alpha); return this; } public ICylinder clr(int gray){ super.clr(gray); return this; } public ICylinder clr(float fgray){ super.clr(fgray); return this; } public ICylinder clr(double dgray){ super.clr(dgray); return this; } public ICylinder clr(int gray, int alpha){ super.clr(gray,alpha); return this; } public ICylinder clr(float fgray, float falpha){ super.clr(fgray,falpha); return this; } public ICylinder clr(double dgray, double dalpha){ super.clr(dgray,dalpha); return this; } public ICylinder clr(int r, int g, int b){ super.clr(r,g,b); return this; } public ICylinder clr(float fr, float fg, float fb){ super.clr(fr,fg,fb); return this; } public ICylinder clr(double dr, double dg, double db){ super.clr(dr,dg,db); return this; } public ICylinder clr(int r, int g, int b, int a){ super.clr(r,g,b,a); return this; } public ICylinder clr(float fr, float fg, float fb, float fa){ super.clr(fr,fg,fb,fa); return this; } public ICylinder clr(double dr, double dg, double db, double da){ super.clr(dr,dg,db,da); return this; } public ICylinder hsb(float h, float s, float b, float a){ super.hsb(h,s,b,a); return this; } public ICylinder hsb(double h, double s, double b, double a){ super.hsb(h,s,b,a); return this; } public ICylinder hsb(float h, float s, float b){ super.hsb(h,s,b); return this; } public ICylinder hsb(double h, double s, double b){ super.hsb(h,s,b); return this; } public ICylinder setColor(Color c){ super.setColor(c); return this; } public ICylinder setColor(Color c, int alpha){ super.setColor(c,alpha); return this; } public ICylinder setColor(int gray){ super.setColor(gray); return this; } public ICylinder setColor(float fgray){ super.setColor(fgray); return this; } public ICylinder setColor(double dgray){ super.setColor(dgray); return this; } public ICylinder setColor(int gray, int alpha){ super.setColor(gray,alpha); return this; } public ICylinder setColor(float fgray, float falpha){ super.setColor(fgray,falpha); return this; } public ICylinder setColor(double dgray, double dalpha){ super.setColor(dgray,dalpha); return this; } public ICylinder setColor(int r, int g, int b){ super.setColor(r,g,b); return this; } public ICylinder setColor(float fr, float fg, float fb){ super.setColor(fr,fg,fb); return this; } public ICylinder setColor(double dr, double dg, double db){ super.setColor(dr,dg,db); return this; } public ICylinder setColor(int r, int g, int b, int a){ super.setColor(r,g,b,a); return this; } public ICylinder setColor(float fr, float fg, float fb, float fa){ super.setColor(fr,fg,fb,fa); return this; } public ICylinder setColor(double dr, double dg, double db, double da){ super.setColor(dr,dg,db,da); return this; } public ICylinder setHSBColor(float h, float s, float b, float a){ super.setHSBColor(h,s,b,a); return this; } public ICylinder setHSBColor(double h, double s, double b, double a){ super.setHSBColor(h,s,b,a); return this; } public ICylinder setHSBColor(float h, float s, float b){ super.setHSBColor(h,s,b); return this; } public ICylinder setHSBColor(double h, double s, double b){ super.setHSBColor(h,s,b); return this; } public ICylinder weight(double w){ super.weight(w); return this; } public ICylinder weight(float w){ super.weight(w); return this; } }
47.57047
118
0.678894
a324b21a45bd081c1604c00ba1be49dd0f6ad234
6,400
package net.remisan.base.repository; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import net.remisan.base.model.mock.TestMock; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; @ContextConfiguration("file:src/test/resources/root-context.xml") @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class RepositoryTest { @Autowired private Repository<TestMock> repository; @Test public void testNotFound() { TestMock c = this.repository.findOne(new Long(99)); Assert.assertNull(c); } @Test public void test() throws Exception { // Entity TestMock entity = this.repository.getNewInstance(); entity.setName("name"); entity.setDummy("dummy"); entity.setFoo("foo"); entity.setBar("bar"); Assert.assertNull(entity.getId()); entity.setId(null); Assert.assertNull(entity.getId()); Assert.assertEquals("name", entity.getName()); Assert.assertEquals("dummy", entity.getDummy()); Assert.assertEquals("foo", entity.getFoo()); Assert.assertEquals("bar", entity.getBar()); TestMock persistableEntity = this.repository.getPersistable(entity); Assert.assertEquals(entity, persistableEntity); // Save List<TestMock> persistEntities = new ArrayList<TestMock>(); persistEntities.add(persistableEntity); List<TestMock> persistedEntities = this.repository.save(persistEntities); Assert.assertNotNull(entity.getId()); Assert.assertTrue(persistedEntities.contains(entity)); final Long id = entity.getId(); TestMock persistedEntity = this.repository.saveAndFlush(persistableEntity); Assert.assertEquals(entity, persistedEntity); //Select One TestMock selectedEntity = this.repository.getOne(id); Assert.assertEquals(entity, selectedEntity); Specification<TestMock> specId = new Specification<TestMock>() { public Predicate toPredicate(Root<TestMock> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.get("id"), id); } }; selectedEntity = this.repository.findOne(specId); Assert.assertEquals(entity, selectedEntity); // Exists Assert.assertTrue(this.repository.exists(id)); Assert.assertFalse(this.repository.exists(-1L)); Assert.assertEquals(1, this.repository.count()); // Select All List<TestMock> entities = this.repository.findAll(); Assert.assertEquals(1, entities.size()); List<Order> orders = new ArrayList<Sort.Order>(); orders.add(new Order("name")); orders.add(new Order(Direction.DESC, "foo")); Sort sort = new Sort(orders); entities = this.repository.findAll(sort); Assert.assertEquals(1, entities.size()); List<Long> ids = new ArrayList<Long>(); ids.add(id); entities = this.repository.findAll(ids); Assert.assertEquals(1, entities.size()); // Pagination Specification<TestMock> specFoo = new Specification<TestMock>() { public Predicate toPredicate(Root<TestMock> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.get("foo"), "foo"); } }; Pageable pageable = new PageRequest(0, 10, sort); Page<TestMock> pagedEntities = this.repository.findAll(specFoo, pageable); Assert.assertEquals(1, pagedEntities.getContent().size()); Assert.assertEquals(1, pagedEntities.getTotalElements()); Assert.assertEquals(1, pagedEntities.getTotalPages()); pagedEntities = this.repository.findAll(pageable); Assert.assertEquals(1, pagedEntities.getContent().size()); Assert.assertEquals(1, pagedEntities.getTotalElements()); Assert.assertEquals(1, pagedEntities.getTotalPages()); // Delete List<TestMock> persist = new ArrayList<TestMock>(); persist.add(new TestMock("1")); persist.add(new TestMock("2")); persist.add(new TestMock("3")); persist.add(new TestMock("4")); this.repository.save(persist); entities = this.repository.findAll(); Assert.assertEquals(5, entities.size()); TestMock toDelete = new TestMock("5"); this.repository.save(toDelete); Long toDeleteId = toDelete.getId(); TestMock toDelete2 = new TestMock("6"); this.repository.save(toDelete2); Long toDeleteId2 = toDelete2.getId(); entities = this.repository.findAll(); Assert.assertEquals(7, entities.size()); this.repository.delete(toDelete); Assert.assertFalse(this.repository.exists(toDeleteId)); this.repository.delete(toDeleteId2); Assert.assertFalse(this.repository.exists(toDeleteId2)); entities = this.repository.findAll(); Assert.assertEquals(5, entities.size()); this.repository.deleteInBatch(persist); entities = this.repository.findAll(); Assert.assertEquals(1, entities.size()); Assert.assertTrue(this.repository.exists(id)); this.repository.deleteAllInBatch(); entities = this.repository.findAll(); Assert.assertEquals(0, entities.size()); } }
37.426901
107
0.654531
cd45fb057ff86ab73c47c2acf35bdbe64aac8fc5
975
package org.cjzheng01.inventory.reactor; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class ReactorTest { @Test public void test1() { List<String> list = new ArrayList<>(3); list.add("one"); list.add("two"); list.add("three"); Flux<String> flux = Flux.fromIterable(list); flux.collect(Collectors.toList()).subscribe(res -> { res.forEach(System.out::println); }); } @Test public void test2() { List<String> list = new ArrayList<>(3); list.add("one"); list.add("two"); list.add("three"); Mono<List<String>> mono = Mono.just(list); mono.map(res -> res.stream().map(String::toUpperCase) ).subscribe(res -> { res.forEach(System.out::println); }); } }
24.375
60
0.582564
33908251aaed13983ded8fc77e4a9b3c07d821df
2,797
package slogo.View; import java.util.List; import java.util.ResourceBundle; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import java.util.ArrayList; import slogo.Main; public class CommandHistory implements HistoryView { private ResourceBundle myResources = Main.MY_RESOURCES; private ListView historyWindow; private static final Color TEXT_COLOR = Color.BLACK; private HBox newCommand; private ViewButton runButton; private Label commandEntered; private static final int HEIGHT = 310; private static final int ONE_CONSTANT = 1; private static final int NEW_HEIGHT = 200; private static final int WIDTH = 300; private static final int PLAY_IMAGE_SIZE = 10; private static final int PLAY_IMAGE_SIZE_IN_HBOX = 20; private static final int FONT_SIZE = 0; private static final int SPACING = 5; private ArrayList<String> commandValues; private static final String STYLE = "Style"; private static final String RUN_BUTTON = "PlayImage"; private static final String EMPTY = ""; public CommandHistory() { commandValues = new ArrayList<>(); historyWindow = new ListView(); historyWindow.setBackground(Background.EMPTY); historyWindow.setStyle(myResources.getString(STYLE)); historyWindow.setPrefHeight(HEIGHT); historyWindow.setPrefWidth(WIDTH); } protected List<String> getCommandListCopy() { List<String> copy = new ArrayList<String>(commandValues); return copy; } protected void removeCommand() { commandValues.remove(commandValues.size() - ONE_CONSTANT); } protected void makeBox(String StringRepresentation) { runButton = new ViewButton(EMPTY, PLAY_IMAGE_SIZE_IN_HBOX, PLAY_IMAGE_SIZE_IN_HBOX, FONT_SIZE); setImage(runButton, myResources.getString(RUN_BUTTON)); commandValues.add(StringRepresentation); newCommand = new HBox(SPACING); newCommand.setMaxSize(WIDTH, NEW_HEIGHT); commandEntered = new Label(StringRepresentation); commandEntered.setTextFill(TEXT_COLOR); newCommand.getChildren().addAll(runButton, commandEntered); newCommand.setAccessibleText(StringRepresentation); historyWindow.getItems().add(newCommand); } private void setImage(ViewButton button, String image) { Image img = new Image(image); ImageView buttonImage = new ImageView(img); buttonImage.setFitHeight(PLAY_IMAGE_SIZE); buttonImage.setFitWidth(PLAY_IMAGE_SIZE); button.setGraphic(buttonImage); } public ListView returnScene() { return historyWindow; } public Button returnButton() { return runButton; } }
32.149425
99
0.763318
b224ced9014b454c5cd6c32a05b528740437b43d
4,905
package pl.coderslab.cls_wms_app.service.wmsSettings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.coderslab.cls_wms_app.app.SecurityUtils; import pl.coderslab.cls_wms_app.app.TimeUtils; import pl.coderslab.cls_wms_app.entity.EmailRecipients; import pl.coderslab.cls_wms_app.repository.CompanyRepository; import pl.coderslab.cls_wms_app.repository.EmailRecipientsRepository; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; @Service public class EmailRecipientsServiceImpl implements EmailRecipientsService{ private final EmailRecipientsRepository emailRecipientsRepository; private final CompanyRepository companyRepository; @Autowired public EmailRecipientsServiceImpl(EmailRecipientsRepository emailRecipientsRepository, CompanyRepository companyRepository) { this.emailRecipientsRepository = emailRecipientsRepository; this.companyRepository = companyRepository; } @Override public void add(EmailRecipients emailRecipients) { emailRecipients.setToken(SecurityUtils.uuidToken()); emailRecipientsRepository.save(emailRecipients); } @Override public void saveFromForm(EmailRecipients emailRecipients) { emailRecipients.setToken(SecurityUtils.uuidToken()); emailRecipients.setActive(true); emailRecipients.setCreated(TimeUtils.timeNowLong()); emailRecipients.setLast_update(TimeUtils.timeNowLong()); emailRecipients.setChangeBy(SecurityUtils.usernameForActivations()); if(emailRecipients.getCompany()==null) { emailRecipients.setCompany(companyRepository.getOneCompanyByUsername(SecurityUtils.usernameForActivations())); } emailRecipients.setChangeBy(SecurityUtils.usernameForActivations()); emailRecipientsRepository.save(emailRecipients); } @Override public void editFromForm(EmailRecipients emailRecipients) { emailRecipients.setId(emailRecipientsRepository.getEmailRecipientsByToken(emailRecipients.getToken()).getId()); emailRecipients.setActive(emailRecipientsRepository.getEmailRecipientsByToken(emailRecipients.getToken()).isActive()); emailRecipients.setCreated(TimeUtils.timeNowLong()); emailRecipients.setLast_update(TimeUtils.timeNowLong()); emailRecipients.setChangeBy(SecurityUtils.usernameForActivations()); if(emailRecipients.getCompany()==null) { emailRecipients.setCompany(companyRepository.getOneCompanyByUsername(SecurityUtils.usernameForActivations())); } emailRecipients.setChangeBy(SecurityUtils.usernameForActivations()); emailRecipients.setToken(SecurityUtils.uuidToken()); emailRecipientsRepository.save(emailRecipients); } @Override public List<EmailRecipients> getEmailRecipientsForCompanyByUsername(String username) { return emailRecipientsRepository.getEmailRecipientsForCompanyByUsername(username); } @Override public List<EmailRecipients> getEmailRecipients() { return emailRecipientsRepository.getEmailRecipients(); } @Override public EmailRecipients findByToken(String token) { return emailRecipientsRepository.getEmailRecipientsByToken(token); } @Override public void deactivate(String token) { EmailRecipients emailRecipients = emailRecipientsRepository.getEmailRecipientsByToken(token); emailRecipients.setActive(false); emailRecipients.setLast_update(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)); emailRecipients.setChangeBy(SecurityUtils.usernameForActivations()); emailRecipientsRepository.save(emailRecipients); } @Override public void activate(String token) { EmailRecipients emailRecipients = emailRecipientsRepository.getEmailRecipientsByToken(token); emailRecipients.setActive(true); emailRecipients.setLast_update(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)); emailRecipients.setChangeBy(SecurityUtils.usernameForActivations()); emailRecipientsRepository.save(emailRecipients); } @Override public List<EmailRecipients> getEmailRecipientsByCompanyForShipmentType(String company, String type) { return emailRecipientsRepository.getEmailRecipientsByCompanyForShipmentType(company, type); } @Override public List<EmailRecipients> getEmailRecipientsByCompanyForReceptionType(String company, String type) { return emailRecipientsRepository.getEmailRecipientsByCompanyForReceptionType(company, type); } @Override public List<EmailRecipients> getEmailRecipientsByCompanyForStockType(String type, String company) { return emailRecipientsRepository.getEmailRecipientsByCompanyForStockType(type,company); } }
44.189189
129
0.78104
48fc0c767750d46757caf746fcc99c9e09013386
701
package com.avans.AvansMovieApp.Utilities.FetchingUtilities; import com.avans.AvansMovieApp.Model.CompactMovie; import com.avans.AvansMovieApp.Model.Review; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; public class ReviewTest { private Review review; //Arrange @Test public void testOrSomething() { this.review = new Review( "AuthorAttr", "ContentAttr" ); //Act String authorAttr = review.getAuthor(); String contentAttr = review.getContent(); //Assert Assert.assertEquals(authorAttr, "AuthorAttr"); Assert.assertEquals(contentAttr, "ContentAttr"); } }
18.945946
60
0.661912
5e2391a3319c081c934e4fc9c66c1b99d3d8f4fc
6,309
/* * 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 ec.edu.espe.saturn.service; import ec.edu.espe.saturn.dao.DAOServices; import ec.edu.espe.saturn.dao.QueryParameter; import ec.edu.espe.saturn.logger.L; import ec.edu.espe.saturn.model.Pebempl; import ec.edu.espe.saturn.util.HibernateUtil; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; /** * * @author Pcmaster2 */ public class PebemplService { private final static L log = new L(PebemplService.class); public static List<Pebempl> FindByPIDM(int pebemplPidm) { List<Pebempl> pebemplist = new ArrayList<>(); try { String sql = "SELECT * FROM PAYROLL.PEBEMPL WHERE PEBEMPL_PIDM=" + pebemplPidm; List<Object[]> list = HibernateUtil. getSessionFactory().getCurrentSession().createSQLQuery(sql).list(); if (!list.isEmpty()) { for (Object[] obj : list) { Pebempl pebempl = new Pebempl(); BigDecimal pidm = null; pidm = (BigDecimal) obj[0]; pebempl.setPebemplPidm((int) pidm.intValue()); pebempl.setPebemplEmplStatus((String) obj[1]); pebempl.setPebemplCoasCodeHome((String) obj[2]); pebempl.setPebemplOrgnCodeHome((String) obj[3]); pebempl.setPebemplCoasCodeDist((String) obj[4]);// pebempl.setPebemplOrgnCodeDist((String) obj[5]);// pebempl.setPebemplEclsCode((String) obj[6]); pebempl.setPebemplLcatCode((String) obj[7]); pebempl.setPebemplBcatCode((String) obj[8]); pebempl.setPebemplFirstHireDate((Date) obj[9]); pebempl.setPebemplCurrentHireDate((Date) obj[10]); pebempl.setPebemplAdjServiceDate((Date) obj[11]); pebempl.setPebemplSeniorityDate((Date) obj[12]); pebempl.setPebemplLreaCode((String) obj[13]); pebempl.setPebemplLoaBegDate((Date) obj[14]); pebempl.setPebemplLoaEndDate((Date) obj[15]);// pebempl.setPebemplTreaCode((String) obj[16]); pebempl.setPebemplTermDate((Date) obj[17]); pebempl.setPebemplI9FormInd((String) obj[18]); pebempl.setPebemplI9Date((Date) obj[19]); pebempl.setPebemplI9ExpireDate((Date) obj[20]); pebempl.setPebemplActivityDate((Date) obj[21]); pebempl.setPebemplWkprCode((String) obj[22]); pebempl.setPebemplFlsaInd((String) obj[23]); pebempl.setPebemplStgrCode((String) obj[24]); Object sshort = obj[25]; if(sshort==null)sshort=0; String objshort = sshort.toString(); pebempl.setPebemplDaysInCanada(Short.parseShort(objshort)); pebempl.setPebempl1042RecipientCd((String) obj[26]); pebempl.setPebemplInternalFtPtInd((String) obj[27]); pebempl.setPebemplDicdCode((String) obj[28]); pebempl.setPebemplEgrpCode((String) obj[29]); pebempl.setPebemplIpedsSoftMoneyInd((String) obj[30]); pebempl.setPebemplFirstWorkDate((Date) obj[31]); pebempl.setPebemplLastWorkDate((Date) obj[32]); pebempl.setPebemplCalifPensionInd((String) obj[33]); pebempl.setPebemplNrsiCode((String) obj[34]); pebempl.setPebemplSsnLastName((String) obj[35]); pebempl.setPebemplSsnFirstName((String) obj[36]); pebempl.setPebemplSsnMi((String) obj[37]); pebempl.setPebemplSsnSuffix((String) obj[38]); pebempl.setPebemplJblnCode((String) obj[39]); pebempl.setPebemplCollCode((String) obj[40]); pebempl.setPebemplCampCode((String) obj[41]); pebempl.setPebemplUserId((String) obj[42]); pebempl.setPebemplDataOrigin((String) obj[43]); pebempl.setPebemplEw2ConsentInd((String) obj[44]); pebempl.setPebemplEw2ConsentDate((Date) obj[45]); pebempl.setPebemplEw2ConsentUserId((String) obj[46]); pebempl.setPebemplIpedsPrimaryFunction((String) obj[47]); pebempl.setPebemplIpedsMedDentalInd((String) obj[48]); pebempl.setPebemplEtaxConsentInd((String) obj[49]); pebempl.setPebemplEtaxConsentDate((Date) obj[50]); pebempl.setPebemplEtaxConsentUserId((String) obj[51]); pebemplist.add(pebempl); } } else { pebemplist = null; } } catch (HibernateException ex) { log.level.info("FindByPIDM : " + ex.getMessage()); } return pebemplist; } public static Pebempl findByPIDM_H(int sgbstdnPidm) { Pebempl findmPebempl = null; try { DAOServices ds = new DAOServices(HibernateUtil. getSessionFactory().getCurrentSession()); QueryParameter query_1 = new QueryParameter(QueryParameter.$TYPE_WHERE); query_1.setColumnName("pebemplPidm"); query_1.setWhereClause("="); query_1.setValue(sgbstdnPidm); List parameList = new ArrayList(); parameList.add(query_1); List<Pebempl> listPebempl = ds.customQuery(parameList, Pebempl.class); if (!listPebempl.isEmpty()) { findmPebempl = listPebempl.get(0); } } catch (HibernateException ex) { log.level.info("FindByPIDM : " + ex.getMessage()); } return findmPebempl; } }
49.289063
92
0.563322
768d7a906fd29bdf1aaf08752f1798ce9b900abd
10,525
package com.simibubi.create.content.contraptions.components.structureMovement; import java.util.HashMap; import java.util.Map; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.contraptions.components.actors.BlockBreakingMovementBehaviour; import net.minecraft.block.BlockState; import net.minecraft.block.CocoaBlock; import net.minecraft.block.material.PushReaction; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.IProjectile; import net.minecraft.entity.MoverType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.Direction.Axis; import net.minecraft.util.Direction.AxisDirection; import net.minecraft.util.ReuseableStream; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.shapes.ISelectionContext; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.world.World; import net.minecraft.world.gen.feature.template.Template.BlockInfo; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.DistExecutor; public class ContraptionCollider { static Map<Object, AxisAlignedBB> renderedBBs = new HashMap<>(); public static boolean wasClientPlayerGrounded; public static void collideEntities(ContraptionEntity contraptionEntity) { if (Contraption.isFrozen()) return; if (!contraptionEntity.collisionEnabled()) return; World world = contraptionEntity.getEntityWorld(); Vec3d contraptionMotion = contraptionEntity.getMotion(); Contraption contraption = contraptionEntity.getContraption(); AxisAlignedBB bounds = contraptionEntity.getBoundingBox(); Vec3d contraptionPosition = contraptionEntity.getPositionVec(); contraptionEntity.collidingEntities.clear(); if (contraption == null) return; if (bounds == null) return; for (Entity entity : world.getEntitiesWithinAABB((EntityType<?>) null, bounds.grow(1), e -> canBeCollidedWith(e))) { ReuseableStream<VoxelShape> potentialHits = getPotentiallyCollidedShapes(world, contraption, contraptionPosition, entity); if (potentialHits.createStream().count() == 0) continue; Vec3d positionOffset = contraptionPosition.scale(-1); AxisAlignedBB entityBB = entity.getBoundingBox().offset(positionOffset).grow(1.0E-7D); Vec3d entityMotion = entity.getMotion(); Vec3d relativeMotion = entityMotion.subtract(contraptionMotion); Vec3d allowedMovement = Entity.getAllowedMovement(relativeMotion, entityBB, world, ISelectionContext.forEntity(entity), potentialHits); potentialHits.createStream() .forEach(voxelShape -> pushEntityOutOfShape(entity, voxelShape, positionOffset, contraptionMotion)); contraptionEntity.collidingEntities.add(entity); if (allowedMovement.equals(relativeMotion)) continue; if (allowedMovement.y != relativeMotion.y) { entity.handleFallDamage(entity.fallDistance, 1); entity.fallDistance = 0; entity.onGround = true; DistExecutor.runWhenOn(Dist.CLIENT, () -> () -> checkForClientPlayerCollision(entity)); } if (entity instanceof ServerPlayerEntity) ((ServerPlayerEntity) entity).connection.floatingTickCount = 0; if (entity instanceof PlayerEntity && !world.isRemote) return; entity.setMotion(allowedMovement.add(contraptionMotion)); entity.velocityChanged = true; } } public static boolean canBeCollidedWith(Entity e) { if (e instanceof PlayerEntity && e.isSpectator()) return false; if (e.noClip) return false; if (e instanceof IProjectile) return false; return e.getPushReaction() == PushReaction.NORMAL; } @OnlyIn(Dist.CLIENT) private static void checkForClientPlayerCollision(Entity entity) { if (entity != Minecraft.getInstance().player) return; wasClientPlayerGrounded = true; } public static void pushEntityOutOfShape(Entity entity, VoxelShape voxelShape, Vec3d positionOffset, Vec3d shapeMotion) { AxisAlignedBB entityBB = entity.getBoundingBox().offset(positionOffset); Vec3d entityMotion = entity.getMotion(); if (!voxelShape.toBoundingBoxList().stream().anyMatch(entityBB::intersects)) return; AxisAlignedBB shapeBB = voxelShape.getBoundingBox(); Direction bestSide = Direction.DOWN; double bestOffset = 100; double finalOffset = 0; for (Direction face : Direction.values()) { Axis axis = face.getAxis(); double d = axis == Axis.X ? entityBB.getXSize() + shapeBB.getXSize() : axis == Axis.Y ? entityBB.getYSize() + shapeBB.getYSize() : entityBB.getZSize() + shapeBB.getZSize(); d = d + .5f; Vec3d nudge = new Vec3d(face.getDirectionVec()).scale(d); AxisAlignedBB nudgedBB = entityBB.offset(nudge.getX(), nudge.getY(), nudge.getZ()); double nudgeDistance = face.getAxisDirection() == AxisDirection.POSITIVE ? -d : d; double offset = voxelShape.getAllowedOffset(face.getAxis(), nudgedBB, nudgeDistance); double abs = Math.abs(nudgeDistance - offset); if (abs < Math.abs(bestOffset) && abs != 0) { bestOffset = abs; finalOffset = abs; bestSide = face; } } if (bestOffset != 0) { entity.move(MoverType.SELF, new Vec3d(bestSide.getDirectionVec()).scale(finalOffset)); boolean positive = bestSide.getAxisDirection() == AxisDirection.POSITIVE; double clamped; switch (bestSide.getAxis()) { case X: clamped = positive ? Math.max(shapeMotion.x, entityMotion.x) : Math.min(shapeMotion.x, entityMotion.x); entity.setMotion(clamped, entityMotion.y, entityMotion.z); break; case Y: clamped = positive ? Math.max(shapeMotion.y, entityMotion.y) : Math.min(shapeMotion.y, entityMotion.y); if (bestSide == Direction.UP) clamped = shapeMotion.y; entity.setMotion(entityMotion.x, clamped, entityMotion.z); entity.handleFallDamage(entity.fallDistance, 1); entity.fallDistance = 0; entity.onGround = true; break; case Z: clamped = positive ? Math.max(shapeMotion.z, entityMotion.z) : Math.min(shapeMotion.z, entityMotion.z); entity.setMotion(entityMotion.x, entityMotion.y, clamped); break; } } } public static ReuseableStream<VoxelShape> getPotentiallyCollidedShapes(World world, Contraption contraption, Vec3d contraptionPosition, Entity entity) { AxisAlignedBB blockScanBB = entity.getBoundingBox().offset(contraptionPosition.scale(-1)).grow(.5f); BlockPos min = new BlockPos(blockScanBB.minX, blockScanBB.minY, blockScanBB.minZ); BlockPos max = new BlockPos(blockScanBB.maxX, blockScanBB.maxY, blockScanBB.maxZ); ReuseableStream<VoxelShape> potentialHits = new ReuseableStream<>(BlockPos.getAllInBox(min, max).filter(contraption.blocks::containsKey).map(p -> { BlockState blockState = contraption.blocks.get(p).state; BlockPos pos = contraption.blocks.get(p).pos; VoxelShape collisionShape = blockState.getCollisionShape(world, p); return collisionShape.withOffset(pos.getX(), pos.getY(), pos.getZ()); })); return potentialHits; } public static boolean collideBlocks(ContraptionEntity contraptionEntity) { if (Contraption.isFrozen()) return true; if (!contraptionEntity.collisionEnabled()) return false; World world = contraptionEntity.getEntityWorld(); Vec3d motion = contraptionEntity.getMotion(); Contraption contraption = contraptionEntity.getContraption(); AxisAlignedBB bounds = contraptionEntity.getBoundingBox(); Vec3d position = contraptionEntity.getPositionVec(); BlockPos gridPos = new BlockPos(position); if (contraption == null) return false; if (bounds == null) return false; if (motion.equals(Vec3d.ZERO)) return false; Direction movementDirection = Direction.getFacingFromVector(motion.x, motion.y, motion.z); // Blocks in the world if (movementDirection.getAxisDirection() == AxisDirection.POSITIVE) gridPos = gridPos.offset(movementDirection); if (isCollidingWithWorld(world, contraption, gridPos, movementDirection)) return true; // Other moving Contraptions for (ContraptionEntity otherContraptionEntity : world.getEntitiesWithinAABB(ContraptionEntity.class, bounds.grow(1), e -> !e.equals(contraptionEntity))) { if (!otherContraptionEntity.collisionEnabled()) continue; Vec3d otherMotion = otherContraptionEntity.getMotion(); Contraption otherContraption = otherContraptionEntity.getContraption(); AxisAlignedBB otherBounds = otherContraptionEntity.getBoundingBox(); Vec3d otherPosition = otherContraptionEntity.getPositionVec(); if (otherContraption == null) return false; if (otherBounds == null) return false; if (!bounds.offset(motion).intersects(otherBounds.offset(otherMotion))) continue; for (BlockPos colliderPos : contraption.getColliders(world, movementDirection)) { colliderPos = colliderPos.add(gridPos).subtract(new BlockPos(otherPosition)); if (!otherContraption.blocks.containsKey(colliderPos)) continue; return true; } } return false; } public static boolean isCollidingWithWorld(World world, Contraption contraption, BlockPos anchor, Direction movementDirection) { for (BlockPos pos : contraption.getColliders(world, movementDirection)) { BlockPos colliderPos = pos.add(anchor); if (!world.isBlockPresent(colliderPos)) return true; BlockState collidedState = world.getBlockState(colliderPos); BlockInfo blockInfo = contraption.blocks.get(pos); if (blockInfo.state.getBlock() instanceof IPortableBlock) { IPortableBlock block = (IPortableBlock) blockInfo.state.getBlock(); if (block.getMovementBehaviour() instanceof BlockBreakingMovementBehaviour) { BlockBreakingMovementBehaviour behaviour = (BlockBreakingMovementBehaviour) block.getMovementBehaviour(); if (!behaviour.canBreak(world, colliderPos, collidedState) && !collidedState.getCollisionShape(world, pos).isEmpty()) { return true; } continue; } } if (AllBlocks.PULLEY_MAGNET.has(collidedState) && pos.equals(BlockPos.ZERO) && movementDirection == Direction.UP) continue; if (collidedState.getBlock() instanceof CocoaBlock) continue; if (!collidedState.getMaterial().isReplaceable() && !collidedState.getCollisionShape(world, colliderPos).isEmpty()) { return true; } } return false; } }
36.545139
109
0.752304
0ef2f940c9338d0711fcfa3d9aaa434c2c5ac547
2,586
/* * Copyright 2018-2020 adorsys GmbH & Co KG * * 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.adorsys.psd2.scheduler; import de.adorsys.psd2.consent.domain.payment.PisCommonPaymentData; import de.adorsys.psd2.consent.repository.PisCommonPaymentDataRepository; import de.adorsys.psd2.consent.service.PisCommonPaymentConfirmationExpirationService; import de.adorsys.psd2.xs2a.core.pis.TransactionStatus; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.EnumSet; import java.util.List; import java.util.stream.Collectors; @Slf4j @RequiredArgsConstructor @Component public class NotConfirmedPaymentExpirationScheduleTask { private final PisCommonPaymentConfirmationExpirationService pisCommonPaymentConfirmationExpirationService; private final PisCommonPaymentDataRepository paymentDataRepository; @Scheduled(cron = "${xs2a.cms.not-confirmed-payment-expiration.cron.expression}") @Transactional public void obsoleteNotConfirmedPaymentIfExpired() { log.info("Not confirmed payment expiration schedule task is run!"); List<PisCommonPaymentData> expiredNotConfirmedPaymentDatas = paymentDataRepository.findByTransactionStatusIn(EnumSet.of(TransactionStatus.RCVD, TransactionStatus.PATC)) .stream() .filter(pisCommonPaymentConfirmationExpirationService::isConfirmationExpired) .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(expiredNotConfirmedPaymentDatas)) { pisCommonPaymentConfirmationExpirationService.updatePaymentDataListOnConfirmationExpiration(expiredNotConfirmedPaymentDatas); } } }
46.178571
176
0.743619
107df9893bfda0c7a7f6805a78141bdb79109faa
1,177
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; //import checkers.inference.ownership.quals.*; public class UpdatedMethodBinding extends MethodBinding { public TypeBinding updatedDeclaringClass; public UpdatedMethodBinding(TypeBinding updatedDeclaringClass, int modifiers, char[] selector, TypeBinding returnType, TypeBinding[] args, ReferenceBinding[] exceptions, ReferenceBinding declaringClass) { super(modifiers, selector, returnType, args, exceptions, declaringClass); this.updatedDeclaringClass = updatedDeclaringClass; } public TypeBinding constantPoolDeclaringClass() { return this.updatedDeclaringClass; } }
43.592593
205
0.686491
3810e29709664a900d379fbc01924f756611b644
2,647
package com.drk.tools.gplannercore.core.streams; import com.drk.tools.gplannercore.core.Plan; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; public class PlanBuffer { private final BlockingQueue<Item> queue; private boolean isClosed; public PlanBuffer(int bufferSize) { this.queue = new ArrayBlockingQueue<>(bufferSize); this.isClosed = false; } public GOutputStream outputStream() { return new OutputStream(); } public GInputStream inputStream() { return new InputStream(); } private void internalClose() { if (isClosed) { return; } isClosed = true; //Unblock producer if (isFull()) { queue.poll(); } //Unblock consumer queue.offer(new Item(null)); } private boolean isFull() { return queue.remainingCapacity() == 0; } private class InputStream implements GInputStream { @Override public Plan read() throws GStreamException { if (isClosed) { throw new GStreamException("Stream is Closed"); } try { Item item = queue.poll(Long.MAX_VALUE, TimeUnit.MILLISECONDS); return item == null ? null : item.plan; } catch (InterruptedException e) { throw new GStreamException(e); } } @Override public void close() { internalClose(); } } private class OutputStream implements GOutputStream { @Override public void write(Plan plan) throws GStreamException { if (isClosed) { throw new GStreamException("Stream is Closed"); } queue.offer(new Item(plan)); } @Override public void write(Plan plan, long timeout) throws GStreamException { if (isClosed) { throw new GStreamException("Stream is Closed"); } try { queue.offer(new Item(plan), timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new GStreamException(e); } } @Override public void close() throws GStreamException { internalClose(); } @Override public boolean isClosed() { return isClosed; } } private static class Item { final Plan plan; Item(Plan plan) { this.plan = plan; } } }
24.509259
78
0.55459
ffbca926f5b1377b76f65f397ddbab1e09660da2
9,927
package com.bumptech.glide; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoader; import com.bumptech.glide.load.model.ModelLoaderFactory; import com.bumptech.glide.load.model.file_descriptor.FileDescriptorModelLoader; import com.bumptech.glide.load.model.stream.StreamByteArrayLoader; import com.bumptech.glide.load.model.stream.StreamModelLoader; import com.bumptech.glide.manager.ConnectivityMonitor; import com.bumptech.glide.manager.ConnectivityMonitor.ConnectivityListener; import com.bumptech.glide.manager.ConnectivityMonitorFactory; import com.bumptech.glide.manager.Lifecycle; import com.bumptech.glide.manager.RequestTracker; import com.bumptech.glide.tests.BackgroundUtil; import com.bumptech.glide.tests.GlideShadowLooper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import static com.bumptech.glide.tests.BackgroundUtil.testInBackground; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(shadows = GlideShadowLooper.class) public class RequestManagerTest { private RequestManager manager; private ConnectivityMonitor connectivityMonitor; private RequestTracker requestTracker; private ConnectivityListener connectivityListener; private RequestManager.DefaultOptions options; private Lifecycle lifecycle = mock(Lifecycle.class); @Before public void setUp() { connectivityMonitor = mock(ConnectivityMonitor.class); ConnectivityMonitorFactory factory = mock(ConnectivityMonitorFactory.class); when(factory.build(any(Context.class), any(ConnectivityMonitor.ConnectivityListener.class))) .thenAnswer(new Answer<ConnectivityMonitor>() { @Override public ConnectivityMonitor answer(InvocationOnMock invocation) throws Throwable { connectivityListener = (ConnectivityListener) invocation.getArguments()[1]; return connectivityMonitor; } }); requestTracker = mock(RequestTracker.class); manager = new RequestManager(Robolectric.application, lifecycle, requestTracker, factory); options = mock(RequestManager.DefaultOptions.class); manager.setDefaultOptions(options); } @Test public void testAppliesDefaultOptionsWhenUsingGenericModelLoaderAndDataClass() { Float model = 1f; ModelLoader<Float, InputStream> modelLoader = mock(ModelLoader.class); GenericTranscodeRequest<Float, InputStream, Bitmap> builder = manager.using(modelLoader, InputStream.class) .load(model) .as(Bitmap.class); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsWhenUsingImageStreamModelLoader() { String model = "fake"; StreamModelLoader<String> modelLoader = mock(StreamModelLoader.class); DrawableTypeRequest<String> builder = manager.using(modelLoader) .load(model); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsWhenUsingByteArrayLoader() { byte[] model = new byte[] { 1, 4, 65, 2}; StreamByteArrayLoader loader = mock(StreamByteArrayLoader.class); DrawableTypeRequest<byte[]> builder = manager.using(loader) .load(model); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsWhenUsingVideoFileDescriptorModelLoader() { String model = "fake"; FileDescriptorModelLoader<String> modelLoader = mock(FileDescriptorModelLoader.class); DrawableTypeRequest<String> builder = manager.using(modelLoader) .load(model); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadString() { String model = "fake"; DrawableTypeRequest<String> builder = manager.load(model); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadUri() { Uri uri = Uri.EMPTY; DrawableTypeRequest<Uri> builder = manager.load(uri); verify(options).apply(eq(uri), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadMediaStoreUri() { Uri uri = Uri.EMPTY; DrawableTypeRequest<Uri> builder = manager.loadFromMediaStore(uri, "image/jpeg", 123L, 0); verify(options).apply(eq(uri), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadResourceId() { int id = 123; DrawableTypeRequest<Integer> builder = manager.load(id); verify(options).apply(eq(id), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadGenericFromImage() { ModelLoaderFactory<Double, InputStream> factory = mock(ModelLoaderFactory.class); when(factory.build(any(Context.class), any(GenericLoaderFactory.class))).thenReturn(mock(ModelLoader.class)); Glide.get(Robolectric.application).register(Double.class, InputStream.class, factory); Double model = 2.2; DrawableTypeRequest<Double> builder = manager.load(model); verify(options).apply(eq(model), eq(builder)); Glide.get(Robolectric.application).unregister(Double.class, InputStream.class); } @Test public void testAppliesDefaultOptionsToLoadUrl() throws MalformedURLException { URL url = new URL("http://www.google.com"); DrawableTypeRequest<URL> builder = manager.load(url); verify(options).apply(eq(url), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadFromImageByteWithId() { byte[] model = new byte[] { 1, 2, 4 }; DrawableTypeRequest<byte[]> builder = manager.load(model, "fakeId"); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadFromImageBytes() { byte[] model = new byte[] { 5, 9, 23 }; DrawableTypeRequest<byte[]> builder = manager.load(model); verify(options).apply(eq(model), eq(builder)); } @Test public void testAppliesDefaultOptionsToLoadGenericFromVideo() { ModelLoaderFactory<Float, InputStream> factory = mock(ModelLoaderFactory.class); when(factory.build(any(Context.class), any(GenericLoaderFactory.class))).thenReturn(mock(ModelLoader.class)); Glide.get(Robolectric.application).register(Float.class, InputStream.class, factory); Float model = 23.2f; DrawableTypeRequest<Float> builder = manager.load(model); verify(options).apply(eq(model), eq(builder)); Glide.get(Robolectric.application).unregister(Float.class, InputStream.class); } @Test public void testPauseRequestsPausesRequests() { manager.pauseRequests(); verify(requestTracker).pauseRequests(); } @Test public void testResumeRequestsResumesRequests() { manager.resumeRequests(); verify(requestTracker).resumeRequests(); } @Test public void testPausesRequestsOnStop() { manager.onStart(); manager.onStop(); verify(requestTracker).pauseRequests(); } @Test public void testResumesRequestsOnStart() { manager.onStart(); verify(requestTracker).resumeRequests(); } @Test public void testClearsRequestsOnDestroy() { manager.onDestroy(); verify(requestTracker).clearRequests(); } @Test public void testAddsConnectivityMonitorToLifecycleWhenConstructed() { verify(lifecycle).addListener(eq(connectivityMonitor)); } @Test public void testAddsSelfToLifecycleWhenConstructed() { verify(lifecycle).addListener(eq(manager)); } @Test public void testRestartsRequestOnConnected() { connectivityListener.onConnectivityChanged(true); verify(requestTracker).restartRequests(); } @Test public void testDoesNotRestartRequestsOnDisconnected() { connectivityListener.onConnectivityChanged(false); verify(requestTracker, never()).restartRequests(); } @Test(expected = RuntimeException.class) public void testThrowsIfResumeCalledOnBackgroundThread() throws InterruptedException { testInBackground(new BackgroundUtil.BackgroundTester() { @Override public void runTest() throws Exception { manager.resumeRequests(); } }); } @Test(expected = RuntimeException.class) public void testThrowsIfPauseCalledOnBackgroundThread() throws InterruptedException { testInBackground(new BackgroundUtil.BackgroundTester() { @Override public void runTest() throws Exception { manager.pauseRequests(); } }); } @Test public void testDelegatesIsPausedToRequestTracker() { when(requestTracker.isPaused()).thenReturn(true); assertTrue(manager.isPaused()); when(requestTracker.isPaused()).thenReturn(false); assertFalse(manager.isPaused()); } }
35.580645
117
0.701823
a69de1b0b3d9a076d9897aed19461d4c147ed548
553
package com.peoplepowerco.virtuoso.models.rules; import java.util.List; /** * Created by justintan on 4/22/16. */ public class PPRuleSavePropertyModel { private int id; private List<PPRuleSaveParameterModel> parameter; public int getId() { return id; } public void setId(int id) { this.id = id; } public List<PPRuleSaveParameterModel> getParameter() { return parameter; } public void setParameter(List<PPRuleSaveParameterModel> parameter) { this.parameter = parameter; } }
19.75
72
0.663653
2813fc33c18af9ab62d42715da1e58baeeedb3d6
1,844
/* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jaspersoft.mongodb.jasperserver; import com.jaspersoft.jasperserver.api.metadata.jasperreports.service.CustomReportDataSourceService; import net.sf.jasperreports.engine.JRException; import org.apache.log4j.Logger; /** * * @author Eric Diaz * */ public class MongoDbDataSourceService extends MongoDbDataSourceService45 implements CustomReportDataSourceService { private final static Logger logger = Logger.getLogger(MongoDbDataSourceService.class); @Override public boolean testConnection() throws JRException { if (logger.isDebugEnabled()) { logger.debug("Testing connection"); } try { createConnection(); if (connection == null) { return false; } connection.test(); return true; } finally { closeConnection(); } } }
34.148148
116
0.679501
2e855faa90038f127c42527d09b2c083006d3978
995
package com.qa.ims.persistence.dao; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.qa.ims.persistence.domain.Items; import com.qa.ims.utils.DBUtils; public class ItemsDAOTestempty { private final ItemsDAO DAO = new ItemsDAO(); @Before public void setup() { DBUtils.connect(); DBUtils.getInstance().init("src/test/resources/sql-Itemsschema2.sql", "src/test/resources/sql-Itemsdata2.sql"); } @Test public void testEmpty() { List<Items> expected = new ArrayList<>(); expected.isEmpty(); assertEquals(expected, DAO.readAll()); } @Test public void testReadAll() { List<Items> expected = new ArrayList<>(); assertEquals(expected, DAO.readAll()); } @Test public void testUpdate() { final Items updated = new Items(8L, "Tim", 8D); assertEquals(null, DAO.update(updated)); } @Test public void testDelete() { assertEquals(0, DAO.delete(8)); } }
20.306122
113
0.712563
449adad4d1f9cd19ce619ef5107b89fde0dc4ec4
2,125
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib; import com.wilutions.com.*; /** * ChannelState. * Enumerates the media channel states. */ @SuppressWarnings("all") @CoInterface(guid="{00000000-0000-0000-0000-000000000000}") public class ChannelState { static boolean __typelib__loaded = __TypeLib.load(); // Typed constants public final static ChannelState ucChannelStateNone = new ChannelState(0); public final static ChannelState ucChannelStateConnecting = new ChannelState(1); public final static ChannelState ucChannelStateNotified = new ChannelState(2); public final static ChannelState ucChannelStateSend = new ChannelState(3); public final static ChannelState ucChannelStateReceive = new ChannelState(4); public final static ChannelState ucChannelStateSendReceive = new ChannelState(5); public final static ChannelState ucChannelStateInactive = new ChannelState(6); // Integer constants for bitsets and switch statements public final static int _ucChannelStateNone = 0; public final static int _ucChannelStateConnecting = 1; public final static int _ucChannelStateNotified = 2; public final static int _ucChannelStateSend = 3; public final static int _ucChannelStateReceive = 4; public final static int _ucChannelStateSendReceive = 5; public final static int _ucChannelStateInactive = 6; // Value, readonly field. public final int value; // Private constructor, use valueOf to create an instance. private ChannelState(int value) { this.value = value; } // Return one of the predefined typed constants for the given value or create a new object. public static ChannelState valueOf(int value) { switch(value) { case 0: return ucChannelStateNone; case 1: return ucChannelStateConnecting; case 2: return ucChannelStateNotified; case 3: return ucChannelStateSend; case 4: return ucChannelStateReceive; case 5: return ucChannelStateSendReceive; case 6: return ucChannelStateInactive; default: return new ChannelState(value); } } }
40.865385
94
0.751529
eef7c268f64aef6bc896206a7c316d17c275b19d
1,587
package Shape.Shape2D; import Color.ColorRGB; import Interface.ICalculable; import Shape.Point2D; import Shape.Shape; import java.util.ArrayList; public abstract class Shape2D extends Shape implements ICalculable<Shape2D> { protected ArrayList<Point2D> points; public Shape2D(ArrayList<Point2D> p, String n) { super(n); points = p; } public Shape2D(ArrayList<Point2D> p, String name, ColorRGB color) { super(name, color); points = p; } public Shape2D(Shape2D s2d) { super(s2d); points = s2d.points; } public int getNumberSide() { return points.size(); } public abstract double sideToOperator(); public int getNumberVertex() { return points.size(); } public ArrayList<Point2D> getPoints() { return points; } public void translate(Point2D p) { for (Point2D point : points) { point.setX(p.getX() + point.getX()); point.setY(p.getY() + point.getY()); } } public boolean equalsPoints(ArrayList<Point2D> p) { if (points == null || p == null) return false; if (points.size() != p.size()) return false; for (Point2D points : points) { if (!p.contains(points)) { return false; } } return true; } public boolean equals(Object obj) { if (super.equals(obj)) { Shape2D s2d = (Shape2D) obj; return equalsPoints(s2d.points); } return false; } }
22.671429
77
0.565217
f1cfa31224783f336efb34552e4b38d542d925d4
8,633
package net.elodina.mesos.util; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import org.junit.Test; import java.io.*; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class RequestTest { @Test public void encoding() { assertEquals(Charset.defaultCharset().name(), Request.encoding(null)); assertEquals("utf-16", Request.encoding("text/html; charset=utf-16")); } @Test public void contentType_get() { Request request = new Request(); request.header("Content-Type", "text/html"); assertEquals("text/html", request.contentType()); } @Test public void uri_set() { Request request = new Request(); request.uri("/path?a=1&b=2"); assertEquals("/path", request.uri()); assertEquals("1", request.param("a")); assertEquals("2", request.param("b")); } @Test public void query_get() { Request request = new Request(); assertNull(request.query()); // all types of params request.param("a", "1"); request.param("b", "2", "3"); request.param("c", (String) null); assertEquals("a=1&b=2&b=3&c", request.query()); // url encoding request.params().clear(); request.param("a", "="); request.param("b", " "); assertEquals("a=%3D&b=+", request.query()); } @Test public void query_set() { Request request = new Request(); // all types of params request.query("a=1&b=2&b=3&c"); assertEquals("1", request.param("a")); assertEquals(Arrays.asList("2", "3"), request.params("b")); assertEquals(null, request.param("c")); // url decoding request.params().clear(); request.query("a=%3D&b=+"); assertEquals("=", request.param("a")); assertEquals(" ", request.param("b")); } @Test public void send() throws IOException { HttpHandler handler = new HttpHandler() { @Override public void response(HttpExchange exchange) throws IOException { exchange.getResponseHeaders().add("a", "1"); exchange.getResponseHeaders().add("a", "2"); exchange.getResponseHeaders().add("b", "3"); byte[] data = "response".getBytes(); exchange.sendResponseHeaders(200, data.length); exchange.getResponseBody().write(data); } }; try(HttpServer server = new HttpServer(handler)) { Request request = new Request(server.getUrl() + "/") .header("a", "1", "2").header("b", "3") .param("a", "1", "2").param("b", "3"); Request.Response response = request.send(); assertEquals("response", response.text()); assertEquals("GET", handler.method); // params sent assertEquals("/?a=1&a=2&b=3", "" + handler.uri); // request headers sent assertEquals(Arrays.asList("1", "2"), handler.headers.get("a")); assertEquals(Arrays.asList("3"), handler.headers.get("b")); // response code & message assertEquals(200, response.code()); assertEquals("OK", response.message()); // response headers received List<String> aValues = new ArrayList<>(response.headers("A")); Collections.sort(aValues); assertEquals(Arrays.asList("1", "2"), aValues); assertEquals("3", response.header("B")); } } @Test public void send_keepOpen() throws IOException { HttpHandler handler = new HttpHandler() { @Override public void response(HttpExchange exchange) throws IOException { byte[] data = "123\n".getBytes(); exchange.sendResponseHeaders(200, data.length); exchange.getResponseBody().write(data); } }; try(HttpServer server = new HttpServer(handler); Request request = new Request(server.getUrl() + "/")) { Request.Response response = request .contentType("text/plain") .send(true); BufferedReader reader = new BufferedReader(new InputStreamReader(response.stream())); String line = reader.readLine(); assertEquals("123", line); } } @Test public void send_404_500() throws IOException { final AtomicInteger code = new AtomicInteger(0); HttpHandler handler = new HttpHandler() { @Override public void response(HttpExchange exchange) throws IOException { exchange.sendResponseHeaders(code.get(), 5); exchange.getResponseBody().write("error".getBytes()); } }; try(HttpServer server = new HttpServer(handler)) { // 404 code.set(404); Request.Response response = new Request(server.getUrl() + "/").send(); assertEquals(404, response.code()); assertEquals("Not Found", response.message()); // 500 handler.reset(); code.set(500); response = new Request(server.getUrl() + "/").send(); assertEquals(500, response.code()); assertEquals("error", new String(response.body())); assertEquals("Internal Server Error", response.message()); } } @Test public void send_body() throws IOException { HttpHandler handler = new HttpHandler() { @Override public void response(HttpExchange exchange) throws IOException { exchange.getResponseHeaders().add("Content-Length", "0"); exchange.sendResponseHeaders(200, 0); } }; try(HttpServer server = new HttpServer(handler)) { Request.Response response = new Request(server.getUrl() + "/") .method(Request.Method.PUT) .body("body".getBytes()) .send(); assertEquals(200, response.code()); assertEquals("PUT", handler.method); assertEquals("body", new String(handler.body)); } } // Response @Test public void Response_contentType() { Request.Response response = new Request.Response(); assertNull(response.contentType()); response.header("Content-Type", "text/plain"); assertEquals("text/plain", response.contentType()); } private static class HttpHandler implements com.sun.net.httpserver.HttpHandler { private String method; private URI uri; private Headers headers; private byte[] body; @Override public void handle(HttpExchange exchange) throws IOException { method = exchange.getRequestMethod(); uri = exchange.getRequestURI(); headers = exchange.getRequestHeaders(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IO.copyAndClose(exchange.getRequestBody(), bytes); body = bytes.toByteArray(); response(exchange); } public void reset() { method = null; uri = null; headers = null; } public void response(HttpExchange exchange) throws IOException {} } private static class HttpServer implements Closeable { private com.sun.net.httpserver.HttpHandler handler; private com.sun.net.httpserver.HttpServer server; private HttpServer(com.sun.net.httpserver.HttpHandler handler) throws IOException { this.handler = handler; start(); } public void start() throws IOException { server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(Net.findAvailPort()), 0); server.createContext("/", handler); server.setExecutor(null); server.start(); } public void stop() { server.stop(0); server = null; } public String getUrl() { return "http://localhost:" + server.getAddress().getPort(); } @Override public void close() { if (server != null) stop(); } } }
32.700758
112
0.57257
46854e8373c8301ff375d581eca69cee72140b55
3,094
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.command; import java.util.ArrayList; import java.util.List; import net.sourceforge.plantuml.StringLocated; import net.sourceforge.plantuml.TitledDiagram; import net.sourceforge.plantuml.command.regex.Matcher2; import net.sourceforge.plantuml.command.regex.MyPattern; import net.sourceforge.plantuml.command.regex.Pattern2; import net.sourceforge.plantuml.style.NoStyleAvailableException; public class SkinLoader { public final static Pattern2 p1 = MyPattern .cmpile("^([\\w.]*(?:\\<\\<.*\\>\\>)?[\\w.]*)[%s]+(?:(\\{)|(.*))$|^\\}?$"); final private List<String> context = new ArrayList<String>(); final private TitledDiagram diagram; public SkinLoader(TitledDiagram diagram) { this.diagram = diagram; } private void push(String s) { context.add(s); } private void pop() { context.remove(context.size() - 1); } private String getFullParam() { final StringBuilder sb = new StringBuilder(); for (String s : context) { sb.append(s); } return sb.toString(); } public CommandExecutionResult execute(BlocLines lines, final String group1) { if (group1 != null) { this.push(group1); } try { lines = lines.subExtract(1, 1); lines = lines.trim().removeEmptyLines(); for (StringLocated s : lines) { assert s.getString().length() > 0; if (s.getString().equals("}")) { this.pop(); continue; } final Matcher2 m = p1.matcher(s.getString()); if (m.find() == false) { throw new IllegalStateException(); } if (m.group(2) != null) { this.push(m.group(1)); } else if (m.group(3) != null) { final String key = this.getFullParam() + m.group(1); diagram.setParam(key, m.group(3)); } else { throw new IllegalStateException("." + s.getString() + "."); } } return CommandExecutionResult.ok(); } catch (NoStyleAvailableException e) { // e.printStackTrace(); return CommandExecutionResult.error("General failure: no style available."); } } }
27.873874
79
0.644473
ecccd5299eefef24186aa6fc235af57d73987fe1
1,464
package bilokhado.linkcollector.converter; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; import bilokhado.linkcollector.entity.TagsList; /** * A JSF converter for {@code TagsList} class. * */ @FacesConverter(forClass = TagsList.class) public class TagsListConverter implements Converter { /** * Converts {@code String} to {@code TagsList}. */ @Override public Object getAsObject(FacesContext context, UIComponent component, String tagsJson) { TagsList tags = new TagsList(); try { tags.populateFromJson(tagsJson); return tags; } catch (Exception e) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()); throw new ConverterException(message); } } /** * Converts {@code TagsList} {@code String}. * * @see bilokhado.linkcollector.entity.TagsList#getAsJsonString() */ @Override public String getAsString(FacesContext context, UIComponent component, Object tagsList) { if (tagsList instanceof TagsList) { return ((TagsList) tagsList).getAsJsonString(); } FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsupported object type to convert", "Unsupported object type to convert"); throw new ConverterException(message); } }
29.28
108
0.75888
b6defa8bc368df9a1d5a289e7ff48e112559579a
9,453
package com.linkedin.metadata.boot.steps; import com.linkedin.common.AuditStamp; import com.linkedin.common.urn.Urn; import com.linkedin.data.DataMap; import com.linkedin.data.template.RecordTemplate; import com.linkedin.entity.EntityResponse; import com.linkedin.entity.EnvelopedAspectMap; import com.linkedin.events.metadata.ChangeType; import com.linkedin.glossary.GlossaryNodeInfo; import com.linkedin.glossary.GlossaryTermInfo; import com.linkedin.metadata.Constants; import com.linkedin.metadata.boot.BootstrapStep; import com.linkedin.metadata.entity.EntityService; import com.linkedin.metadata.key.DataHubUpgradeKey; import com.linkedin.metadata.models.AspectSpec; import com.linkedin.metadata.models.registry.EntityRegistry; import com.linkedin.metadata.search.EntitySearchService; import com.linkedin.metadata.search.SearchEntity; import com.linkedin.metadata.search.SearchResult; import com.linkedin.metadata.utils.EntityKeyUtils; import com.linkedin.metadata.utils.GenericRecordUtils; import com.linkedin.mxe.MetadataChangeProposal; import com.linkedin.upgrade.DataHubUpgradeRequest; import com.linkedin.upgrade.DataHubUpgradeResult; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nonnull; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Slf4j @RequiredArgsConstructor public class RestoreGlossaryIndices implements BootstrapStep { private static final String VERSION = "1"; private static final String UPGRADE_ID = "restore-glossary-indices-ui"; private static final Urn GLOSSARY_UPGRADE_URN = EntityKeyUtils.convertEntityKeyToUrn(new DataHubUpgradeKey().setId(UPGRADE_ID), Constants.DATA_HUB_UPGRADE_ENTITY_NAME); private static final Integer BATCH_SIZE = 1000; private static final Integer SLEEP_SECONDS = 120; private final EntityService _entityService; private final EntitySearchService _entitySearchService; private final EntityRegistry _entityRegistry; @Override public String name() { return this.getClass().getSimpleName(); } @Nonnull @Override public ExecutionMode getExecutionMode() { return ExecutionMode.ASYNC; } @Override public void execute() throws Exception { log.info("Attempting to run RestoreGlossaryIndices upgrade.."); log.info(String.format("Waiting %s seconds..", SLEEP_SECONDS)); // Sleep to ensure deployment process finishes. Thread.sleep(SLEEP_SECONDS * 1000); try { EntityResponse response = _entityService.getEntityV2( Constants.DATA_HUB_UPGRADE_ENTITY_NAME, GLOSSARY_UPGRADE_URN, Collections.singleton(Constants.DATA_HUB_UPGRADE_REQUEST_ASPECT_NAME) ); if (response != null && response.getAspects().containsKey(Constants.DATA_HUB_UPGRADE_REQUEST_ASPECT_NAME)) { DataMap dataMap = response.getAspects().get(Constants.DATA_HUB_UPGRADE_REQUEST_ASPECT_NAME).getValue().data(); DataHubUpgradeRequest request = new DataHubUpgradeRequest(dataMap); if (request.hasVersion() && request.getVersion().equals(VERSION)) { log.info("Glossary Upgrade has run before with this version. Skipping"); return; } } final AspectSpec termAspectSpec = _entityRegistry.getEntitySpec(Constants.GLOSSARY_TERM_ENTITY_NAME).getAspectSpec(Constants.GLOSSARY_TERM_INFO_ASPECT_NAME); final AspectSpec nodeAspectSpec = _entityRegistry.getEntitySpec(Constants.GLOSSARY_NODE_ENTITY_NAME).getAspectSpec(Constants.GLOSSARY_NODE_INFO_ASPECT_NAME); final AuditStamp auditStamp = new AuditStamp().setActor(Urn.createFromString(Constants.SYSTEM_ACTOR)).setTime(System.currentTimeMillis()); final DataHubUpgradeRequest upgradeRequest = new DataHubUpgradeRequest().setTimestampMs(System.currentTimeMillis()).setVersion(VERSION); ingestUpgradeAspect(Constants.DATA_HUB_UPGRADE_REQUEST_ASPECT_NAME, upgradeRequest, auditStamp); final int totalTermsCount = getAndRestoreTermAspectIndices(0, auditStamp, termAspectSpec); int termsCount = BATCH_SIZE; while (termsCount < totalTermsCount) { getAndRestoreTermAspectIndices(termsCount, auditStamp, termAspectSpec); termsCount += BATCH_SIZE; } final int totalNodesCount = getAndRestoreNodeAspectIndices(0, auditStamp, nodeAspectSpec); int nodesCount = BATCH_SIZE; while (nodesCount < totalNodesCount) { getAndRestoreNodeAspectIndices(nodesCount, auditStamp, nodeAspectSpec); nodesCount += BATCH_SIZE; } final DataHubUpgradeResult upgradeResult = new DataHubUpgradeResult().setTimestampMs(System.currentTimeMillis()); ingestUpgradeAspect(Constants.DATA_HUB_UPGRADE_RESULT_ASPECT_NAME, upgradeResult, auditStamp); log.info("Successfully restored glossary index"); } catch (Exception e) { log.error("Error when running the RestoreGlossaryIndices Bootstrap Step", e); _entityService.deleteUrn(GLOSSARY_UPGRADE_URN); throw new RuntimeException("Error when running the RestoreGlossaryIndices Bootstrap Step", e); } } private void ingestUpgradeAspect(String aspectName, RecordTemplate aspect, AuditStamp auditStamp) { final MetadataChangeProposal upgradeProposal = new MetadataChangeProposal(); upgradeProposal.setEntityUrn(GLOSSARY_UPGRADE_URN); upgradeProposal.setEntityType(Constants.DATA_HUB_UPGRADE_ENTITY_NAME); upgradeProposal.setAspectName(aspectName); upgradeProposal.setAspect(GenericRecordUtils.serializeAspect(aspect)); upgradeProposal.setChangeType(ChangeType.UPSERT); _entityService.ingestProposal(upgradeProposal, auditStamp); } private int getAndRestoreTermAspectIndices(int start, AuditStamp auditStamp, AspectSpec termAspectSpec) throws Exception { SearchResult termsResult = _entitySearchService.search(Constants.GLOSSARY_TERM_ENTITY_NAME, "", null, null, start, BATCH_SIZE); List<Urn> termUrns = termsResult.getEntities().stream().map(SearchEntity::getEntity).collect(Collectors.toList()); if (termUrns.size() == 0) { return 0; } final Map<Urn, EntityResponse> termInfoResponses = _entityService.getEntitiesV2( Constants.GLOSSARY_TERM_ENTITY_NAME, new HashSet<>(termUrns), Collections.singleton(Constants.GLOSSARY_TERM_INFO_ASPECT_NAME) ); // Loop over Terms and produce changelog for (Urn termUrn : termUrns) { EntityResponse termEntityResponse = termInfoResponses.get(termUrn); if (termEntityResponse == null) { log.warn("Term not in set of entity responses {}", termUrn); continue; } GlossaryTermInfo termInfo = mapTermInfo(termEntityResponse); if (termInfo == null) { log.warn("Received null termInfo for urn {}", termUrn); continue; } _entityService.produceMetadataChangeLog( termUrn, Constants.GLOSSARY_TERM_ENTITY_NAME, Constants.GLOSSARY_TERM_INFO_ASPECT_NAME, termAspectSpec, null, termInfo, null, null, auditStamp, ChangeType.RESTATE); } return termsResult.getNumEntities(); } private int getAndRestoreNodeAspectIndices(int start, AuditStamp auditStamp, AspectSpec nodeAspectSpec) throws Exception { SearchResult nodesResult = _entitySearchService.search(Constants.GLOSSARY_NODE_ENTITY_NAME, "", null, null, start, BATCH_SIZE); List<Urn> nodeUrns = nodesResult.getEntities().stream().map(SearchEntity::getEntity).collect(Collectors.toList()); if (nodeUrns.size() == 0) { return 0; } final Map<Urn, EntityResponse> nodeInfoResponses = _entityService.getEntitiesV2( Constants.GLOSSARY_NODE_ENTITY_NAME, new HashSet<>(nodeUrns), Collections.singleton(Constants.GLOSSARY_NODE_INFO_ASPECT_NAME) ); // Loop over Nodes and produce changelog for (Urn nodeUrn : nodeUrns) { EntityResponse nodeEntityResponse = nodeInfoResponses.get(nodeUrn); if (nodeEntityResponse == null) { log.warn("Node not in set of entity responses {}", nodeUrn); continue; } GlossaryNodeInfo nodeInfo = mapNodeInfo(nodeEntityResponse); if (nodeInfo == null) { log.warn("Received null nodeInfo for urn {}", nodeUrn); continue; } _entityService.produceMetadataChangeLog( nodeUrn, Constants.GLOSSARY_NODE_ENTITY_NAME, Constants.GLOSSARY_NODE_INFO_ASPECT_NAME, nodeAspectSpec, null, nodeInfo, null, null, auditStamp, ChangeType.RESTATE); } return nodesResult.getNumEntities(); } private GlossaryTermInfo mapTermInfo(EntityResponse entityResponse) { EnvelopedAspectMap aspectMap = entityResponse.getAspects(); if (!aspectMap.containsKey(Constants.GLOSSARY_TERM_INFO_ASPECT_NAME)) { return null; } return new GlossaryTermInfo(aspectMap.get(Constants.GLOSSARY_TERM_INFO_ASPECT_NAME).getValue().data()); } private GlossaryNodeInfo mapNodeInfo(EntityResponse entityResponse) { EnvelopedAspectMap aspectMap = entityResponse.getAspects(); if (!aspectMap.containsKey(Constants.GLOSSARY_NODE_INFO_ASPECT_NAME)) { return null; } return new GlossaryNodeInfo(aspectMap.get(Constants.GLOSSARY_NODE_INFO_ASPECT_NAME).getValue().data()); } }
41.279476
144
0.749074
86f306a790b394ed0d37e98ec01f44947cca548c
1,030
/* * Copyright 2019 OpenAPI-Generator Contributors (https://openapi-generator.tech) * * 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 org.openapitools.codegen.api; // TODO: 6.0 Remove /** * interface to the full template content * implementers might take into account the -t cli option, * look in the resources for a language specific template, etc * * @deprecated as of 5.0, replaced by {@link TemplatingExecutor}. */ @Deprecated public interface TemplatingGenerator extends TemplatingExecutor { }
33.225806
81
0.748544
3c190a94bac5e94ac23d46053430159cf0835397
2,843
/******************************************************************************* * Copyright (c) 2012 IBM Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * * Keith Wells - initial API and implementation * Sam Padgett - initial API and Implementation * Jim Conallen - initial API and implementation * *******************************************************************************/ package org.eclipse.lyo.samples.sharepoint.adapter; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.lyo.samples.sharepoint.SharepointConnector; import org.eclipse.lyo.samples.sharepoint.exceptions.ConnectionException; import org.eclipse.lyo.samples.sharepoint.exceptions.SharepointException; import org.eclipse.lyo.samples.sharepoint.services.ShareBaseService; import org.eclipse.lyo.samples.sharepoint.store.ShareValue; import org.eclipse.lyo.samples.sharepoint.store.UnrecognizedValueTypeException; public class ResourceListService extends ShareBaseService { private static final long serialVersionUID = -8436719131002636593L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @SuppressWarnings("nls") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String collection = (String)request.getParameter("collection"); //List<Map<String, ShareValue>> results = store.query(IConstants.SPARQL, query, IAmConstants.DEFAULT_MAX_RESULTS); final SharepointConnector sc = SharepointInitializer.getSharepointConnector(); List<Map<String, ShareValue>> results = sc.getDocuments(collection); request.setAttribute("results", results); request.setAttribute("collection", collection); RequestDispatcher rd = request.getRequestDispatcher("/sharepoint/resource_listing.jsp"); rd.forward(request, response); } catch (ConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SharepointException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognizedValueTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
37.407895
118
0.723531
25dff7c4794c8192893c06a7e5bc529e27968df0
3,731
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser.accessibility.captioning; import android.content.Context; import android.view.accessibility.CaptioningManager; import org.chromium.base.ContextUtils; import java.util.Locale; /** * Implementation of SystemCaptioningBridge that uses CaptioningManager. */ public class CaptioningBridge extends CaptioningManager.CaptioningChangeListener implements SystemCaptioningBridge { private final CaptioningChangeDelegate mCaptioningChangeDelegate; private final CaptioningManager mCaptioningManager; private static CaptioningBridge sInstance; public static CaptioningBridge getInstance() { if (sInstance == null) { sInstance = new CaptioningBridge(); } return sInstance; } private CaptioningBridge() { mCaptioningChangeDelegate = new CaptioningChangeDelegate(); mCaptioningManager = (CaptioningManager) ContextUtils.getApplicationContext().getSystemService( Context.CAPTIONING_SERVICE); } @Override public void onEnabledChanged(boolean enabled) { mCaptioningChangeDelegate.onEnabledChanged(enabled); } @Override public void onFontScaleChanged(float fontScale) { mCaptioningChangeDelegate.onFontScaleChanged(fontScale); } @Override public void onLocaleChanged(Locale locale) { mCaptioningChangeDelegate.onLocaleChanged(locale); } @Override public void onUserStyleChanged(CaptioningManager.CaptionStyle userStyle) { final CaptioningStyle captioningStyle = getCaptioningStyleFrom(userStyle); mCaptioningChangeDelegate.onUserStyleChanged(captioningStyle); } /** * Force-sync the current closed caption settings to the delegate */ private void syncToDelegate() { mCaptioningChangeDelegate.onEnabledChanged(mCaptioningManager.isEnabled()); mCaptioningChangeDelegate.onFontScaleChanged(mCaptioningManager.getFontScale()); mCaptioningChangeDelegate.onLocaleChanged(mCaptioningManager.getLocale()); mCaptioningChangeDelegate.onUserStyleChanged( getCaptioningStyleFrom(mCaptioningManager.getUserStyle())); } @Override public void syncToListener(SystemCaptioningBridge.SystemCaptioningBridgeListener listener) { if (!mCaptioningChangeDelegate.hasActiveListener()) { syncToDelegate(); } mCaptioningChangeDelegate.notifyListener(listener); } @Override public void addListener(SystemCaptioningBridge.SystemCaptioningBridgeListener listener) { if (!mCaptioningChangeDelegate.hasActiveListener()) { mCaptioningManager.addCaptioningChangeListener(this); syncToDelegate(); } mCaptioningChangeDelegate.addListener(listener); mCaptioningChangeDelegate.notifyListener(listener); } @Override public void removeListener(SystemCaptioningBridge.SystemCaptioningBridgeListener listener) { mCaptioningChangeDelegate.removeListener(listener); if (!mCaptioningChangeDelegate.hasActiveListener()) { mCaptioningManager.removeCaptioningChangeListener(this); } } /** * Create a Chromium CaptioningStyle from a platform CaptionStyle * * @param userStyle the platform CaptionStyle * @return a Chromium CaptioningStyle */ private CaptioningStyle getCaptioningStyleFrom(CaptioningManager.CaptionStyle userStyle) { return CaptioningStyle.createFrom(userStyle); } }
35.533333
96
0.733047
32afecd6b7dda6b715e7bf95549dbaecc9d1b58d
1,616
package com.morrisware.flutter.net; import android.content.Context; import com.morrisware.flutter.net.request.FileRequest; import java.io.File; /** * @author mmw * @date 2020/3/20 **/ public class FileDownloader { public static final int STATUS_PENDING = 1; public static final int STATUS_RUNNING = 1 << 1; public static final int STATUS_SUCCESSFUL = 1 << 3; public static final int STATUS_FAILED = 1 << 4; public static final String NO_TAG = ""; public static boolean downloadUrl(Context context, String url, FileRequest.FileResponseCallback callback) { return downloadUrl(context, url, "", callback); } public static boolean downloadUrl(Context context, String url, String tag, FileRequest.FileResponseCallback callback) { return HttpManager.getInstance(context).getFileDownloaderEngine().downloadUrl(url, tag, callback); } public static void cancelDownload(Context context, String url, String tag) { HttpManager.getInstance(context).getFileDownloaderEngine().cancel(url, tag); } public static File getDownloadFile(Context context, String url, String tag) { return HttpManager.getInstance(context).getFileDownloaderEngine().getDownloadFile(url, tag); } public static int[] getDownloadStatus(Context context, String url, String tag) { return HttpManager.getInstance(context).getFileDownloaderEngine().checkDownloadStatus(url, tag); } public static void clearCache(Context context, long interval) { HttpManager.getInstance(context).getFileDownloaderEngine().clearCache(interval); } }
34.382979
123
0.73453
4d7f08d6a5d95b8de17f2df64c44212c3a357c37
56,689
package bsearch.app ; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.border.SoftBevelBorder; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.SwingUtilities; import org.xml.sax.SAXException; import bsearch.algorithms.SearchMethod; import bsearch.algorithms.SearchMethodLoader; import bsearch.nlogolink.NetLogoLinkException; import bsearch.representations.ChromosomeFactory; import bsearch.representations.ChromosomeTypeLoader; import bsearch.space.ParameterSpec; import bsearch.space.SearchSpace; import bsearch.util.GeneralUtils; import java.awt.FlowLayout; /* * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public strictfp class BehaviorSearchGUI extends javax.swing.JFrame { private static final long serialVersionUID = 1L; private static String getWindowTitleSuffix() { return " - BehaviorSearch " + GeneralUtils.getVersionString(); } { //Set Look & Feel try { if( System.getProperty( "os.name" ).startsWith( "Mac" ) || System.getProperty( "os.name" ).startsWith( "Windows" )) { javax.swing.UIManager.setLookAndFeel ( javax.swing.UIManager.getSystemLookAndFeelClassName() ) ; } else if (System.getProperty( "swing.defaultlaf" ) == null ) { // On Linux, I prefer the Nimbus LAF... but users can override by setting // the swing.defaultlaf property. javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } } catch(Exception e) { e.printStackTrace(); } } private JMenuBar jMenuBar; private JMenu jMenuFile; private JMenuItem jMenuItemNew ; private JMenuItem jMenuItemSaveAs; private JMenuItem jMenuItemSave; private JMenuItem jMenuItemOpen; private JMenuItem jMenuItemExit ; private JSeparator jSeparator1; private JLabel jLabel1; private JLabel jLabel2; private JLabel jLabel3; private JLabel jLabel4; private JLabel jLabel5; private JLabel jLabel6; private JLabel jLabel7; private JLabel jLabel8; private JLabel jLabel10; private JLabel jLabel12; private JLabel jLabelSep; private JPanel jPanelSampling; private JPanel jPanelMeasureAfter; private JScrollPane jScrollPane1; private JTable jTableSearchMethodParams; private JPanel jPanel1; private JButton jButtonHelpSearchSpace; private JLabel jLabelDerivWRT; private JLabel jLabelDerivDELTA; private JTextField jTextFieldFitnessDerivativeDelta; private JComboBox jComboBoxFitnessDerivativeParameter; private JCheckBox jCheckBoxTakeDerivative; private JCheckBox jCheckBoxFitnessDerivativeUseAbs; private JPanel jPanelDeriv; private JPanel jPanelDeriv2; private JButton jButtonHelpSearchSpaceRepresentation; private JSeparator jSeparator2; private JMenuItem jMenuItemOpenExample; private JMenuItem jMenuItemAbout; private JMenuItem jMenuItemTutorial; private JMenu jMenuHelp; private JTextField jTextFieldBestChecking; private JLabel jLabel19; private JCheckBox jCheckBoxCaching; private JButton jButtonSuggestParamRanges; private JButton jButtonHelpEvaluation; private JButton jButtonHelpSearchMethod; private JTextField jTextFieldEvaluationLimit; private JLabel jLabel18; private JLabel jLabel9; private JTextField jTextFieldFitnessSamplingRepetitions; private JComboBox jComboBoxFitnessSamplingMethod; private JComboBox jComboBoxSearchMethodType; private JTextField jTextFieldModelStepLimit; private JTextArea jTextAreaParamSpecs; private JButton jButtonBrowseModel; private JTextField jTextFieldMeasureIf; private JLabel jLabel17; private JComboBox jComboBoxFitnessCombineReplications; private JLabel jLabel16; private JLabel jLabel15; private JLabel jLabel14; private JComboBox jComboBoxFitnessCollecting; private JLabel jLabel13; private JComboBox jComboBoxChromosomeType; private JLabel jLabel11; private JScrollPane jScrollPane2; private JTextField jTextFieldModelFile; private JTextField jTextFieldModelStopCondition; private JComboBox jComboBoxFitnessMinMax; private JTextField jTextFieldFitnessMetric; private JTextField jTextFieldModelStepCommands; private JTextField jTextFieldModelSetupCommands; private JButton jButtonRunNow; public static void main(final String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { BehaviorSearchGUI bgui = new BehaviorSearchGUI(); bgui.setLocationRelativeTo(null); bgui.setVisible(true); if (args.length > 0) { File f = new File(args[0]); if (f.exists()) { bgui.openFile(f); } } } }); } public BehaviorSearchGUI() { super(); initGUI(); // mainly Jigloo-generated UI code finishInitWork(); // custom stuff } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.addWindowListener(new WindowListener() { public void windowActivated(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowClosing(WindowEvent arg0) { actionExit(); } public void windowDeactivated(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowOpened(WindowEvent arg0) { } }); GridBagLayout thisLayout = new GridBagLayout(); getContentPane().setLayout(thisLayout); this.setTitle("BehaviorSearch - Experiment Editor"); thisLayout.rowWeights = new double[] {0.0, 0.1, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.0, 0.1, 0.0}; thisLayout.rowHeights = new int[] {7, 25, 10, 25, 25, 25, 25, 20, 25, 10, 25, 25, 25, 25, 20, 20, 20, 23, 20, 7}; thisLayout.columnWeights = new double[] {0.0, 0.1, 0.0, 0.1, 0.0, 0.0}; thisLayout.columnWidths = new int[] {7, 300, 29, 200, 207, 7}; { jMenuBar = new JMenuBar(); setJMenuBar(jMenuBar); { jMenuFile = new JMenu(); jMenuBar.add(jMenuFile); jMenuFile.setText("File"); { jMenuItemNew = new JMenuItem(); jMenuFile.add(jMenuItemNew); jMenuItemNew.setText("New"); jMenuItemNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionNew(); } }); } { jMenuItemOpen = new JMenuItem(); jMenuFile.add(jMenuItemOpen); jMenuItemOpen.setText("Open..."); jMenuItemOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionOpen(); } }); } { jMenuItemSave = new JMenuItem(); jMenuFile.add(jMenuItemSave); jMenuItemSave.setText("Save"); jMenuItemSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionSave(); } }); } { jMenuItemSaveAs = new JMenuItem(); jMenuFile.add(jMenuItemSaveAs); jMenuItemSaveAs.setText("Save as..."); jMenuItemSaveAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionSaveAs(); } }); } { jSeparator1 = new JSeparator(); jMenuFile.add(jSeparator1); } { jMenuItemOpenExample = new JMenuItem(); jMenuFile.add(jMenuItemOpenExample); jMenuItemOpenExample.setText("Open Example..."); jMenuItemOpenExample.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionOpenExample(); } }); } { jSeparator2 = new JSeparator(); jMenuFile.add(jSeparator2); } { jMenuItemExit = new JMenuItem(); jMenuFile.add(jMenuItemExit); jMenuItemExit.setText("Exit"); jMenuItemExit.setMnemonic( java.awt.event.KeyEvent.VK_X); jMenuItemExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionExit(); } }); } } { jMenuHelp = new JMenu(); jMenuBar.add(jMenuHelp); jMenuHelp.setText("Help"); { jMenuItemTutorial = new JMenuItem(); jMenuHelp.add(jMenuItemTutorial); jMenuItemTutorial.setText("Tutorial"); jMenuItemTutorial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionHelpTutorial(); } }); } { jMenuItemAbout = new JMenuItem(); jMenuHelp.add(jMenuItemAbout); jMenuItemAbout.setText("About..."); jMenuItemAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionHelpAbout(); } }); } } } { jLabel2 = new JLabel(); getContentPane().add(jLabel2, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel2.setText("Setup: "); jLabel2.setFont(new java.awt.Font("Tahoma",1,11)); } { jTextFieldModelSetupCommands = new JTextField(); getContentPane().add(jTextFieldModelSetupCommands, new GridBagConstraints(4, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); jTextFieldModelSetupCommands.setText("setup"); jTextFieldModelSetupCommands.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); jTextFieldModelSetupCommands.setFont(new java.awt.Font("Monospaced",0,11)); } { jTextFieldModelStepCommands = new JTextField(); getContentPane().add(jTextFieldModelStepCommands, new GridBagConstraints(4, 4, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); jTextFieldModelStepCommands.setText("go"); jTextFieldModelStepCommands.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); jTextFieldModelStepCommands.setFont(new java.awt.Font("Monospaced",0,11)); } { jLabel3 = new JLabel(); getContentPane().add(jLabel3, new GridBagConstraints(3, 4, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel3.setText("Step: "); jLabel3.setFont(new java.awt.Font("Tahoma",1,11)); } { jLabel10 = new JLabel(); getContentPane().add(jLabel10, new GridBagConstraints(3, 7, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel10.setText("Stop If: "); jLabel10.setFont(new java.awt.Font("SansSerif",1,11)); } { jTextFieldModelStopCondition = new JTextField(); getContentPane().add(jTextFieldModelStopCondition, new GridBagConstraints(4, 7, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); jTextFieldModelStopCondition.setFont(new java.awt.Font("Monospaced",0,11)); jTextFieldModelStopCondition.setText("count turtles > 100"); jTextFieldModelStopCondition.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { jLabel4 = new JLabel(); getContentPane().add(jLabel4, new GridBagConstraints(3, 5, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel4.setText("Measure: "); jLabel4.setFont(new java.awt.Font("SansSerif",1,11)); } { jTextFieldFitnessMetric = new JTextField(); getContentPane().add(jTextFieldFitnessMetric, new GridBagConstraints(4, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); jTextFieldFitnessMetric.setText("mean [energy] of turtles"); jTextFieldFitnessMetric.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); jTextFieldFitnessMetric.setFont(new java.awt.Font("Monospaced",0,11)); } { jLabelSep = new JLabel(); getContentPane().add(jLabelSep, new GridBagConstraints(1, 9, 4, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); jLabelSep.setBackground(new java.awt.Color(0,0,0)); jLabelSep.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); jLabelSep.setPreferredSize(new java.awt.Dimension(0, 5)); } { jLabel6 = new JLabel(); getContentPane().add(jLabel6, new GridBagConstraints(1, 10, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel6.setText("Search Method Configuration"); jLabel6.setFont(new java.awt.Font("SansSerif",1,14)); jLabel6.setBounds(197, 32, 138, 19); } { jLabel7 = new JLabel(); getContentPane().add(jLabel7, new GridBagConstraints(3, 10, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel7.setText("Objective / Fitness Function"); jLabel7.setFont(new java.awt.Font("SansSerif",1,14)); } { jPanelSampling = new JPanel(); getContentPane().add(jPanelSampling, new GridBagConstraints(3, 13, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jPanelSampling.setOpaque(false); { ComboBoxModel jComboBoxSamplingMethodModel = new DefaultComboBoxModel( new String[] { "Fixed Sampling" }); //, "Adaptive Sampling" }); jComboBoxFitnessSamplingMethod = new JComboBox(); jPanelSampling.add(jComboBoxFitnessSamplingMethod); jComboBoxFitnessSamplingMethod.setModel(jComboBoxSamplingMethodModel); jComboBoxFitnessSamplingMethod.setEditable(false); jComboBoxFitnessSamplingMethod.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { actionSamplingMethodChanged(); } }); } { jTextFieldFitnessSamplingRepetitions = new JTextField(); jPanelSampling.add(jTextFieldFitnessSamplingRepetitions); jTextFieldFitnessSamplingRepetitions.setText("10"); jTextFieldFitnessSamplingRepetitions.setPreferredSize(new java.awt.Dimension(50, 20)); jTextFieldFitnessSamplingRepetitions.setFont(new java.awt.Font("Monospaced",0,11)); jTextFieldFitnessSamplingRepetitions.setToolTipText("How many times should the model be run, for a given setting of the parameters?"); } { jLabel8 = new JLabel(); jPanelSampling.add(jLabel8); jLabel8.setText("replicates"); } } { jScrollPane1 = new JScrollPane(); getContentPane().add(jScrollPane1, new GridBagConstraints(1, 12, 1, 4, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); jScrollPane1.setPreferredSize(new java.awt.Dimension(202, 58)); { TableModel jTableSearchMethodParamsModel = new DefaultTableModel( new String[][] { { "population", "100" }, { "mutation-rate", "1.0" } , { "crossover-rate", "0.70" }}, new String[] { "Parameter", "Value" }); jTableSearchMethodParams = new JTable(); jScrollPane1.setViewportView(jTableSearchMethodParams); jTableSearchMethodParams.setModel(jTableSearchMethodParamsModel); jTableSearchMethodParams.getColumn(jTableSearchMethodParams.getColumnName(0)).setPreferredWidth(120); } } { jButtonRunNow = new JButton(); getContentPane().add(jButtonRunNow, new GridBagConstraints(3, 18, 2, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0)); jButtonRunNow.setText("Run BehaviorSearch"); jButtonRunNow.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionRunNow(); } }); } { ComboBoxModel jComboBoxMinMaxModel = new DefaultComboBoxModel( new String[] { "Minimize Fitness", "Maximize Fitness" }); jComboBoxFitnessMinMax = new JComboBox(); getContentPane().add(jComboBoxFitnessMinMax, new GridBagConstraints(4, 11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jComboBoxFitnessMinMax.setModel(jComboBoxMinMaxModel); } { jPanelMeasureAfter = new JPanel(); getContentPane().add(jPanelMeasureAfter, new GridBagConstraints(4, 8, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); jPanelMeasureAfter.setOpaque(false); { jTextFieldModelStepLimit = new JTextField(); jPanelMeasureAfter.add(jTextFieldModelStepLimit); jTextFieldModelStepLimit.setText("100"); jTextFieldModelStepLimit.setPreferredSize(new java.awt.Dimension(50, 20)); jTextFieldModelStepLimit.setFont(new java.awt.Font("Monospaced",0,11)); } { jLabel5 = new JLabel(); jPanelMeasureAfter.add(jLabel5); jLabel5.setText("model steps"); } } { jLabel12 = new JLabel(); getContentPane().add(jLabel12, new GridBagConstraints(1, 2, 4, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); jLabel12.setBackground(new java.awt.Color(0,0,0)); jLabel12.setPreferredSize(new java.awt.Dimension(0,5)); jLabel12.setBorder(new SoftBevelBorder(BevelBorder.LOWERED,null,null,null,null)); } { jTextFieldModelFile = new JTextField(); getContentPane().add(jTextFieldModelFile, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); jTextFieldModelFile.setText("Model.nlogo"); jTextFieldModelFile.setToolTipText("Path to .nlogo file - may be specified relative to the folder containing the '.bsearch' file"); } { jButtonBrowseModel = new JButton(); getContentPane().add(jButtonBrowseModel, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 10, 0, 0), 0, 0)); jButtonBrowseModel.setText("Browse for model..."); jButtonBrowseModel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionBrowseModel(); } }); } { jScrollPane2 = new JScrollPane(); getContentPane().add(jScrollPane2, new GridBagConstraints(1, 4, 1, 4, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); { jTextAreaParamSpecs = new JTextArea(); jTextAreaParamSpecs.setText("[\"variable1\" [0 1 10]] \n[\"variable2\" [0.0 \"C\" 5.0]] \n[\"variable3\" \"moore\" \"vonN\"] \n[\"variable4\" true false]"); jTextAreaParamSpecs.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); jTextAreaParamSpecs.setFont(new java.awt.Font("Monospaced",0,11)); jTextAreaParamSpecs.setAutoscrolls(true); jScrollPane2.setViewportView(jTextAreaParamSpecs); } } { jLabel11 = new JLabel(); getContentPane().add(jLabel11, new GridBagConstraints(1, 17, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel11.setText("Search Encoding Representation"); jLabel11.setFont(new java.awt.Font("SansSerif",1,11)); } { ComboBoxModel jComboBoxChromosomeTypeModel = new DefaultComboBoxModel( new String[] { "MixedTypeChromosome" }); jComboBoxChromosomeType = new JComboBox(); getContentPane().add(jComboBoxChromosomeType, new GridBagConstraints(1, 18, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jComboBoxChromosomeType.setModel(jComboBoxChromosomeTypeModel); } { jLabel13 = new JLabel(); getContentPane().add(jLabel13, new GridBagConstraints(3, 12, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel13.setText("Collected measure: "); jLabel13.setFont(new java.awt.Font("SansSerif",1,11)); } { ComboBoxModel jComboBox1Model = new DefaultComboBoxModel( new String[] { "Item One", "Item Two" }); jComboBoxFitnessCollecting = new JComboBox(); getContentPane().add(jComboBoxFitnessCollecting, new GridBagConstraints(4, 12, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jComboBoxFitnessCollecting.setModel(jComboBox1Model); } { jLabel14 = new JLabel(); getContentPane().add(jLabel14, new GridBagConstraints(3, 14, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel14.setText("Combine replicates: "); jLabel14.setFont(new java.awt.Font("SansSerif",1,11)); } { jLabel15 = new JLabel(); getContentPane().add(jLabel15, new GridBagConstraints(3, 8, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel15.setText("Step Limit: "); jLabel15.setFont(new java.awt.Font("SansSerif",1,11)); } { jLabel16 = new JLabel(); getContentPane().add(jLabel16, new GridBagConstraints(3, 11, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel16.setText("Goal: "); jLabel16.setFont(new java.awt.Font("SansSerif",1,11)); } { ComboBoxModel jComboBox1Model = new DefaultComboBoxModel( new String[] { "Item One", "Item Two" }); jComboBoxFitnessCombineReplications = new JComboBox(); getContentPane().add(jComboBoxFitnessCombineReplications, new GridBagConstraints(4, 14, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jComboBoxFitnessCombineReplications.setModel(jComboBox1Model); } { jLabel17 = new JLabel(); getContentPane().add(jLabel17, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel17.setText("Measure If: "); jLabel17.setFont(new java.awt.Font("SansSerif",1,11)); } { jTextFieldMeasureIf = new JTextField(); getContentPane().add(jTextFieldMeasureIf, new GridBagConstraints(4, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); jTextFieldMeasureIf.setFont(new java.awt.Font("Monospaced",0,11)); jTextFieldMeasureIf.setText("true"); jTextFieldMeasureIf.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); jTextFieldMeasureIf.setToolTipText("e.g. \"(ticks mod 100) = 0\", or \"member? ticks [50 100 200]\""); } { jLabel9 = new JLabel(); getContentPane().add(jLabel9, new GridBagConstraints(3, 16, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel9.setText("Evaluation limit: "); jLabel9.setFont(new java.awt.Font("SansSerif",1,11)); } { jPanel1 = new JPanel(); FlowLayout jPanel1Layout = new FlowLayout(); jPanel1Layout.setAlignment(FlowLayout.LEFT); jPanel1.setLayout(jPanel1Layout); getContentPane().add(jPanel1, new GridBagConstraints(4, 16, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); jPanel1.setOpaque(false); { jTextFieldEvaluationLimit = new JTextField(); jPanel1.add(jTextFieldEvaluationLimit); jTextFieldEvaluationLimit.setFont(new java.awt.Font("Monospaced",0,11)); jTextFieldEvaluationLimit.setText("300"); jTextFieldEvaluationLimit.setPreferredSize(new java.awt.Dimension(50, 20)); jTextFieldEvaluationLimit.setToolTipText("Stop the search after this many model runs have occurred."); } { jLabel18 = new JLabel(); jPanel1.add(jLabel18); jLabel18.setText("model runs"); } } { jLabel1 = new JLabel(); getContentPane().add(jLabel1, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel1.setText("Parameter Specification"); jLabel1.setBounds(197, 32, 138, 19); jLabel1.setFont(new java.awt.Font("SansSerif",1,14)); jLabel1.setForeground(new java.awt.Color(0,0,0)); jLabel1.setHorizontalAlignment(SwingConstants.CENTER); } { jButtonHelpSearchSpace = new JButton(); getContentPane().add(jButtonHelpSearchSpace, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jButtonHelpSearchSpace.setText("?"); jButtonHelpSearchSpace.setToolTipText("Help about Search Space Specification"); jButtonHelpSearchSpace.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionHelpSearchSpace(); } }); } { jButtonHelpSearchMethod = new JButton(); getContentPane().add(jButtonHelpSearchMethod, new GridBagConstraints(1, 11, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jButtonHelpSearchMethod.setText("?"); jButtonHelpSearchMethod.setToolTipText("Help about this Search Method"); jButtonHelpSearchMethod.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionHelpSearchMethod(); } }); } { ComboBoxModel jComboBoxSearchMethodModel = new DefaultComboBoxModel( new String[] { "xxxx", "yyyy" }); jComboBoxSearchMethodType = new JComboBox(); getContentPane().add(jComboBoxSearchMethodType, new GridBagConstraints(1, 11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jComboBoxSearchMethodType.setModel(jComboBoxSearchMethodModel); jComboBoxSearchMethodType.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { actionUpdateSearchMethodParams(); } }); } { jButtonHelpEvaluation = new JButton(); getContentPane().add(jButtonHelpEvaluation, new GridBagConstraints(4, 10, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jButtonHelpEvaluation.setText("?"); jButtonHelpEvaluation.setToolTipText("Help about Evaluation"); jButtonHelpEvaluation.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionHelpEvaluation(); } }); } { jButtonSuggestParamRanges = new JButton(); getContentPane().add(jButtonSuggestParamRanges, new GridBagConstraints(1, 8, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jButtonSuggestParamRanges.setText("Load param ranges from model interface"); jButtonSuggestParamRanges.setToolTipText("Sets the search space specification based on sliders, choosers, etc., from model interface tab."); jButtonSuggestParamRanges.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionSuggestParamRanges(); } }); } { jCheckBoxCaching = new JCheckBox(); getContentPane().add(jCheckBoxCaching, new GridBagConstraints(1, 16, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jCheckBoxCaching.setText("Use fitness caching"); jCheckBoxCaching.setToolTipText("If fitness caching is turned on then the result of running the model with certain parameters gets saved so the model won't be re-run if a run with those same parameters are requested again."); jCheckBoxCaching.setSelected(true); } { jLabel19 = new JLabel(); getContentPane().add(jLabel19, new GridBagConstraints(3, 17, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jLabel19.setText("BestChecking replicates: "); jLabel19.setFont(new java.awt.Font("SansSerif",1,11)); } { jTextFieldBestChecking = new JTextField(); getContentPane().add(jTextFieldBestChecking, new GridBagConstraints(4, 17, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jTextFieldBestChecking.setFont(new java.awt.Font("Monospaced",0,11)); jTextFieldBestChecking.setText("10"); jTextFieldBestChecking.setPreferredSize(new java.awt.Dimension(50,20)); jTextFieldBestChecking.setOpaque(true); jTextFieldBestChecking.setMinimumSize(new java.awt.Dimension(50, 27)); jTextFieldBestChecking.setToolTipText("BestChecking: running another N independent model runs to get an unbiased estimate of the objective function for each \"best\" individual that's found."); } { jButtonHelpSearchSpaceRepresentation = new JButton(); getContentPane().add(jButtonHelpSearchSpaceRepresentation, new GridBagConstraints(1, 18, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); jButtonHelpSearchSpaceRepresentation.setText("?"); jButtonHelpSearchSpaceRepresentation.setToolTipText("Help about this Search Space Representation"); jButtonHelpSearchSpaceRepresentation.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { actionHelpSearchSpaceRepresentation(); } }); } { jPanelDeriv = new JPanel(); jPanelDeriv.setBackground(new Color(214,217,223)); jPanelDeriv.setLayout(new BorderLayout()); getContentPane().add(jPanelDeriv, new GridBagConstraints(3, 15, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); { jCheckBoxTakeDerivative = new JCheckBox(); JPanel temp = new JPanel(); temp.setLayout( new FlowLayout(FlowLayout.CENTER, 40, 10) ); temp.add(jCheckBoxTakeDerivative); jPanelDeriv.add(temp, BorderLayout.NORTH); jCheckBoxTakeDerivative.setText("Take derivative?"); jCheckBoxTakeDerivative.setToolTipText("Instead of using the measure you've specified, use the *change* in that measure (with respect to a certain parameter) for your objective function."); jCheckBoxTakeDerivative.setPreferredSize(new java.awt.Dimension(134, 22)); jCheckBoxTakeDerivative.setFont(new java.awt.Font("SansSerif",1,11)); jCheckBoxTakeDerivative.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { updateFitnessDerivativePanel(); } }); jCheckBoxFitnessDerivativeUseAbs = new JCheckBox(); jCheckBoxFitnessDerivativeUseAbs.setText("Use ABS value?"); jCheckBoxFitnessDerivativeUseAbs.setToolTipText("You might want to take the absolute value if you don't care about the direction of the measured change... e.g., for trying to find phase transitions"); jCheckBoxTakeDerivative.setFont(new java.awt.Font("SansSerif",1,11)); temp.add(jCheckBoxFitnessDerivativeUseAbs); } { jPanelDeriv2 = new JPanel(); jPanelDeriv2.setOpaque(false); jPanelDeriv.add(jPanelDeriv2,BorderLayout.CENTER); { jLabelDerivWRT = new JLabel(); jPanelDeriv2.add(jLabelDerivWRT); jLabelDerivWRT.setText("w.r.t."); } { ComboBoxModel jComboBoxFitnessDerivativeParameterModel = new DefaultComboBoxModel( new String[] { "----" }); jComboBoxFitnessDerivativeParameter = new JComboBox(); jComboBoxFitnessDerivativeParameter.setToolTipText("Which parameter should be varied by a small amount to see how much change results?"); Dimension d = jComboBoxFitnessDerivativeParameter.getPreferredSize(); jComboBoxFitnessDerivativeParameter.setPreferredSize(new Dimension(200,d.height)); jPanelDeriv2.add(jComboBoxFitnessDerivativeParameter); jComboBoxFitnessDerivativeParameter.setModel(jComboBoxFitnessDerivativeParameterModel); jComboBoxFitnessDerivativeParameter.addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { updateFitnessDerivativeParameterChoices(); } public void focusLost(FocusEvent arg0) { } }); } { jLabelDerivDELTA = new JLabel(); jPanelDeriv2.add(jLabelDerivDELTA); jLabelDerivDELTA.setText("\u0394="); } { jTextFieldFitnessDerivativeDelta = new JTextField(); jPanelDeriv2.add(jTextFieldFitnessDerivativeDelta); jTextFieldFitnessDerivativeDelta.setText("0.100"); jTextFieldFitnessDerivativeDelta.setToolTipText("How much should be subtracted from the parameter's value, to get the measured change?"); int prefHeight = jTextFieldFitnessDerivativeDelta.getPreferredSize().height; jTextFieldFitnessDerivativeDelta.setPreferredSize(new Dimension(50, prefHeight)); } } } pack(); this.setSize(760, 630); } catch (Exception e) { e.printStackTrace(); } } /////////////////////////////////////////////////////////////////////////////////////////////// //the special comment on the next line marks the remaining code so the Jigloo gui builder won't try to parse it. //$hide>>$ private String defaultProtocolXMLForNewSearch; private File currentFile; private String lastSavedText; private HashMap<String,SearchMethod> searchMethodChoices = new HashMap<String, SearchMethod>(); BehaviorSearch.RunOptions runOptions = null; // keep track of what options they ran the search with last time, // and use those as the offered options when they run again. private File defaultUserDocumentsFolder = new JFileChooser().getCurrentDirectory(); public static void handleError(String msg, java.awt.Container parentContainer) { JOptionPane wrappingTextOptionPane = new JOptionPane(msg, JOptionPane.ERROR_MESSAGE) { private static final long serialVersionUID = 1L; @Override public int getMaxCharactersPerLineCount() { return 58; } }; javax.swing.JDialog dialog = wrappingTextOptionPane.createDialog(parentContainer, "Error!"); dialog.setVisible(true); // javax.swing.JOptionPane.showMessageDialog(this, msg, "ERROR!", JOptionPane.ERROR_MESSAGE); } private void handleError(String msg) { handleError(msg,this); } private void finishInitWork() { setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(GeneralUtils.getResource("icon_behaviorsearch.png").getAbsolutePath())); // Set a few keyboard shortcuts for menu item jMenuItemNew.setAccelerator( javax.swing.KeyStroke.getKeyStroke( 'N' , java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() ) ) ; jMenuItemOpen.setAccelerator( javax.swing.KeyStroke.getKeyStroke( 'O' , java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() ) ) ; jMenuItemSave.setAccelerator( javax.swing.KeyStroke.getKeyStroke( 'S' , java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() ) ) ; // load our default 'new' search configuration from a file try { defaultProtocolXMLForNewSearch = GeneralUtils.stringContentsOfFile(GeneralUtils.getResource("defaultNewSearch.xml")); } catch (java.io.FileNotFoundException ex) { handleError(ex.getMessage()); System.exit(1); } initComboBoxes(); actionNew(); } /* * Some of the choices for combo boxes need to be filled in dynamically, based on reading files and such. */ private void initComboBoxes() { ////////////// SearchMethods DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxSearchMethodType.getModel(); model.removeAllElements(); List<String> names = null; try { names = SearchMethodLoader.getAllSearchMethodNames(); } catch (BehaviorSearchException ex) { handleError(ex.getMessage()); System.exit(1); } for (String name: names) { try { searchMethodChoices.put(name, SearchMethodLoader.createFromName(name)); model.addElement(name); } catch (BehaviorSearchException ex) { handleError(ex.getMessage()); } } ////////////// ChromosomeType model = (DefaultComboBoxModel) jComboBoxChromosomeType.getModel(); model.removeAllElements(); names = null; try { names = bsearch.representations.ChromosomeTypeLoader.getAllChromosomeTypes(); } catch (BehaviorSearchException ex) { handleError(ex.getMessage()); System.exit(1); } for (String name: names) { model.addElement(name); } ////////////// FitnessCollecting model = (DefaultComboBoxModel) jComboBoxFitnessCollecting.getModel(); model.removeAllElements(); for (SearchProtocol.FITNESS_COLLECTING f: SearchProtocol.FITNESS_COLLECTING.values()) { model.addElement(f.toString()); } ////////////// FitnessCollecting model = (DefaultComboBoxModel) jComboBoxFitnessCombineReplications.getModel(); model.removeAllElements(); for (SearchProtocol.FITNESS_COMBINE_REPLICATIONS f: SearchProtocol.FITNESS_COMBINE_REPLICATIONS.values()) { model.addElement(f.toString()); } } private void updateFitnessDerivativePanel() { boolean enabled = jCheckBoxTakeDerivative.isSelected(); jLabelDerivWRT.setEnabled(enabled); jLabelDerivDELTA.setEnabled(enabled); jComboBoxFitnessDerivativeParameter.setEnabled(enabled); jTextFieldFitnessDerivativeDelta.setEnabled(enabled); jCheckBoxFitnessDerivativeUseAbs.setEnabled(enabled); if (enabled) { updateFitnessDerivativeParameterChoices(); } } private void updateFitnessDerivativeParameterChoices() { try { Object oldChoice = jComboBoxFitnessDerivativeParameter.getSelectedItem(); SearchSpace ss = new SearchSpace(java.util.Arrays.asList(jTextAreaParamSpecs.getText().split("\n"))); DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxFitnessDerivativeParameter.getModel(); model.removeAllElements(); for (ParameterSpec spec : ss.getParamSpecs()) { model.addElement(spec.getParameterName()); } model.addElement("@MUTATE@"); jComboBoxFitnessDerivativeParameter.setSelectedItem(oldChoice); } catch (Exception ex) { } } private void actionNew() { if (!checkDiscardOkay()) { return; } currentFile = null; /* jTextAreaParamSpecs.setText("[\"integerParameter\" [0 1 10]] \n" + "[\"continuousParameter\" [0.0 \"C\" 1.0]] \n " + "[\"choiceParameter\" \"near\" \"far\"] \n"); */ SearchProtocol protocol; try { protocol = SearchProtocol.load(defaultProtocolXMLForNewSearch); loadProtocol(protocol); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Error loading default XML protocol to initialize UI!"); } catch (SAXException e) { e.printStackTrace(); throw new IllegalStateException("Error loading default XML protocol to initialize UI!"); } this.setTitle("Untitled" + getWindowTitleSuffix()); } private void actionOpen() { if (!checkDiscardOkay()) { return; } JFileChooser chooser = new JFileChooser(); if (currentFile != null) { chooser.setSelectedFile(currentFile); } chooser.addChoosableFileFilter(new javax.swing.filechooser.FileNameExtensionFilter( "Completed search configurations (*.xml)", "xml")); chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter( "Search protocols (*.bsearch)", "bsearch")); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { openFile(chooser.getSelectedFile()); } } private void actionOpenExample() { if (!checkDiscardOkay()) { return; } JFileChooser chooser = new JFileChooser(GeneralUtils.attemptResolvePathFromBSearchRoot("examples")); chooser.addChoosableFileFilter(new javax.swing.filechooser.FileNameExtensionFilter( "Completed search configurations (*.xml)", "xml")); chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter( "Search protocols (*.bsearch)", "bsearch")); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { openFile(chooser.getSelectedFile()); } } private void openFile(File fProtocol) { try { SearchProtocol protocol = SearchProtocol.loadFile(fProtocol.getPath()); currentFile = fProtocol; loadProtocol(protocol); this.setTitle(currentFile.getName() + getWindowTitleSuffix()); } catch (IOException e) { handleError("IO Error occurred attempting to load file: " + fProtocol.getPath()); e.printStackTrace(); } catch (SAXException e) { handleError("XML Parsing error occurred attempting to load file: " + fProtocol.getPath()); e.printStackTrace(); } } private void loadProtocol(SearchProtocol protocol) { jTextFieldModelFile.setText(protocol.modelFile); StringBuilder sb = new StringBuilder(); for (String s : protocol.paramSpecStrings) { sb.append(s); sb.append("\n"); } jTextAreaParamSpecs.setText(sb.toString()); jTextFieldModelStepCommands.setText(protocol.modelStepCommands); jTextFieldModelSetupCommands.setText(protocol.modelSetupCommands); jTextFieldModelStopCondition.setText(protocol.modelStopCondition); jTextFieldModelStepLimit.setText(Integer.toString(protocol.modelStepLimit)); jTextFieldFitnessMetric.setText(protocol.modelMetricReporter); jTextFieldMeasureIf.setText(protocol.modelMeasureIf); jComboBoxFitnessMinMax.setSelectedItem(protocol.fitnessMinimized ? "Minimize Fitness" : "Maximize Fitness"); jComboBoxFitnessCollecting.setSelectedItem(protocol.fitnessCollecting.toString()); jTextFieldFitnessSamplingRepetitions.setText(Integer.toString(protocol.fitnessSamplingReplications)); jComboBoxFitnessSamplingMethod.setSelectedItem((protocol.fitnessSamplingReplications != 0) ? "Fixed Sampling" : "Adaptive Sampling"); jComboBoxFitnessCombineReplications.setSelectedItem(protocol.fitnessCombineReplications.toString()); jCheckBoxTakeDerivative.setSelected(protocol.fitnessDerivativeParameter.length() > 0); jCheckBoxFitnessDerivativeUseAbs.setSelected(protocol.fitnessDerivativeUseAbs); updateFitnessDerivativePanel(); jComboBoxFitnessDerivativeParameter.setSelectedItem(protocol.fitnessDerivativeParameter); jTextFieldFitnessDerivativeDelta.setText(Double.toString(protocol.fitnessDerivativeDelta)); jComboBoxSearchMethodType.setSelectedItem(protocol.searchMethodType); jComboBoxChromosomeType.setSelectedItem(protocol.chromosomeType); updateSearchMethodParamTable(searchMethodChoices.get(protocol.searchMethodType),protocol.searchMethodParams); jCheckBoxCaching.setSelected(protocol.caching); jTextFieldBestChecking.setText(Integer.toString(protocol.bestCheckingNumReplications)); jTextFieldEvaluationLimit.setText(Integer.toString(protocol.evaluationLimit)); lastSavedText = protocol.toXMLString(); runOptions = null; // reset the runOptions to defaults, when a different Protocol is loaded } private void actionSave() { if (currentFile == null) { actionSaveAs(); } else { doSave(); } } private void actionSaveAs() { JFileChooser chooser = new JFileChooser("./experiments/"); if (currentFile != null) { chooser.setSelectedFile(currentFile); } else { chooser.setSelectedFile(new File("Untitled.bsearch")); } chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter( "Search protocols (*.bsearch)", "bsearch")); int returnVal = chooser.showSaveDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { currentFile = chooser.getSelectedFile(); doSave(); this.setTitle(currentFile.getName() + getWindowTitleSuffix()); } } private SearchProtocol createProtocolFromFormData() throws UIConstraintException { HashMap<String, String> searchMethodParams = new java.util.LinkedHashMap<String, String>(); TableModel model = jTableSearchMethodParams.getModel(); for (int i = 0; i < model.getRowCount(); i++) { searchMethodParams.put(model.getValueAt(i, 0).toString().trim(), model.getValueAt(i, 1).toString()); } int modelStepLimit = 0; try { modelStepLimit = Integer.valueOf(jTextFieldModelStepLimit.getText()); if (modelStepLimit < 0) { throw new NumberFormatException(); } } catch (NumberFormatException ex) { throw new UIConstraintException("STEP LIMIT should be a non-negative integer.", "Error: can't create search protocol"); } int fitnessSamplingRepetitions = 0; if (jComboBoxFitnessSamplingMethod.getSelectedItem().toString().equals("Fixed Sampling")) { try { fitnessSamplingRepetitions = Integer.valueOf(jTextFieldFitnessSamplingRepetitions.getText()); if (fitnessSamplingRepetitions < 0) { throw new NumberFormatException(); } } catch (NumberFormatException ex) { throw new UIConstraintException("SAMPLING REPETITIONS should be a positive integer, or 0 if using adaptive sampling.", "Error: can't create protocol"); } } boolean caching = jCheckBoxCaching.isSelected(); int evaluationLimit = 0; try { evaluationLimit = Integer.valueOf(jTextFieldEvaluationLimit.getText()); if (evaluationLimit <= 0) { throw new NumberFormatException(); } } catch (NumberFormatException ex) { throw new UIConstraintException("EVALUATION LIMIT should be a positive integer.", "Error: can't create search protocol"); } int bestCheckingNumReplications = 0; try { bestCheckingNumReplications = Integer.valueOf(jTextFieldBestChecking.getText()); if (bestCheckingNumReplications < 0) { throw new NumberFormatException(); } } catch (NumberFormatException ex) { throw new UIConstraintException("The number of 'BEST CHECKING' replicates should be a non-negative integer.", "Error: can't create search protocol"); } double fitnessDerivDelta = 0.0; if (jCheckBoxTakeDerivative.isSelected()) { try { fitnessDerivDelta = Double.valueOf(jTextFieldFitnessDerivativeDelta.getText()); } catch (NumberFormatException ex) { throw new UIConstraintException("The DELTA value (for taking the derivative of the objective fucntion with respect to a parameter) needs to be a number", "Error: can't create search protocol"); } } SearchProtocol protocol = new SearchProtocol(jTextFieldModelFile.getText(), java.util.Arrays.asList(jTextAreaParamSpecs.getText().split("\n")), jTextFieldModelStepCommands.getText(), jTextFieldModelSetupCommands.getText(), jTextFieldModelStopCondition.getText(), modelStepLimit, jTextFieldFitnessMetric.getText(), jTextFieldMeasureIf.getText(), jComboBoxFitnessMinMax.getSelectedItem().toString().equals("Minimize Fitness"), fitnessSamplingRepetitions, SearchProtocol.FITNESS_COLLECTING.valueOf(jComboBoxFitnessCollecting.getSelectedItem().toString()), SearchProtocol.FITNESS_COMBINE_REPLICATIONS.valueOf(jComboBoxFitnessCombineReplications.getSelectedItem().toString()), jCheckBoxTakeDerivative.isSelected()?jComboBoxFitnessDerivativeParameter.getSelectedItem().toString():"", fitnessDerivDelta, jCheckBoxFitnessDerivativeUseAbs.isSelected(), jComboBoxSearchMethodType.getSelectedItem().toString(), searchMethodParams, jComboBoxChromosomeType.getSelectedItem().toString(), caching, evaluationLimit, bestCheckingNumReplications ); return protocol; } private void doSave() { java.io.FileWriter fout; try { fout = new java.io.FileWriter(currentFile); SearchProtocol protocol = createProtocolFromFormData(); protocol.save(fout); fout.close(); lastSavedText = protocol.toXMLString(); javax.swing.JOptionPane.showMessageDialog(this, "Saved successfully.", "Saved.", JOptionPane.PLAIN_MESSAGE); } catch (IOException ex) { ex.printStackTrace(); handleError("IO Error occurred attempting to save file: " + currentFile.getPath()); } catch (UIConstraintException ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), ex.getTitle(), JOptionPane.WARNING_MESSAGE); } } private void actionExit() { if (!checkDiscardOkay()) { return; } System.exit(0); } private boolean protocolChangedSinceLastSave() { String xmlStr = ""; try { xmlStr = createProtocolFromFormData().toXMLString(); } catch (UIConstraintException ex) { // if we can't create a valid protocol object from the form data, assume the user has changed something... return true; } //System.out.println(xmlStr); //System.out.println("--"); //System.out.println(lastSavedText); // Note: lastSavedText == null ONLY when the GUI is being loaded for the first time. return (lastSavedText != null && !lastSavedText.equals(xmlStr)); } private boolean checkDiscardOkay() { if (protocolChangedSinceLastSave()) { if (JOptionPane.showConfirmDialog(this, "Discard changes you've made to this search experiment?", "Discard changes?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) { return false; } } return true; } private void updateSearchMethodParamTable(SearchMethod searchMethod, HashMap<String,String> searchMethodParams) { //if the search method in the protocol is missing some parameters, fill them in with defaults HashMap<String, String> defaultParams = searchMethod.getSearchParams(); for (String key : defaultParams.keySet()) { if (!searchMethodParams.containsKey(key)) { searchMethodParams.put(key, defaultParams.get(key)); } } DefaultTableModel model = (DefaultTableModel) jTableSearchMethodParams.getModel(); model.setRowCount(0); for (String s: searchMethodParams.keySet()) { model.addRow(new Object[] { s , searchMethodParams.get(s) } ); } } protected void actionUpdateSearchMethodParams() { if (!searchMethodChoices.isEmpty()) // make sure everything has been initialized... { SearchMethod searchMethod = searchMethodChoices.get(jComboBoxSearchMethodType.getSelectedItem()); updateSearchMethodParamTable(searchMethod,searchMethod.getSearchParams()); } } protected void actionSamplingMethodChanged() { if (jComboBoxFitnessSamplingMethod.getSelectedItem().equals("Adaptive Sampling")) { SearchMethod searchMethod = searchMethodChoices.get(jComboBoxSearchMethodType.getSelectedItem()); if (!searchMethod.supportsAdaptiveSampling()) { JOptionPane.showMessageDialog(this, "The currently selected search method doesn't support 'Adaptive Sampling'.", "WARNING", JOptionPane.WARNING_MESSAGE); jComboBoxFitnessSamplingMethod.setSelectedItem("Fixed Sampling"); } else { jTextFieldFitnessSamplingRepetitions.setText("0"); jTextFieldFitnessSamplingRepetitions.setEnabled(false); } } else { jTextFieldFitnessSamplingRepetitions.setEnabled(true); if (jTextFieldFitnessSamplingRepetitions.getText().trim().equals("0")) { jTextFieldFitnessSamplingRepetitions.setText("10"); } } } protected void actionBrowseModel() { JFileChooser chooser = new JFileChooser("."); chooser.setSelectedFile(new File(jTextFieldModelFile.getText())); chooser.setFileFilter(new FileNameExtensionFilter("NetLogo Models", "nlogo")); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { jTextFieldModelFile.setText(chooser.getSelectedFile().getPath()); } } protected void actionSuggestParamRanges() { try { jTextAreaParamSpecs.setText(bsearch.nlogolink.Utils.getDefaultConstraintsText(jTextFieldModelFile.getText())); } catch (NetLogoLinkException e) { handleError(e.getMessage()); } } protected void actionRunNow() { SearchProtocol protocol; try { protocol = createProtocolFromFormData(); } catch (UIConstraintException e) { handleError("Error creating SearchProtocol: " + e.getMessage()); return; } /* while (currentFile == null || protocolChangedSinceLastSave()) { int choice = javax.swing.JOptionPane.showConfirmDialog(this, "Protocol must be saved before running the search. Save now?" , "Save protocol?", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.OK_OPTION) { actionSave(); } else { return; } } */ if (runOptions == null) { runOptions = new BehaviorSearch.RunOptions(); //suggest a filename stem for output files, which users can change. if (currentFile != null) { String fnameStem = currentFile.getPath(); fnameStem = fnameStem.substring(0, fnameStem.lastIndexOf('.')); fnameStem = GeneralUtils.attemptResolvePathFromStartupFolder(fnameStem); runOptions.outputStem = fnameStem; } else { //TODO: Use folder where the NetLogo model is located instead? runOptions.outputStem = new File(defaultUserDocumentsFolder, "mySearchOutput").getPath(); } } if (currentFile != null) { runOptions.protocolFilename = this.currentFile.getAbsolutePath(); } if (RunOptionsDialog.showDialog(this, runOptions)) { GUIProgressDialog dialog = new GUIProgressDialog(this); dialog.setLocationRelativeTo(null); dialog.startSearchTask(protocol, runOptions); dialog.setVisible(true); } } private void actionHelpSearchMethod() { SearchMethod sm = searchMethodChoices.get(jComboBoxSearchMethodType.getSelectedItem()); HelpInfoDialog.showHelp(this, "Help about " + sm.getName(), sm.getHTMLHelpText()); } private void actionHelpSearchSpaceRepresentation() { String chromosomeType = jComboBoxChromosomeType.getSelectedItem().toString(); try { ChromosomeFactory factory = ChromosomeTypeLoader.createFromName(chromosomeType); HelpInfoDialog.showHelp(this, "Help about " + chromosomeType, factory.getHTMLHelpText() + "<BR><BR>"); } catch (BehaviorSearchException ex) { handleError(ex.toString()); } } private void actionHelpSearchSpace() { HelpInfoDialog.showHelp(this, "Help about search space specification", "<HTML><BODY>" + "Specifying the range of parameters to be searched works much the same as the BehaviorSpace tool in NetLogo:" + "<PRE> [ \"PARAM_NAME\" VALUE1 VALUE2 VALUE3 ... ] </PRE>" + "or <PRE> [ \"PARAM_NAME\" [RANGE_START INCREMENT RANGE_END] ] </PRE>" + "<P>One slight difference is that INCREMENT may be \"C\", which means to search the range continously " + "(or at least with fine resolution, if the chromosomal representation doesn't allow for continuous parameters)</P>" + "</BODY></HTML>"); } private void actionHelpEvaluation() { //TODO: Better help docs HelpInfoDialog.showHelp(this, "Help about fitness evaluation", "<HTML><BODY>" + "An objective function must condense the data collected from multiple model runs into a single number, " + "which is what the search process will either attempt to minimize or maximize." + "</BODY></HTML>"); } private void actionHelpTutorial() { org.nlogo.swing.BrowserLauncher.openURL(this, GeneralUtils.attemptResolvePathFromBSearchRoot("documentation/tutorial.html"), true); } private void actionHelpAbout() { HelpAboutDialog.showAboutDialog(this); } private class UIConstraintException extends Exception { private String title; public UIConstraintException(String msg, String title) { super(msg); this.title = title; } public String getTitle() { return title; } private static final long serialVersionUID = 1L; } //$hide<<$ }
40.091231
229
0.722433
bb38d9c410f9772f8476efc9f4f42f07a8690c3e
2,058
package org.smartregister.chw.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONObject; import org.smartregister.chw.core.custom_views.NavigationMenu; import org.smartregister.chw.presenter.IssueReferralActivityPresenter; import org.smartregister.chw.referral.activity.BaseIssueReferralActivity; import org.smartregister.chw.referral.interactor.BaseIssueReferralInteractor; import org.smartregister.chw.referral.model.BaseIssueReferralModel; import org.smartregister.chw.referral.presenter.BaseIssueReferralPresenter; import org.smartregister.chw.referral.util.Constants; import org.smartregister.family.util.JsonFormUtils; public class ReferralRegistrationActivity extends BaseIssueReferralActivity { public static String BASE_ENTITY_ID; public static void startGeneralReferralFormActivityForResults(Activity activity, String baseEntityID, JSONObject formJsonObject, boolean useCustomLayout) { BASE_ENTITY_ID = baseEntityID; Intent intent = new Intent(activity, ReferralRegistrationActivity.class); intent.putExtra(Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); intent.putExtra(Constants.ActivityPayload.JSON_FORM, formJsonObject.toString()); intent.putExtra(Constants.ActivityPayload.ACTION, Constants.ActivityPayloadType.REGISTRATION); intent.putExtra(Constants.ActivityPayload.USE_CUSTOM_LAYOUT, useCustomLayout); activity.startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); NavigationMenu.getInstance(this, null, null); } @NotNull @Override public BaseIssueReferralPresenter presenter() { return new IssueReferralActivityPresenter(BASE_ENTITY_ID, this, BaseIssueReferralModel.class, new BaseIssueReferralInteractor()); } }
46.772727
159
0.806608
7fa1fb97e0a4a42240e20fd73b3cb12889769ed9
2,146
package io.github.thatsmusic99.headsplus.config.headsx.icons; import io.github.thatsmusic99.headsplus.HeadsPlus; import io.github.thatsmusic99.headsplus.commands.maincommand.DebugPrint; import io.github.thatsmusic99.headsplus.config.headsx.Icon; import io.github.thatsmusic99.headsplus.util.InventoryManager; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; public class Nav extends ItemStack implements Icon { final Page direction; final String title; final Material mat; public static enum Page { MENU('M'), START('<'), BACK('B'), NEXT('N'), BACK_2('['), BACK_3('{'), NEXT_2(']'), NEXT_3('}'), LAST('>'); public final char shortHand; private Page(char shortHand) { this.shortHand = shortHand; } } public Nav(Page direction, String title, Material material) { this.direction = direction; this.title = title; this.mat = material; } public Page getNavigationPage() { return direction; } @Override public String getIconName() { return direction.name().toLowerCase(); } @Override public void onClick(Player p, InventoryManager im, InventoryClickEvent e) { e.setCancelled(true); p.closeInventory(); try { im.showPage(direction); } catch (Exception e1) { new DebugPrint(e1, "Changing page (next)", false, p); } } @Override public Material getDefaultMaterial() { return mat; } @Override public List<String> getDefaultLore() { return new ArrayList<>(); } @Override public String getDefaultDisplayName() { return "&a&l" + title; } @Override public List<String> getLore() { return HeadsPlus.getInstance().getItems().getConfig().getStringList("icons." + getIconName() + ".lore"); } @Override public String getSingleLetter() { return String.valueOf(direction.shortHand); } }
25.855422
115
0.647251
bf9da9fb683358cb996dfa4494a9e045b0c381dc
3,054
package gnat.filter.nei; import gnat.alignment.Alignment; import gnat.filter.Filter; import gnat.representation.Context; import gnat.representation.Gene; import gnat.representation.GeneRepository; import gnat.representation.IdentificationStatus; import gnat.representation.RecognizedEntity; import gnat.representation.TextRepository; import gnat.utils.AlignmentHelper; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Filter for recognized gene names based on the aligment score against candidate gene's synonyms. * This filter removes recognized gene names if none of its candidate genes has a similar synonym. * * <br><br> * <b>Requirements:</b><br> * Needs information on each gene (such as synonysm), this requires a loaded GeneRepository. */ public class AlignmentFilter implements Filter { //private GeneRepository geneRepository; private Alignment alignment; private float threshold = 0; /** * Creates a new filter for a given alignment method, a gene repository to lookup candidate genes, and a minimum score threshold. * */ public AlignmentFilter (Alignment alignment, float threshold) { this.alignment = alignment; this.threshold = threshold; } /** * Filter for recognized gene names based on the aligment score against candidate gene's synonyms. * This filter removes recognized gene names if none of its candidate genes has a similar synonym, * i.e., aligns with a score >= threshold. */ public void filter (Context context, TextRepository textRepository, GeneRepository geneRepository) { Map<String, List<Gene>> closestGeneMap = new HashMap<String, List<Gene>>(); Iterator<RecognizedEntity> unidentifiedGeneNames = context.getUnidentifiedEntities().iterator(); while (unidentifiedGeneNames.hasNext()) { RecognizedEntity recognizedGeneName = unidentifiedGeneNames.next(); IdentificationStatus identificationStatus = context.getIdentificationStatus(recognizedGeneName); List<Gene> candidateGenesWithSimilarSynonyms = closestGeneMap.get(recognizedGeneName.getName()); if(candidateGenesWithSimilarSynonyms==null){ Set<String> candidateIds = identificationStatus.getIdCandidates(); Set<Gene> candidateGenes = new HashSet<Gene>(); for (String id : candidateIds) { Gene gene = geneRepository.getGene(id); if (gene != null) { candidateGenes.add(gene); } } candidateGenesWithSimilarSynonyms = AlignmentHelper.getAlignedGenes(alignment, recognizedGeneName, candidateGenes, threshold); closestGeneMap.put(recognizedGeneName.getName(), candidateGenesWithSimilarSynonyms); } Set<String> closestGeneIds = new HashSet<String>(); for (Gene gene : candidateGenesWithSimilarSynonyms) { closestGeneIds.add(gene.getID()); } identificationStatus.setIdCandidates(closestGeneIds); } } /** * Sets the minimum alignment threshold. * */ public void setThreshold (float i) { this.threshold = i; } }
34.314607
130
0.759332
2ed125b37090b1d1428071166a4260fd3f823884
3,675
package lk.my.sliit.it18106398.foodapp; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import android.widget.Toolbar; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.database.FirebaseListAdapter; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; 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; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Map; import lk.my.sliit.it18106398.foodapp.Add_Promotions; import lk.my.sliit.it18106398.foodapp.ModelPromotions; import lk.my.sliit.it18106398.foodapp.PromotionsAdapter; public class ListPromotions extends AppCompatActivity { Toolbar tb; DatabaseReference dRef; RecyclerView recyclerView; ArrayList<ModelPromotions> PromoList; ArrayList<Add_Promotions> promotions; ArrayList<String> foodName; ArrayList<String> promoKey; //ArrayList<> //FirebaseRecyclerAdapter adapter; PromotionsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_promotions); foodName = new ArrayList<>(); promoKey = new ArrayList<>(); dRef = FirebaseDatabase.getInstance().getReference(); recyclerView = findViewById(R.id.promoRecyclerView); adapter = new PromotionsAdapter(getApplicationContext(),foodName, promoKey); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); dRef.child("PromotionTable").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.hasChildren()) { foodName.clear(); promoKey.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { //Map<String,String> map = dataSnapshot.getValue(Map.class); String food = ds.child("foodName").getValue(String.class); //String food = map.get("foodName"); String key = ds.child("description").getValue(String.class); //String key = map.get("description"); Toast.makeText(ListPromotions.this, "Loaded", Toast.LENGTH_SHORT).show(); foodName.add(food); promoKey.add(key); adapter.notifyDataSetChanged(); //Log.v("E_VALUE","foodName:"+food); //Log.v("E_VALUE","description:"+key); } } else { Toast.makeText(ListPromotions.this, "No data found.", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); /* recyclerView = findViewById(R.id.promoRecyclerView); adapter = new PromotionsAdapter(getApplicationContext(),foodName, promoKey); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this));*/ } }
37.886598
101
0.666395
d3e19e7331e4f0586b28fc5b56a34ad858236c5b
1,878
package uk.org.webcompere.modelassert.json.condition.tree; import uk.org.webcompere.modelassert.json.PathWildCard; import java.util.List; import java.util.regex.Pattern; public interface PathMatcher { /** * Does this path matcher prevent a match, or do any of its successors prevent a match * @param location the location * @param remaining the remaining {@link PathMatcher}s * @return <code>true</code> if there's a match */ boolean matches(Location location, List<PathMatcher> remaining); /** * Factory method - convert an object into its path matcher * @param value the value to convert * @return a path matcher or {@link IllegalArgumentException} if not known */ static PathMatcher of(Object value) { if (value instanceof String) { return new StringPathMatcher((String) value); } if (value instanceof PathWildCard) { return new WildCardPathMatcher((PathWildCard) value); } if (value instanceof Pattern) { return new RegexPathMatcher((Pattern) value); } throw new IllegalArgumentException("Unexpected path part: " + value + ". Expecting String, Pattern or PathWildCard"); } /** * Work out whether the rest of the location meets the rest of the remaining matchers * @param location the location so far * @param remaining the remaining matchers * @return true if matches the remainder */ static boolean matchesTheRest(Location location, List<PathMatcher> remaining) { if (remaining.isEmpty() && location.isEmpty()) { return true; } if (!location.isEmpty() && remaining.isEmpty()) { return false; } return remaining.get(0) .matches(location, remaining.subList(1, remaining.size())); } }
32.947368
90
0.646432
ca6c6bd86ee5351633930d8d23ec06ba44dfd223
790
package kotlin.contracts; import kotlin.Metadata; import kotlin.Unit; import kotlin.jvm.functions.Function1; @Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u0016\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\u001a\"\u0010\u0000\u001a\u00020\u00012\u0017\u0010\u0002\u001a\u0013\u0012\u0004\u0012\u00020\u0004\u0012\u0004\u0012\u00020\u00010\u0003¢\u0006\u0002\b\u0005H‡\b¨\u0006\u0006"}, d2 = {"contract", "", "builder", "Lkotlin/Function1;", "Lkotlin/contracts/ContractBuilder;", "Lkotlin/ExtensionFunctionType;", "kotlin-stdlib"}, k = 2, mv = {1, 1, 16}) /* compiled from: ContractBuilder.kt */ public final class ContractBuilderKt { private static final void contract(Function1<? super ContractBuilder, Unit> function1) { } }
60.769231
498
0.743038
9d945fd6a293f204ed53478f6ac50d6c8b5c43a4
594
package co.team.reservation.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import co.team.reservation.service.ReservationService; import co.team.reservation.service.ReservationVO; @Service public class ReservationImpl implements ReservationService { @Autowired ReservationMapper dao; @Override public List<ReservationVO> getReserv(ReservationVO vo) { return dao.getReserv(vo); } @Override public int insertReserv(ReservationVO vo) { return dao.insertReserv(vo); } }
19.8
62
0.794613
c418d6ee6a329543acbbc9989c2c02a45ac076e5
1,092
package smpl.ordering; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Helper class for getting data out of the 'application.properties' file found on the * class path. */ public class PropertyHelper { public static Properties getPropValues(String propFileName) throws IOException { Properties props = new Properties(); InputStream inputStream = PropertyHelper.class.getClassLoader().getResourceAsStream(propFileName); props.load(inputStream); if (inputStream == null) { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } return props; } public static Properties getProperties() { return s_props; } static { try { s_props = getPropValues("application.properties"); } catch (IOException e) { s_props = new Properties(); } } private static Properties s_props; }
22.285714
111
0.637363
1da2d09482f53788443a3f9efa32e97a456f92c0
7,223
package net.minecraft.entity.monster; import net.minecraft.entity.player.*; import net.minecraft.pathfinding.*; import net.minecraft.util.*; import net.minecraft.block.*; import net.minecraft.item.*; import net.minecraft.init.*; import net.minecraft.potion.*; import net.minecraft.world.*; import net.minecraft.entity.*; import net.minecraft.entity.ai.*; import java.util.*; public class EntitySpider extends EntityMob { public EntitySpider(final World worldIn) { super(worldIn); this.setSize(1.4f, 0.9f); this.tasks.addTask(1, new EntityAISwimming(this)); this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4f)); this.tasks.addTask(4, new AISpiderAttack(this, EntityPlayer.class)); this.tasks.addTask(4, new AISpiderAttack(this, EntityIronGolem.class)); this.tasks.addTask(5, new EntityAIWander(this, 0.8)); this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0f)); this.tasks.addTask(6, new EntityAILookIdle(this)); this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0])); this.targetTasks.addTask(2, new AISpiderTarget<Object>(this, EntityPlayer.class)); this.targetTasks.addTask(3, new AISpiderTarget<Object>(this, EntityIronGolem.class)); } @Override public double getMountedYOffset() { return this.height * 0.5f; } @Override protected PathNavigate getNewNavigator(final World worldIn) { return new PathNavigateClimber(this, worldIn); } @Override protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(16, new Byte((byte)0)); } @Override public void onUpdate() { super.onUpdate(); if (!this.worldObj.isRemote) { this.setBesideClimbableBlock(this.isCollidedHorizontally); } } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(16.0); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896); } @Override protected String getLivingSound() { return "mob.spider.say"; } @Override protected String getHurtSound() { return "mob.spider.say"; } @Override protected String getDeathSound() { return "mob.spider.death"; } @Override protected void playStepSound(final BlockPos pos, final Block blockIn) { this.playSound("mob.spider.step", 0.15f, 1.0f); } @Override protected Item getDropItem() { return Items.string; } @Override protected void dropFewItems(final boolean p_70628_1_, final int p_70628_2_) { super.dropFewItems(p_70628_1_, p_70628_2_); if (p_70628_1_ && (this.rand.nextInt(3) == 0 || this.rand.nextInt(1 + p_70628_2_) > 0)) { this.dropItem(Items.spider_eye, 1); } } @Override public boolean isOnLadder() { return this.isBesideClimbableBlock(); } @Override public void setInWeb() { } @Override public EnumCreatureAttribute getCreatureAttribute() { return EnumCreatureAttribute.ARTHROPOD; } @Override public boolean isPotionApplicable(final PotionEffect potioneffectIn) { return potioneffectIn.getPotionID() != Potion.poison.id && super.isPotionApplicable(potioneffectIn); } public boolean isBesideClimbableBlock() { return (this.dataWatcher.getWatchableObjectByte(16) & 0x1) != 0x0; } public void setBesideClimbableBlock(final boolean p_70839_1_) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); if (p_70839_1_) { b0 |= 0x1; } else { b0 &= 0xFFFFFFFE; } this.dataWatcher.updateObject(16, b0); } @Override public IEntityLivingData onInitialSpawn(final DifficultyInstance difficulty, IEntityLivingData livingdata) { livingdata = super.onInitialSpawn(difficulty, livingdata); if (this.worldObj.rand.nextInt(100) == 0) { final EntitySkeleton entityskeleton = new EntitySkeleton(this.worldObj); entityskeleton.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0f); entityskeleton.onInitialSpawn(difficulty, null); this.worldObj.spawnEntityInWorld(entityskeleton); entityskeleton.mountEntity(this); } if (livingdata == null) { livingdata = new GroupData(); if (this.worldObj.getDifficulty() == EnumDifficulty.HARD && this.worldObj.rand.nextFloat() < 0.1f * difficulty.getClampedAdditionalDifficulty()) { ((GroupData)livingdata).func_111104_a(this.worldObj.rand); } } if (livingdata instanceof GroupData) { final int i = ((GroupData)livingdata).potionEffectId; if (i > 0 && Potion.potionTypes[i] != null) { this.addPotionEffect(new PotionEffect(i, Integer.MAX_VALUE)); } } return livingdata; } @Override public float getEyeHeight() { return 0.65f; } static class AISpiderAttack extends EntityAIAttackOnCollide { public AISpiderAttack(final EntitySpider p_i45819_1_, final Class<? extends Entity> targetClass) { super(p_i45819_1_, targetClass, 1.0, true); } @Override public boolean continueExecuting() { final float f = this.attacker.getBrightness(1.0f); if (f >= 0.5f && this.attacker.getRNG().nextInt(100) == 0) { this.attacker.setAttackTarget(null); return false; } return super.continueExecuting(); } @Override protected double func_179512_a(final EntityLivingBase attackTarget) { return 4.0f + attackTarget.width; } } static class AISpiderTarget<T extends EntityLivingBase> extends EntityAINearestAttackableTarget { public AISpiderTarget(final EntitySpider p_i45818_1_, final Class<T> classTarget) { super(p_i45818_1_, classTarget, true); } @Override public boolean shouldExecute() { final float f = this.taskOwner.getBrightness(1.0f); return f < 0.5f && super.shouldExecute(); } } public static class GroupData implements IEntityLivingData { public int potionEffectId; public void func_111104_a(final Random rand) { final int i = rand.nextInt(5); if (i <= 1) { this.potionEffectId = Potion.moveSpeed.id; } else if (i <= 2) { this.potionEffectId = Potion.damageBoost.id; } else if (i <= 3) { this.potionEffectId = Potion.regeneration.id; } else if (i <= 4) { this.potionEffectId = Potion.invisibility.id; } } } }
33.439815
158
0.622594
1e7e23cc709f3f96764bbd9fdf05b922f19869d5
1,435
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.recognizers.datatypes.timex.expression; import java.util.ArrayList; import java.util.List; public class Resolution { private List<Entry> values; public List<Entry> getValues() { return this.values; } public Resolution() { this.values = new ArrayList<Entry>(); } public static class Entry { private String timex; private String type; private String value; private String start; private String end; public String getTimex() { return timex; } public void setTimex(String withTimex) { this.timex = withTimex; } public String getType() { return type; } public void setType(String withType) { this.type = withType; } public String getValue() { return value; } public void setValue(String withValue) { this.value = withValue; } public String getStart() { return start; } public void setStart(String withStart) { this.start = withStart; } public String getEnd() { return end; } public void setEnd(String withEnd) { this.end = withEnd; } } }
19.930556
61
0.554007
2ee59721c8e7a9c9655241bb97a1277c2152863c
5,363
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.testutil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; /** * Some static utility functions for testing. */ public class TestUtils { public static final ThreadPoolExecutor POOL = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); public static final UUID ZERO_UUID = UUID.fromString("00000000-0000-0000-0000-000000000000"); /** * Wait until the {@link System#currentTimeMillis} / 1000 advances. * * This method takes 0-1000ms to run, 500ms on average. */ public static void advanceCurrentTimeSeconds() throws InterruptedException { long currentTimeSeconds = System.currentTimeMillis() / 1000; do { Thread.sleep(50); } while (currentTimeSeconds == System.currentTimeMillis() / 1000); } public static ThreadPoolExecutor getPool() { return POOL; } public static String tmpDir() { return tmpDirFile().getAbsolutePath(); } static String getUserValue(String key) { String value = System.getProperty(key); if (value == null) { value = System.getenv(key); } return value; } public static File tmpDirFile() { File tmpDir; // Flag value specified in environment? String tmpDirStr = getUserValue("TEST_TMPDIR"); if (tmpDirStr != null && tmpDirStr.length() > 0) { tmpDir = new File(tmpDirStr); } else { // Fallback default $TEMP/$USER/tmp/$TESTNAME String baseTmpDir = System.getProperty("java.io.tmpdir"); tmpDir = new File(baseTmpDir).getAbsoluteFile(); // .. Add username String username = System.getProperty("user.name"); username = username.replace('/', '_'); username = username.replace('\\', '_'); username = username.replace('\000', '_'); tmpDir = new File(tmpDir, username); tmpDir = new File(tmpDir, "tmp"); } // Ensure tmpDir exists if (!tmpDir.isDirectory()) { tmpDir.mkdirs(); } return tmpDir; } public static File makeTempDir() throws IOException { File dir = File.createTempFile(TestUtils.class.getName(), ".temp", tmpDirFile()); if (!dir.delete()) { throw new IOException("Cannot remove a temporary file " + dir); } if (!dir.mkdir()) { throw new IOException("Cannot create a temporary directory " + dir); } return dir; } public static int getRandomSeed() { // Default value if not running under framework int randomSeed = 301; // Value specified in environment by framework? String value = getUserValue("TEST_RANDOM_SEED"); if ((value != null) && (value.length() > 0)) { try { randomSeed = Integer.parseInt(value); } catch (NumberFormatException e) { // throw new AssertionError("TEST_RANDOM_SEED must be an integer"); throw new RuntimeException("TEST_RANDOM_SEED must be an integer"); } } return randomSeed; } public static byte[] serializeObject(Object obj) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (ObjectOutputStream objectStream = new ObjectOutputStream(outputStream)) { objectStream.writeObject(obj); } return outputStream.toByteArray(); } public static Object deserializeObject(byte[] buf) throws IOException, ClassNotFoundException { try (ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(buf))) { return inStream.readObject(); } } /** * Timeouts for asserting that an arbitrary event occurs eventually. * * <p>In general, it's not appropriate to use a small constant timeout for an arbitrary * computation since there is no guarantee that a snippet of code will execute within a given * amount of time - you are at the mercy of the jvm, your machine, and your OS. In theory we * could try to take all of these factors into account but instead we took the simpler and * obviously correct approach of not having timeouts. * * <p>If a test that uses these timeout values is failing due to a "timeout" at the * 'blaze test' level, it could be because of a legitimate deadlock that would have been caught * if the timeout values below were small. So you can rule out such a deadlock by changing these * values to small numbers (also note that the --test_timeout blaze flag may be useful). */ public static final long WAIT_TIMEOUT_MILLISECONDS = Long.MAX_VALUE; public static final long WAIT_TIMEOUT_SECONDS = WAIT_TIMEOUT_MILLISECONDS / 1000; }
35.052288
98
0.70166
e6fc7832accc20e43d7d57dba44a9df095636a0b
2,574
/* * Copyright 2020 S. Webber * * 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.projog.core.udp.interpreter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.projog.core.KnowledgeBase; import org.projog.core.udp.ClauseModel; public class Clauses { private final int numClauses; private final List<ClauseAction> clauses; private final int[] immutableColumns; public static Clauses createFromModels(KnowledgeBase kb, List<ClauseModel> models) { List<ClauseAction> actions = new ArrayList<>(); for (ClauseModel model : models) { ClauseAction action = ClauseActionFactory.createClauseAction(kb, model); actions.add(action); } return new Clauses(kb, actions); } public Clauses(KnowledgeBase kb, List<ClauseAction> actions) { if (actions.isEmpty()) { this.numClauses = 0; this.clauses = Collections.emptyList(); this.immutableColumns = new int[0]; return; } this.numClauses = actions.size(); this.clauses = new ArrayList<>(numClauses); int numArgs = actions.get(0).getModel().getConsequent().getNumberOfArguments(); boolean[] muttableColumns = new boolean[numArgs]; int muttableColumnCtr = 0; for (ClauseAction action : actions) { this.clauses.add(action); for (int i = 0; i < numArgs; i++) { if (!muttableColumns[i] && !action.getModel().getConsequent().getArgument(i).isImmutable()) { muttableColumns[i] = true; muttableColumnCtr++; } } } this.immutableColumns = new int[numArgs - muttableColumnCtr]; for (int i = 0, ctr = 0; ctr < immutableColumns.length; i++) { if (!muttableColumns[i]) { immutableColumns[ctr++] = i; } } } public int[] getImmutableColumns() { return immutableColumns; } public ClauseAction[] getClauseActions() { return clauses.toArray(new ClauseAction[clauses.size()]); } }
33
105
0.658897
1446f60597465fd504add22cd978703bdcea5f0e
21,430
/* * 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.felix.connect.felix.framework.capabilityset; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import org.apache.felix.connect.felix.framework.util.StringComparator; import org.apache.felix.connect.felix.framework.wiring.BundleCapabilityImpl; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; import org.osgi.framework.wiring.BundleCapability; import org.osgi.resource.Capability; public class CapabilitySet { private final SortedMap<String, Map<Object, Set<BundleCapability>>> m_indices; // Should also be concurrent! private final Set<Capability> m_capSet = Collections.newSetFromMap(new ConcurrentHashMap<Capability, Boolean>()); public CapabilitySet(final List<String> indexProps, final boolean caseSensitive) { m_indices = (caseSensitive) ? new ConcurrentSkipListMap<String, Map<Object, Set<BundleCapability>>>() : new ConcurrentSkipListMap<String, Map<Object, Set<BundleCapability>>>( StringComparator.COMPARATOR); for (int i = 0; (indexProps != null) && (i < indexProps.size()); i++) { m_indices.put( indexProps.get(i), new ConcurrentHashMap<Object, Set<BundleCapability>>()); } } public void addCapability(final BundleCapability cap) { m_capSet.add(cap); // Index capability. for (Entry<String, Map<Object, Set<BundleCapability>>> entry : m_indices.entrySet()) { Object value = cap.getAttributes().get(entry.getKey()); if (value != null) { if (value.getClass().isArray()) { value = convertArrayToList(value); } ConcurrentMap<Object, Set<BundleCapability>> index = (ConcurrentMap<Object, Set<BundleCapability>>) entry.getValue(); if (value instanceof Collection) { Collection c = (Collection) value; for (Object o : c) { indexCapability(index, cap, o); } } else { indexCapability(index, cap, value); } } } } private void indexCapability( ConcurrentMap<Object, Set<BundleCapability>> index, BundleCapability cap, Object capValue) { Set<BundleCapability> caps = Collections.newSetFromMap(new ConcurrentHashMap<BundleCapability, Boolean>()); Set<BundleCapability> prevval = index.putIfAbsent(capValue, caps); if (prevval != null) caps = prevval; caps.add(cap); } public void removeCapability(final BundleCapability cap) { if (m_capSet.remove(cap)) { for (Entry<String, Map<Object, Set<BundleCapability>>> entry : m_indices.entrySet()) { Object value = cap.getAttributes().get(entry.getKey()); if (value != null) { if (value.getClass().isArray()) { value = convertArrayToList(value); } Map<Object, Set<BundleCapability>> index = entry.getValue(); if (value instanceof Collection) { Collection c = (Collection) value; for (Object o : c) { deindexCapability(index, cap, o); } } else { deindexCapability(index, cap, value); } } } } } private void deindexCapability( Map<Object, Set<BundleCapability>> index, BundleCapability cap, Object value) { Set<BundleCapability> caps = index.get(value); if (caps != null) { caps.remove(cap); if (caps.isEmpty()) { index.remove(value); } } } public Set<Capability> match(final SimpleFilter sf, final boolean obeyMandatory) { final Set<Capability> matches = match(m_capSet, sf); return (obeyMandatory) ? matchMandatory(matches, sf) : matches; } private Set<Capability> match(Set<Capability> caps, final SimpleFilter sf) { Set<Capability> matches = Collections.newSetFromMap(new ConcurrentHashMap<Capability, Boolean>()); if (sf.getOperation() == SimpleFilter.MATCH_ALL) { matches.addAll(caps); } else if (sf.getOperation() == SimpleFilter.AND) { // Evaluate each subfilter against the remaining capabilities. // For AND we calculate the intersection of each subfilter. // We can short-circuit the AND operation if there are no // remaining capabilities. final List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; (caps.size() > 0) && (i < sfs.size()); i++) { matches = match(caps, sfs.get(i)); caps = matches; } } else if (sf.getOperation() == SimpleFilter.OR) { // Evaluate each subfilter against the remaining capabilities. // For OR we calculate the union of each subfilter. List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; i < sfs.size(); i++) { matches.addAll(match(caps, sfs.get(i))); } } else if (sf.getOperation() == SimpleFilter.NOT) { // Evaluate each subfilter against the remaining capabilities. // For OR we calculate the union of each subfilter. matches.addAll(caps); List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; i < sfs.size(); i++) { matches.removeAll(match(caps, sfs.get(i))); } } else { Map<Object, Set<BundleCapability>> index = m_indices.get(sf.getName()); if ((sf.getOperation() == SimpleFilter.EQ) && (index != null)) { Set<BundleCapability> existingCaps = index.get(sf.getValue()); if (existingCaps != null) { matches.addAll(existingCaps); if (caps != m_capSet) { matches.retainAll(caps); } } } else { for (Iterator<Capability> it = caps.iterator(); it.hasNext(); ) { Capability cap = it.next(); Object lhs = cap.getAttributes().get(sf.getName()); if (lhs != null) { if (compare(lhs, sf.getValue(), sf.getOperation())) { matches.add(cap); } } } } } return matches; } public static boolean matches(Capability cap, SimpleFilter sf) { return matchesInternal(cap, sf) && matchMandatory(cap, sf); } private static boolean matchesInternal(Capability cap, SimpleFilter sf) { boolean matched = true; if (sf.getOperation() == SimpleFilter.MATCH_ALL) { matched = true; } else if (sf.getOperation() == SimpleFilter.AND) { // Evaluate each subfilter against the remaining capabilities. // For AND we calculate the intersection of each subfilter. // We can short-circuit the AND operation if there are no // remaining capabilities. List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; matched && (i < sfs.size()); i++) { matched = matchesInternal(cap, sfs.get(i)); } } else if (sf.getOperation() == SimpleFilter.OR) { // Evaluate each subfilter against the remaining capabilities. // For OR we calculate the union of each subfilter. matched = false; List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; !matched && (i < sfs.size()); i++) { matched = matchesInternal(cap, sfs.get(i)); } } else if (sf.getOperation() == SimpleFilter.NOT) { // Evaluate each subfilter against the remaining capabilities. // For OR we calculate the union of each subfilter. List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; i < sfs.size(); i++) { matched = !(matchesInternal(cap, sfs.get(i))); } } else { matched = false; Object lhs = cap.getAttributes().get(sf.getName()); if (lhs != null) { matched = compare(lhs, sf.getValue(), sf.getOperation()); } } return matched; } private static Set<Capability> matchMandatory( Set<Capability> caps, SimpleFilter sf) { for (Iterator<Capability> it = caps.iterator(); it.hasNext(); ) { Capability cap = it.next(); if (!matchMandatory(cap, sf)) { it.remove(); } } return caps; } private static boolean matchMandatory(Capability cap, SimpleFilter sf) { Map<String, Object> attrs = cap.getAttributes(); for (Entry<String, Object> entry : attrs.entrySet()) { if (((BundleCapabilityImpl) cap).isAttributeMandatory(entry.getKey()) && !matchMandatoryAttribute(entry.getKey(), sf)) { return false; } } return true; } private static boolean matchMandatoryAttribute(String attrName, SimpleFilter sf) { if ((sf.getName() != null) && sf.getName().equals(attrName)) { return true; } else if (sf.getOperation() == SimpleFilter.AND) { List list = (List) sf.getValue(); for (int i = 0; i < list.size(); i++) { SimpleFilter sf2 = (SimpleFilter) list.get(i); if ((sf2.getName() != null) && sf2.getName().equals(attrName)) { return true; } } } return false; } private static final Class<?>[] STRING_CLASS = new Class[] { String.class }; private static final String VALUE_OF_METHOD_NAME = "valueOf"; private static boolean compare(Object lhs, Object rhsUnknown, int op) { if (lhs == null) { return false; } // If this is a PRESENT operation, then just return true immediately // since we wouldn't be here if the attribute wasn't present. if (op == SimpleFilter.PRESENT) { return true; } //Need a special case here when lhs is a Version and rhs is a VersionRange //Version is comparable so we need to check this first if(lhs instanceof Version && op == SimpleFilter.EQ) { Object rhs = null; try { rhs = coerceType(lhs, (String) rhsUnknown); } catch (Exception ex) { //Do nothing will check later if rhs is null } if(rhs != null && rhs instanceof VersionRange) { return ((VersionRange)rhs).includes((Version)lhs); } } // If the type is comparable, then we can just return the // result immediately. if (lhs instanceof Comparable) { // Spec says SUBSTRING is false for all types other than string. if ((op == SimpleFilter.SUBSTRING) && !(lhs instanceof String)) { return false; } Object rhs; if (op == SimpleFilter.SUBSTRING) { rhs = rhsUnknown; } else { try { rhs = coerceType(lhs, (String) rhsUnknown); } catch (Exception ex) { return false; } } switch (op) { case SimpleFilter.EQ : try { return (((Comparable) lhs).compareTo(rhs) == 0); } catch (Exception ex) { return false; } case SimpleFilter.GTE : try { return (((Comparable) lhs).compareTo(rhs) >= 0); } catch (Exception ex) { return false; } case SimpleFilter.LTE : try { return (((Comparable) lhs).compareTo(rhs) <= 0); } catch (Exception ex) { return false; } case SimpleFilter.APPROX : return compareApproximate(lhs, rhs); case SimpleFilter.SUBSTRING : return SimpleFilter.compareSubstring((List<String>) rhs, (String) lhs); default: throw new RuntimeException( "Unknown comparison operator: " + op); } } // Booleans do not implement comparable, so special case them. else if (lhs instanceof Boolean) { Object rhs; try { rhs = coerceType(lhs, (String) rhsUnknown); } catch (Exception ex) { return false; } switch (op) { case SimpleFilter.EQ : case SimpleFilter.GTE : case SimpleFilter.LTE : case SimpleFilter.APPROX : return (lhs.equals(rhs)); default: throw new RuntimeException( "Unknown comparison operator: " + op); } } // If the LHS is not a comparable or boolean, check if it is an // array. If so, convert it to a list so we can treat it as a // collection. if (lhs.getClass().isArray()) { lhs = convertArrayToList(lhs); } // If LHS is a collection, then call compare() on each element // of the collection until a match is found. if (lhs instanceof Collection) { for (Iterator iter = ((Collection) lhs).iterator(); iter.hasNext(); ) { if (compare(iter.next(), rhsUnknown, op)) { return true; } } return false; } // Spec says SUBSTRING is false for all types other than string. if ((op == SimpleFilter.SUBSTRING) && !(lhs instanceof String)) { return false; } // Since we cannot identify the LHS type, then we can only perform // equality comparison. try { return lhs.equals(coerceType(lhs, (String) rhsUnknown)); } catch (Exception ex) { return false; } } private static boolean compareApproximate(Object lhs, Object rhs) { if (rhs instanceof String) { return removeWhitespace((String) lhs) .equalsIgnoreCase(removeWhitespace((String) rhs)); } else if (rhs instanceof Character) { return Character.toLowerCase(((Character) lhs)) == Character.toLowerCase(((Character) rhs)); } return lhs.equals(rhs); } private static String removeWhitespace(String s) { StringBuilder sb = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { if (!Character.isWhitespace(s.charAt(i))) { sb.append(s.charAt(i)); } } return sb.toString(); } private static Object coerceType(Object lhs, String rhsString) throws Exception { // If the LHS expects a string, then we can just return // the RHS since it is a string. if (lhs.getClass() == rhsString.getClass()) { return rhsString; } // Try to convert the RHS type to the LHS type by using // the string constructor of the LHS class, if it has one. Object rhs = null; try { // The Character class is a special case, since its constructor // does not take a string, so handle it separately. if (lhs instanceof Character) { rhs = new Character(rhsString.charAt(0)); } else if(lhs instanceof Version && rhsString.indexOf(',') >= 0) { rhs = new VersionRange(rhsString); } else { // Spec says we should trim number types. if ((lhs instanceof Number) || (lhs instanceof Boolean)) { rhsString = rhsString.trim(); } try { // Try to find a suitable static valueOf method Method valueOfMethod = lhs.getClass().getDeclaredMethod( VALUE_OF_METHOD_NAME, STRING_CLASS); if (valueOfMethod.getReturnType().isAssignableFrom(lhs.getClass()) && ((valueOfMethod.getModifiers() & Modifier.STATIC) > 0)) { valueOfMethod.setAccessible(true); rhs = valueOfMethod.invoke(null, new Object[] { rhsString }); } } catch (Exception ex) { // Static valueOf fails, try the next conversion mechanism } if (rhs == null) { Constructor ctor = lhs.getClass().getConstructor(STRING_CLASS); ctor.setAccessible(true); rhs = ctor.newInstance(new Object[] { rhsString }); } } } catch (Exception ex) { throw new Exception( "Could not instantiate class " + lhs.getClass().getName() + " from string constructor with argument '" + rhsString + "' because " + ex); } return rhs; } /** * This is an ugly utility method to convert an array of primitives * to an array of primitive wrapper objects. This method simplifies * processing LDAP filters since the special case of primitive arrays * can be ignored. * @param array An array of primitive types. * @return An corresponding array using pritive wrapper objects. **/ private static List convertArrayToList(Object array) { int len = Array.getLength(array); List list = new ArrayList(len); for (int i = 0; i < len; i++) { list.add(Array.get(array, i)); } return list; } }
33.801262
117
0.50532
f35eb53460d7d956b753fd76d94345312a24b9d4
6,224
package com.arun.admin; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; @WebServlet("/validate") public class validate extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(name="jdbc/project") private DataSource datasource; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String thecommand = request.getParameter("command"); if(thecommand==null) thecommand="LIST"; switch(thecommand) { case "UPDATE": resetpass(request,response); break; case "ADD": validatepassword(request,response); break; case "LOGIN": request.getRequestDispatcher("admin").forward(request, response); break; case "QUESTION": checkanswer(request,response); break; case "PASSWORD": newpassword(request,response); break; default: request.getRequestDispatcher("login.jsp").include(request, response); } } catch (Exception e) { throw new ServletException(e); } } private void newpassword(HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out=response.getWriter(); String password=request.getParameter("password"); String repassword=request.getParameter("repassword"); if(password.length()>=8) { if(password.equals(repassword)) { request.getRequestDispatcher("admin").forward(request, response); } else { out.print("please Enter Both Password Will Be Same"); request.getRequestDispatcher("reenterpassword.jsp").include(request, response); } } else { out.print("<b> Please Enter 8 charcter Password </b>"); request.getRequestDispatcher("reenterpassword.jsp").include(request, response); } } private void checkanswer(HttpServletRequest request, HttpServletResponse response) throws Exception{ PrintWriter out=response.getWriter(); Connection con=null; PreparedStatement ps=null; String username=request.getParameter("username"); String answer=(request.getParameter("answer")).toLowerCase(); try { con=datasource.getConnection(); String sql="Select Answer from admin where Username=?"; ps=con.prepareStatement(sql); ps.setString(1, username); ResultSet rs=ps.executeQuery(); if(rs.next()) { String realanswer=rs.getString("Answer"); if(realanswer.equals(answer)) { request.setAttribute("username", username); request.getRequestDispatcher("reenterpassword.jsp").forward(request, response);} else { out.print("<b> Answer Not Match"); request.getRequestDispatcher("resatpassword.jsp").include(request, response); } } rs.close(); } catch(Exception e) { out.print(e); } finally { ps.close(); con.close(); } } private void validatepassword(HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out=response.getWriter(); Connection con=null; PreparedStatement ps=null; String username=(request.getParameter("username")).toLowerCase(); String password=request.getParameter("password"); String repassword=request.getParameter("repassword"); try { con=datasource.getConnection(); String sql="Select Password from admin where Username=?"; ps=con.prepareStatement(sql); ps.setString(1, username); ResultSet rs=ps.executeQuery(); if(rs.next() == false) { if(password.length()>=8) { if(password.equals(repassword)) { request.getRequestDispatcher("admin").forward(request, response); } else { out.print("<b> Please Enter Both Filde Same Password </b>"); request.getRequestDispatcher("NewAdmin.jsp").include(request, response); } } else { out.print("<b> Please Enter or 8 and more thane 8 charcter Password </b>"); request.getRequestDispatcher("NewAdmin.jsp").include(request, response); } rs.close(); } else { out.print("<b> User Name Alrade Exsiste </b>"); request.getRequestDispatcher("NewAdmin.jsp").include(request, response); } } catch(Exception e) { out.print(e); } finally { con.close(); ps.close(); } } private void resetpass(HttpServletRequest request, HttpServletResponse response) throws Exception{ PrintWriter out=response.getWriter(); Connection con=null; PreparedStatement ps=null; String username=(request.getParameter("username")).toLowerCase(); try { con=datasource.getConnection(); String sql="SELECT Question from admin where Username=?"; ps=con.prepareStatement(sql); ps.setString(1, username); ResultSet rs=ps.executeQuery(); if(rs.next()) { int que =rs.getInt("Question"); String question=null; switch(que) { case 1: question="Enter Your Home Name"; break; case 2: question="Enter Your First Phone Number"; break; case 3: question="Enter Your Best Teacher Name"; break; case 4: question="Enter Your Favorite Song Name"; break; } request.setAttribute("Question", question); request.setAttribute("username", username); request.getRequestDispatcher("resatpassword.jsp").forward(request, response); } else { out.print("<b> User Name Not Exsiste </b>"); request.getRequestDispatcher("forgetpassword.jsp").include(request, response); } rs.close(); } catch(Exception e) { out.print(e); } finally { ps.close(); con.close(); } } }
23.486792
120
0.654081
77937eb8a096e92f57bd5a1a3dc4b6a2e9272e97
1,253
package db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; public class MyWeatherDBHelper extends SQLiteOpenHelper { private static final String CREATE_T_PROVINCE = "create table t_province (" + "id integer primary key autoincrement," + "name text not NULL," + "code text not NULL)"; private static final String CREATE_T_CITY = "create table t_city (" + "id integer primary key autoincrement," + "name text not NULL," + "code text not NULL," + "province_code text not NULL)"; private static final String CREATE_T_COUNTY = "create table t_county (" + "id integer primary key autoincrement," + "name text not NULL," + "code text not NULL," + "city_code text not NULL)"; public MyWeatherDBHelper(Context context,String strName,CursorFactory factory,int nVersion) { super(context,strName,factory,nVersion); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_T_PROVINCE); db.execSQL(CREATE_T_CITY); db.execSQL(CREATE_T_COUNTY); } @Override public void onUpgrade(SQLiteDatabase db,int nOldVersion,int nNewVersion) { } }
27.844444
92
0.741421
ac70376150b4bd0d50c158027cc23c0ee306f823
549
package com.ilsid.poc.uidiscovery.microservice_a.main; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; /** * * @author illia.sydorovych * */ @SpringBootApplication public class MicroserviceA extends SpringBootServletInitializer { public static void main(String[] args) { new MicroserviceA().configure(new SpringApplicationBuilder(MicroserviceA.class)).run(args); } }
27.45
93
0.817851
2ea3ffb40dd9dcc1705b669bbeef68ad099d24cb
6,411
package com.hitomi.tilibrary.transfer; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.support.v7.app.AlertDialog; import android.view.KeyEvent; import com.hitomi.tilibrary.loader.ImageLoader; import com.hitomi.tilibrary.loader.NoneImageLoader; import com.hitomi.tilibrary.style.index.CircleIndexIndicator; import com.hitomi.tilibrary.style.progress.ProgressBarIndicator; /** * Main workflow: <br/> * 1、点击缩略图展示缩略图到 transferee 过渡动画 <br/> * 2、显示下载高清图片进度 <br/> * 3、加载完成显示高清图片 <br/> * 4、高清图支持手势缩放 <br/> * 5、关闭 transferee 展示 transferee 到原缩略图的过渡动画 <br/> * Created by hitomi on 2017/1/19. * <p> * email: 196425254@qq.com */ public class Transferee implements DialogInterface.OnShowListener, DialogInterface.OnKeyListener, TransferLayout.OnLayoutResetListener { static volatile Transferee defaultInstance; private Context context; private Dialog transDialog; private TransferLayout transLayout; private TransferConfig transConfig; private OnTransfereeStateChangeListener transListener; // 因为Dialog的关闭有动画延迟,固不能使用 dialog.isShowing, 去判断 transferee 的显示逻辑 private boolean shown; /** * 构造方法私有化,通过{@link #getDefault(Context)} 创建 transferee * * @param context 上下文环境 */ private Transferee(Context context) { this.context = context; creatLayout(); createDialog(); } /** * @param context * @return {@link Transferee} */ public static Transferee getDefault(Context context) { if (defaultInstance == null) { synchronized (Transferee.class) { if (defaultInstance == null) { defaultInstance = new Transferee(context); } } } return defaultInstance; } private void creatLayout() { transLayout = new TransferLayout(context); transLayout.setOnLayoutResetListener(this); } private void createDialog() { transDialog = new AlertDialog.Builder(context, getDialogStyle()) .setView(transLayout) .create(); transDialog.setOnShowListener(this); transDialog.setOnKeyListener(this); } /** * 兼容4.4以下的全屏 Dialog 样式 * * @return The style of the dialog */ private int getDialogStyle() { int dialogStyle; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { dialogStyle = android.R.style.Theme_Translucent_NoTitleBar_Fullscreen; } else { dialogStyle = android.R.style.Theme_Translucent_NoTitleBar; } return dialogStyle; } /** * 检查参数,如果必须参数缺少,就使用缺省参数或者抛出异常 */ private void checkConfig() { if (transConfig.isSourceEmpty()) throw new IllegalArgumentException("the parameter sourceImageList can't be empty"); transConfig.setNowThumbnailIndex(transConfig.getNowThumbnailIndex() < 0 ? 0 : transConfig.getNowThumbnailIndex()); transConfig.setOffscreenPageLimit(transConfig.getOffscreenPageLimit() <= 0 ? 1 : transConfig.getOffscreenPageLimit()); transConfig.setDuration(transConfig.getDuration() <= 0 ? 300 : transConfig.getDuration()); transConfig.setProgressIndicator(transConfig.getProgressIndicator() == null ? new ProgressBarIndicator() : transConfig.getProgressIndicator()); transConfig.setIndexIndicator(transConfig.getIndexIndicator() == null ? new CircleIndexIndicator() : transConfig.getIndexIndicator()); transConfig.setImageLoader(transConfig.getImageLoader() == null ? new NoneImageLoader() : transConfig.getImageLoader()); } /** * 配置 transferee 参数对象 * * @param config 参数对象 * @return transferee */ public Transferee apply(TransferConfig config) { if (!shown) { transConfig = config; checkConfig(); transLayout.apply(config); } return defaultInstance; } /** * transferee 是否显示 * * @return true :显示, false :关闭 */ public boolean isShown() { return shown; } /** * 显示 transferee */ public void show() { if (shown) return; transDialog.show(); if (transListener != null) transListener.onShow(); shown = true; } /** * 显示 transferee, 并设置 OnTransfereeChangeListener * * @param listener {@link OnTransfereeStateChangeListener} */ public void show(OnTransfereeStateChangeListener listener) { if (shown) return; transDialog.show(); transListener = listener; transListener.onShow(); shown = true; } /** * 关闭 transferee */ public void dismiss() { if (!shown) return; transLayout.dismiss(transConfig.getNowThumbnailIndex()); shown = false; } /** * 销毁 transferee 组件 */ public void destroy() { defaultInstance = null; } /** * 清除 transferee 缓存 */ public static void clear(ImageLoader imageLoader) { imageLoader.clearCache(); } @Override public void onShow(DialogInterface dialog) { transLayout.show(); } @Override public void onReset() { transDialog.dismiss(); if (transListener != null) transListener.onDismiss(); shown = false; } @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP && !event.isCanceled()) { dismiss(); } return true; } /** * 设置 Transferee 显示和关闭的监听器 * * @param listener {@link OnTransfereeStateChangeListener} */ public void setOnTransfereeStateChangeListener(OnTransfereeStateChangeListener listener) { transListener = listener; } /** * Transferee 显示的时候调用 {@link OnTransfereeStateChangeListener#onShow()} * <p> * Transferee 关闭的时候调用 {@link OnTransfereeStateChangeListener#onDismiss()} */ public interface OnTransfereeStateChangeListener { void onShow(); void onDismiss(); } }
26.7125
95
0.623304
6e73c62cb77f7117bea728a7a3a9cdf29d3b18bf
2,745
package com.burakgomec.wordreminder.Adapters; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.burakgomec.wordreminder.Model.DatabaseController; import com.burakgomec.wordreminder.Model.Database; import com.burakgomec.wordreminder.R; import com.burakgomec.wordreminder.Model.TranslatedWord; import com.burakgomec.wordreminder.databinding.FragmentSavedBinding; import java.util.ArrayList; public class WordsRecyclerAdapter extends RecyclerView.Adapter<WordsRecyclerAdapter.ViewHolder> { Context context; ArrayList<TranslatedWord> translatedWordArrayList; Database database; FragmentSavedBinding binding; public WordsRecyclerAdapter(Context context, Database database, FragmentSavedBinding binding){ this.context = context; this.database = database; this.translatedWordArrayList = DatabaseController.getInstance().getTranslatedWordArrayList(); this.binding = binding; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.recycler_row_words,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.word1.setText(translatedWordArrayList.get(position).getFirstWord()); holder.word2.setText(translatedWordArrayList.get(position).getSecondWord()); holder.imageViewUnStar.setOnClickListener(v -> { database.deleteWordWithId(translatedWordArrayList.get(position)); notifyItemRemoved(position); notifyItemRangeChanged(position, getItemCount() - position); if(translatedWordArrayList.size() == 0){ binding.recyclerViewSaved.setVisibility(View.INVISIBLE); binding.textViewNullList.setVisibility(View.VISIBLE); } }); } @Override public int getItemCount() { return translatedWordArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView word1,word2; ImageView imageViewUnStar; public ViewHolder(@NonNull View itemView) { super(itemView); word1 = itemView.findViewById(R.id.textViewSavedWord1); word2 = itemView.findViewById(R.id.textViewSavedWord2); imageViewUnStar= itemView.findViewById(R.id.imageViewUnStar); } } }
34.746835
101
0.732605
b50e7254681f584db50f98f320cee14bbb41d244
3,329
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. /* * Copyright 2000-2009 JetBrains s.r.o. * * 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.microsoft.alm.plugin.idea.tfvc.core.revision; import com.intellij.openapi.project.Project; import com.microsoft.alm.plugin.context.ServerContext; import com.microsoft.alm.plugin.external.commands.Command; import com.microsoft.alm.plugin.external.commands.DownloadCommand; import com.microsoft.alm.plugin.idea.tfvc.core.TFSVcs; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class TFSContentStoreFactory { private static final Logger logger = LoggerFactory.getLogger(TFSContentStoreFactory.class); public static TFSContentStore create(final String localPath, final int revision) throws IOException { return new TFSTmpFileStore(localPath, revision); } @Nullable public static TFSContentStore find(final String localPath, final int revision) throws IOException { return TFSTmpFileStore.find(localPath, revision); } /** * Find the store for the given file path and if it doesn't already exist create it and download the file * * @param localPath: local path of the file which is used as the key in the store along with the revision number * @param revision: revision number of the file * @param actualPath: file path acknowledged by the server (could differ local path in case of renames) * @return * @throws IOException */ public static TFSContentStore findOrCreate(final String localPath, final int revision, final String actualPath, final Project project) throws IOException { TFSContentStore store = TFSContentStoreFactory.find(localPath, revision); if (store == null) { try { store = TFSContentStoreFactory.create(localPath, revision); final ServerContext serverContext = TFSVcs.getInstance(project).getServerContext(false); // By setting the IgnoreFileNotFound flag to true in DownloadCommand, we will get back an empty file if the file was deleted on the server or // for some other reason doesn't exist. final Command<String> command = new DownloadCommand(serverContext, actualPath, revision, store.getTmpFile().getPath(), true); command.runSynchronously(); } catch (final Throwable t) { // Can't let exceptions bubble out here to the caller. This method is called by the VCS provider code in various places. logger.warn("Unable to download content for a TFVC file.", t); } } return store; } }
45.60274
159
0.71553
de5f5fbe7acd59e7e47c0ab9065635ac4e33e4ac
1,533
package cn.nekocode.tachie.sample; import android.content.Context; import android.graphics.Bitmap; import android.support.v8.renderscript.Allocation; import android.support.v8.renderscript.RenderScript; import cn.nekocode.rs.ScriptC_Tachie; /** * Created by nekocode on 16/8/3. */ public final class TachieRenderScriptUtil { private TachieRenderScriptUtil(){ } public static Bitmap trans(Bitmap source, Bitmap target, float alpha, Context context) { // Create renderscript RenderScript rs = RenderScript.create(context); // Create allocation from Bitmap Allocation allocationSource = Allocation.createFromBitmap(rs, source); Allocation allocationTarget = Allocation.createFromBitmap(rs, target); Allocation allocationOut = Allocation.createTyped(rs, allocationSource.getType()); // Create script ScriptC_Tachie script = new ScriptC_Tachie(rs); // Set global parameters script.set_alpha(alpha); script.set_gTarget(allocationTarget); // Call script for output allocation script.forEach_fade(allocationSource, allocationOut); // Copy script result into bitmap Bitmap outBitmap = source.copy(source.getConfig(), true); allocationOut.copyTo(outBitmap); // Destroy everything to free memory allocationSource.destroy(); allocationTarget.destroy(); allocationOut.destroy(); script.destroy(); rs.destroy(); return outBitmap; } }
30.66
92
0.696021
6c9affb83b65756e82a0c7a3c672b54d416a3770
1,929
package pg.gipter.toolkit.sharepoint.soap; import org.w3c.dom.*; import javax.xml.parsers.*; import java.util.Map; class BatchElement { private final Map<String, String> attributes; BatchElement(Map<String, String> attributes) { this.attributes = attributes; } Element create() { try { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document rootDocument = docBuilder.newDocument(); Element batch = rootDocument.createElement("Batch"); batch.setAttribute("ListVersion", "1"); batch.setAttribute("OnError", "Continue"); batch.setAttribute("ViewName", attributes.get("ViewName")); batch.setAttribute("RootFolder", attributes.get("RootFolder")); Element methodElement = rootDocument.createElement("Method"); methodElement.setAttribute("Cmd", attributes.get("Cmd")); methodElement.setAttribute("ID", "1"); batch.appendChild(methodElement); rootDocument.appendChild(batch); attributes.remove("ViewName"); attributes.remove("RootFolder"); attributes.remove("Cmd"); Element createdElement; for (Map.Entry<String, String> aField : attributes.entrySet()) { createdElement = rootDocument.createElement("Field"); createdElement.setAttribute("Name", aField.getKey()); Text attributeValue = rootDocument.createTextNode("" + aField.getValue()); createdElement.appendChild(attributeValue); methodElement.appendChild(createdElement); } return rootDocument.getDocumentElement(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex.toString()); } } }
36.396226
90
0.627786
dbc138e24da354fd96c4f7397696435308f35391
1,639
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedHashSet; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); LinkedHashSet<Student> students = new LinkedHashSet<>(); while (true){ String[] info = reader.readLine().split("\\s+"); if (info[0].equals("END")){ break; }else{ String fName = info[0]; String lName = info[1]; int age = Integer.parseInt(info[2]); Student student = new Student(fName,lName,age); students.add(student); } } students.stream() .filter(x-> x.getAge()>= 18 && x.getAge()<= 24) .forEach(x-> System.out.println(x.toString())); } } class Student { private String firstName; private String secondName; private int age; public Student(String firstName, String secondName, int age) { this.firstName = firstName; this.secondName = secondName; this.age = age; } public Student() { } public String getFirstName() { return firstName; } public String getSecondName() { return secondName; } public int getAge() { return age; } @Override public String toString() { return this.getFirstName()+" "+this.getSecondName()+" "+this.getAge(); } }
26.015873
86
0.546065
08d0b976ebacaf163e52c78bbb318ce877a88403
1,486
package net.sourceforge.marathon.component.jide; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseEvent; import org.json.JSONArray; import com.jidesoft.swing.JideSplitPane; import net.sourceforge.marathon.component.RComponent; import net.sourceforge.marathon.javarecorder.IJSONRecorder; import net.sourceforge.marathon.javarecorder.JSONOMapConfig; public class RJideSplitPaneElement extends RComponent { private String prevLocations; public RJideSplitPaneElement(Component source, JSONOMapConfig omapConfig, Point point, IJSONRecorder recorder) { super(source, omapConfig, point, recorder); } @Override protected void mouseButton1Pressed(MouseEvent me) { JideSplitPane sp = (JideSplitPane) getComponent(); prevLocations = new JSONArray(sp.getDividerLocations()).toString(); } @Override protected void mouseReleased(MouseEvent me) { JideSplitPane sp = (JideSplitPane) getComponent(); String currentDividerLoctions = new JSONArray(sp.getDividerLocations()).toString(); if (!currentDividerLoctions.equals(prevLocations)) { recorder.recordSelect(this, currentDividerLoctions); } } @Override public String _getText() { JideSplitPane sp = (JideSplitPane) getComponent(); return new JSONArray(sp.getDividerLocations()).toString(); } @Override public String getTagName() { return "jide-split-pane"; } }
30.326531
116
0.727456
00422c80830a1454c4f3f9101e526dd4cb071ed1
15,137
package bio.terra.cli.businessobject; import bio.terra.cli.exception.SystemException; import bio.terra.cli.serialization.persisted.PDUser; import bio.terra.cli.service.GoogleOauth; import bio.terra.cli.service.SamService; import bio.terra.cli.service.utils.HttpUtils; import bio.terra.cli.utils.FileUtils; import bio.terra.cli.utils.UserIO; import com.google.api.client.http.HttpStatusCodes; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.UserCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.util.Date; import java.util.List; import java.util.Optional; import org.broadinstitute.dsde.workbench.client.sam.model.UserStatusInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Internal representation of a user. An instance of this class is part of the current context or * state. */ @SuppressFBWarnings( value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Known false positive for certain try-with-resources blocks, which are used in several methods in this class. https://github.com/spotbugs/spotbugs/issues/1338 (Other similar issues linked from there.)") public class User { private static final Logger logger = LoggerFactory.getLogger(User.class); // id that Terra uses to identify a user. the CLI queries SAM for a user's subject id to populate // this field. private String id; // name that Terra associates with this user. the CLI queries SAM for a user's email to populate // this field. private String email; // proxy group email that Terra associates with this user. permissions granted to the proxy group // are transitively granted to the user and all of their pet SAs. the CLI queries SAM to populate // this field. private String proxyGroupEmail; // pet SA email that Terra associates with this user. the CLI queries SAM to populate this field. private String petSAEmail; // Google credentials for the user private UserCredentials userCredentials; // these are the same scopes requested by Terra service swagger pages @VisibleForTesting public static final List<String> USER_SCOPES = ImmutableList.of("openid", "email", "profile"); // these are the same scopes requested by Terra service swagger pages, plus the cloud platform // scope. pet SAs need the cloud platform scope to talk to GCP directly (e.g. to check the status // of a GCP notebook) private static final List<String> PET_SA_SCOPES = ImmutableList.of( "openid", "email", "profile", "https://www.googleapis.com/auth/cloud-platform"); // google OAuth client secret file // (https://developers.google.com/adwords/api/docs/guides/authentication#create_a_client_id_and_client_secret) private static final String CLIENT_SECRET_FILENAME = "client_secret.json"; // URL of the landing page shown in the browser after completing the OAuth part of login // ideally this should point to product documentation or perhaps the UI, but for now the CLI // README seems like the best option. in the future, if we want to make this server-specific, then // it should become a property of the Server private static final String LOGIN_LANDING_PAGE = "https://github.com/DataBiosphere/terra-cli/blob/main/README.md"; /** Build an instance of this class from the serialized format on disk. */ public User(PDUser configFromDisk) { this.id = configFromDisk.id; this.email = configFromDisk.email; this.proxyGroupEmail = configFromDisk.proxyGroupEmail; this.petSAEmail = configFromDisk.petSAEmail; } /** Build an empty instance of this class. */ private User() {} /** * Load any existing credentials for this user. Return silently, do not prompt for login, if they * are expired or do not exist on disk. */ public void loadExistingCredentials() { // load existing user credentials from disk try (InputStream inputStream = User.class.getClassLoader().getResourceAsStream(CLIENT_SECRET_FILENAME)) { userCredentials = GoogleOauth.getExistingUserCredential( USER_SCOPES, inputStream, Context.getContextDir().toFile()); } catch (IOException | GeneralSecurityException ex) { throw new SystemException("Error fetching user credentials.", ex); } // load existing pet SA credentials from disk if (Context.getWorkspace().isEmpty() || !Context.requireWorkspace().getIsLoaded()) { logger.debug( "Current workspace is either not defined or not loaded, so there are no pet SA credentials."); return; } Path jsonKeyPath = Context.getPetSaKeyFile(this); logger.debug("Looking for pet SA key file at: {}", jsonKeyPath); if (!jsonKeyPath.toFile().exists()) { logger.debug("Pet SA key file not found for current user + workspace"); return; } } /** * Load any existing credentials for this user. Prompt for login if they are expired or do not * exist. */ public static void login() { Optional<User> currentUser = Context.getUser(); currentUser.ifPresent(User::loadExistingCredentials); // populate the current user object or build a new one User user = currentUser.orElseGet(() -> new User()); // do the login flow if the current user is undefined or has expired credentials if (currentUser.isEmpty() || currentUser.get().requiresReauthentication()) { user.doOauthLoginFlow(); } // if this is a new login... if (currentUser.isEmpty()) { try { user.fetchUserInfo(); } catch (Exception exception) { user.deleteOauthCredentials(); throw exception; } // update the global context on disk Context.setUser(user); // load the workspace metadata (if not already loaded), and the pet SA credentials if (Context.getWorkspace().isPresent()) { user.fetchWorkspaceInfo(); } } } /** Delete all credentials associated with this user. */ public void logout() { deleteOauthCredentials(); deletePetSaCredentials(); // unset the current user in the global context Context.setUser(null); } /** * Fetch the pet SA email for this user + current workspace from SAM and persist it in the global * context directory. If the pet SA does not yet exist for the user, then SAM will create it. * Grant both the user and the pet SA permission to impersonate the pet SA. This method assumes * that this user is the current user, and that there is a current workspace specified. */ public void fetchPetSaCredentials() { // if the cloud context is undefined, then something went wrong during workspace creation // just log an error here instead of throwing an exception, so that the workspace load will // will succeed and the user can delete the corrupted workspace Workspace currentWorkspace = Context.requireWorkspace(); String googleProjectId = currentWorkspace.getGoogleProjectId(); if (googleProjectId == null || googleProjectId.isEmpty()) { logger.error("No Google context for the current workspace. Skip fetching pet SA from SAM."); return; } // ask SAM for the project-specific pet SA email and persist it on disk petSAEmail = SamService.forUser(this).getPetSaEmailForProject(googleProjectId); Context.setUser(this); // Allow the user and their pet to impersonate the pet service account so that Nextflow and // other app calls can run. // TODO(PF-991): This behavior will change in the future when WSM disallows SA // self-impersonation currentWorkspace.enablePet(); logger.debug("Enabled pet SA impersonation"); } /** * Fetch the pet SA key file for this user + current workspace from SAM and persist it in the * global context directory. This method assumes that this user is the current user, and that * there is a current workspace specified. * * <p>This method should only used for testing, because the relevant SAM endpoint may not be * implemented in prod environments. * * @return the absolute path to the pet SA key file */ @VisibleForTesting public Path fetchPetSaKeyFile() { // if the key file already exists on disk, just return it Path jsonKeyPath = Context.getPetSaKeyFile(this); if (jsonKeyPath.toFile().exists()) { return jsonKeyPath; } // ask SAM for the project-specific pet SA key HttpUtils.HttpResponse petSaKeySamResponse = SamService.forUser(this) .getPetSaKeyForProject(Context.requireWorkspace().getGoogleProjectId()); logger.debug("SAM response to pet SA key request: {})", petSaKeySamResponse); if (!HttpStatusCodes.isSuccess(petSaKeySamResponse.statusCode)) { throw new SystemException( "Error fetching pet SA key from SAM (status code = " + petSaKeySamResponse.statusCode + ")."); } try { // persist the key file in the global context directory FileUtils.writeStringToFile(jsonKeyPath.toFile(), petSaKeySamResponse.responseBody); } catch (IOException ioEx) { throw new SystemException("Error writing pet SA key to the global context directory.", ioEx); } logger.debug("Stored pet SA key file for this user and workspace: {}", jsonKeyPath); return jsonKeyPath; } /** Delete this user's OAuth credentials. */ private void deleteOauthCredentials() { try (InputStream inputStream = User.class.getClassLoader().getResourceAsStream(CLIENT_SECRET_FILENAME)) { // delete the user credentials GoogleOauth.deleteExistingCredential( USER_SCOPES, inputStream, Context.getContextDir().toFile()); } catch (IOException | GeneralSecurityException ex) { throw new SystemException("Error deleting credentials.", ex); } } /** Delete all pet SA credentials for this user. */ public void deletePetSaCredentials() { File jsonKeysDir = Context.getPetSaKeyDir(this).toFile(); // delete all key files File[] keyFiles = jsonKeysDir.listFiles(); if (keyFiles != null) { for (File keyFile : keyFiles) { if (!keyFile.delete() && keyFile.exists()) { throw new SystemException( "Failed to delete pet SA key file: " + keyFile.getAbsolutePath()); } } } // delete the key file directory if (!jsonKeysDir.delete() && jsonKeysDir.exists()) { throw new SystemException( "Failed to delete pet SA key file sub-directory: " + jsonKeysDir.getAbsolutePath()); } this.petSAEmail = null; } /** * Do the OAuth login flow. If there is an existing non-expired credential stored on disk, then we * load that. If not, then we prompt the user for the requested user scopes. */ private void doOauthLoginFlow() { try (InputStream inputStream = User.class.getClassLoader().getResourceAsStream(CLIENT_SECRET_FILENAME)) { // log the user in and get their consent to the requested scopes boolean launchBrowserAutomatically = Context.getConfig().getBrowserLaunchOption().equals(Config.BrowserLaunchOption.AUTO); userCredentials = GoogleOauth.doLoginAndConsent( USER_SCOPES, inputStream, Context.getContextDir().toFile(), launchBrowserAutomatically, LOGIN_LANDING_PAGE); } catch (IOException | GeneralSecurityException ex) { throw new SystemException("Error fetching user credentials.", ex); } } /** Fetch the user information (id, email, proxy group email) for this user from SAM. */ private void fetchUserInfo() { SamService samService = SamService.forUser(this); UserStatusInfo userInfo = samService.getUserInfoOrRegisterUser(); id = userInfo.getUserSubjectId(); email = userInfo.getUserEmail(); proxyGroupEmail = samService.getProxyGroupEmail(email); } /** * Fetch the workspace metadata (if it's not already loaded) and the pet SA credentials. Don't * throw an exception if it fails, because that shouldn't block a successful login, but do log the * error to the console. */ private void fetchWorkspaceInfo() { try { if (!Context.requireWorkspace().getIsLoaded()) { // if the workspace was set without credentials, load the workspace metadata and pet SA Workspace.load(Context.requireWorkspace().getId()); } else { // otherwise, just load the pet SA fetchPetSaCredentials(); } } catch (Exception ex) { logger.error("Error loading workspace or pet SA credentials during login", ex); UserIO.getErr() .println( "Error loading workspace information for the logged in user (workspace id: " + Context.requireWorkspace().getId() + ")."); } } /** Create a credentials object for a service account from a key file. */ private static ServiceAccountCredentials createSaCredentials(Path jsonKeyPath) { try { return GoogleOauth.getServiceAccountCredential(jsonKeyPath.toFile(), PET_SA_SCOPES); } catch (IOException ioEx) { throw new SystemException("Error reading SA key file.", ioEx); } } // ==================================================== // Property getters. public String getId() { return id; } public String getEmail() { return email; } public String getProxyGroupEmail() { return proxyGroupEmail; } public String getPetSaEmail() { return petSAEmail; } public UserCredentials getUserCredentials() { return userCredentials; } public GoogleCredentials getPetSACredentials() { return GoogleCredentials.create(getPetSaAccessToken()); } /** Return true if the user credentials are expired or do not exist on disk. */ public boolean requiresReauthentication() { if (userCredentials == null) { return true; } // this method call will attempt to refresh the token if it's already expired AccessToken accessToken = getUserAccessToken(); // check if the token is expired logger.debug("Access token expiration date: {}", accessToken.getExpirationTime()); return accessToken.getExpirationTime().compareTo(new Date()) <= 0; } /** Get the access token for the user credentials. */ public AccessToken getUserAccessToken() { return GoogleOauth.getAccessToken(userCredentials); } /** Get the access token for the pet SA credentials. */ public AccessToken getPetSaAccessToken() { String googleProjectId = Context.requireWorkspace().getGoogleProjectId(); String accessTokenStr = SamService.forUser(this).getPetSaAccessTokenForProject(googleProjectId, PET_SA_SCOPES); return new AccessToken(accessTokenStr, null); } }
38.912596
210
0.704565
70cdedaee12a88839cdca1956ca2667067812997
1,799
package org.tbd.TextAdventureCreator; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import ilusr.textadventurecreator.statusbars.ProjectStatusService; import ilusr.textadventurecreator.statusbars.StatusItem; public class ProjectStatusServiceUnitTest { private ProjectStatusService service; @Before public void setup() { service = new ProjectStatusService(); } @Test public void testCreate() { assertNotNull(service); assertNotNull(service.currentItem()); } @Test public void testAddItem() { RunAction action = new RunAction(); StatusItem item = new StatusItem("Test", action); service.addStatusItemToQueue(item); assertTrue(action.ran()); } @Test public void testRemovePendingItem() { RunAction action = new RunAction(); StatusItem item = new StatusItem("Test", action); RunAction action2 = new RunAction(); StatusItem item2 = new StatusItem("Test2", action2); service.addStatusItemToQueue(item); service.addStatusItemToQueue(item2); service.removeStatusItemFromQueue(item2); item.finished().set(true); assertTrue(action.ran()); assertFalse(action2.ran()); } @Test public void testMultipleAdd() { RunAction action = new RunAction(); StatusItem item = new StatusItem("Test", action); RunAction action2 = new RunAction(); StatusItem item2 = new StatusItem("Test2", action2); service.addStatusItemToQueue(item); service.addStatusItemToQueue(item2); item.finished().set(true); assertTrue(action.ran()); assertTrue(action2.ran()); } private class RunAction implements Runnable { private boolean ran; public RunAction() { ran = false; } @Override public void run() { ran = true; } public boolean ran() { return ran; } } }
20.678161
66
0.715397
98bfbe7d2bafadf2617348bf5eba860ef1d5b096
9,043
/* * Author: Gergely Zahoranszky-Kohalmi, PhD * * Organization: National Center for Advancing Translational Sciences * * Email: zahoranszkykog2@mail.nih.gov * */ package gov.nih.ncats.smrtgraph4j; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import gov.nih.ncats.smrtgraph4j.structure.C2P; import gov.nih.ncats.smrtgraph4j.structure.Compound; import gov.nih.ncats.smrtgraph4j.structure.Pattern; public class DBOperations { private DBConnector DBC = null; private String limit = ""; public DBOperations (DBConnector connection, boolean isTest) { if (isTest) { limit = " limit 1000"; } assignDBConnetcion(connection); } public void assignDBConnetcion(DBConnector connection) { // TODO Auto-generated method stub this.DBC = connection; } public double getTargetActivityCutoff (String uniprot_id) throws SQLException { double cutoff = 0.0; List<String> columns = new ArrayList<String> (); columns.add("actual_cutoff"); String query = "select actual_cutoff from target_activity_cutoff where uniprot_id='" + uniprot_id + "'"; List<String> ACS = DBC.runQuery(query, columns); if (ACS.size() > 1) { throw new IllegalStateException ("[ERROR]: target " + uniprot_id + " has more " + "than one activity cutoff values."); } cutoff = Double.parseDouble(ACS.get(0)); return cutoff; } public List<String> acquireC2Ts () throws SQLException { List<String> C2Ts = new ArrayList<String> (); List<String> columns = new ArrayList<String> (); columns.add("compound_id"); columns.add("uniprot_id"); columns.add("can_activity_pm"); String query = "select c.compound_id, a.uniprot_id, a.can_activity_pm from compound c, canonical_activity a where a.inchi_key=c.inchi_key and a.can_activity_pm is not null order by compound_id asc, uniprot_id asc" + limit; //System.out.println(query); C2Ts = DBC.runQuery(query, columns); return C2Ts; } public List<String> acquireP2Ts () throws SQLException { /* ###### ASSOCIATING TARGETS WITH POTENT SCAFFOLDS - START ################## Logic : 1. Find active potent interaction. 2. Find the scaffolds in C2P table (compounds-all scaffold associations) that are associated to the compound of the potent interaction. 3. The identified scaffolds are potent scaffolds of the target in question. 4. List the unique target_id - scaffold_id associations. ###### ASSOCIATING TARGETS WITH POTENT SCAFFOLDS - END ################## */ List<String> P2Ts = new ArrayList<String> (); List<String> columns = new ArrayList<String> (); columns.add("pattern_id"); columns.add("uniprot_id"); //String query = "select c.pattern_id, a.uniprot_id from compound u, canonical_activity a, c2p c where a.can_activity_pm>=" + cutoff + " and a.inchi_key=u.inchi_key and u.compound_id=c.compound_id group by c.pattern_id, a.uniprot_id" + limit; String query = "select c.pattern_id, a.uniprot_id from compound u, canonical_activity a, c2p c, target_activity_cutoff tac where a.can_activity_pm>=tac.actual_cutoff and tac.uniprot_id=a.uniprot_id and a.inchi_key=u.inchi_key and u.compound_id=c.component_id group by c.pattern_id, a.uniprot_id" + limit; //System.out.println(query); P2Ts = DBC.runQuery(query, columns); return P2Ts; } public List<String> acquireC2Ps () throws SQLException { List<String> C2Ps = new ArrayList<String> (); List<String> columns = new ArrayList<String> (); columns.add("compound_id"); columns.add("pattern_id"); columns.add("islargest"); columns.add("pattern_overlap_ratio"); String query = "select component_id as compound_id, pattern_id, islargest, pattern_overlap_ratio from c2p order by compound_id asc, pattern_id asc" + limit; //System.out.println(query); C2Ps = DBC.runQuery(query, columns); return C2Ps; } public List<String> acquirePatternsOfChembl () throws SQLException { List<String> patterns = null; List<String> columns = new ArrayList<String> (); columns.add("pattern_id"); columns.add("structure"); columns.add("hash"); columns.add("ptype"); String query = "select pattern_id, structure, hash, ptype from pattern where hash is not null order by pattern_id asc" + limit; patterns = DBC.runQuery(query, columns); return patterns; } public List<String> acquireCompoundsOfChembl () throws SQLException { List<String> compounds = null; List<String> columns = new ArrayList<String> (); columns.add("compound_id"); columns.add("smiles"); columns.add("inchi_key"); String query = "select compound_id, smiles, inchi_key from compound where inchi_key is not null order by compound_id asc" + limit; compounds = DBC.runQuery(query, columns); return compounds; } public List<String> acquireTargetsOfPPIs () throws SQLException { List<String> targets = null; List<String> columns = new ArrayList<String> (); columns.add("uniprot_id"); columns.add("name"); columns.add("organism"); String query = "select u.entry as uniprot_id, u.protein_names as name, u.organism from uniprot u, (select uniprot_ida " + "as uniprot_id from ppi where uniprot_ida like '%uniprotkb:%' and type_a='psi-mi:MI:0326(protein)' " + "union select uniprot_idb as uniprot_id from ppi where uniprot_idb like '%uniprotkb:%' " + "and type_b='psi-mi:MI:0326(protein)') as t where replace(t.uniprot_id,'uniprotkb:','')=u.entry" + limit; targets = DBC.runQuery(query, columns); return targets; } public List<String> acquireTargetsOfChembl (DBConnector dbcPPI) throws SQLException { List<String> chembl_targets = null; List<String> targets = new ArrayList<String> (); List<String> tmp = null; List<String> columns = new ArrayList<String> (); columns.add("uniprot_id"); String query = "select distinct uniprot_id from canonical_activity" + limit; chembl_targets = DBC.runQuery(query, columns); for (String target: chembl_targets ) { // Here recycling the column uniprot_id columns.add("name"); columns.add("organism"); query = "select entry as uniprot_id, protein_names as name, organism from uniprot where entry='" + target + "'"; //System.out.println(query); tmp = dbcPPI.runQuery(query, columns); //System.out.println(tmp); targets.addAll(tmp); } return targets; } public List<String> acquirePPIs () throws SQLException { List<String> PPIs = new ArrayList<String> (); List<String> columns = new ArrayList<String> (); columns.add("uniprot_ida"); columns.add("uniprot_idb"); columns.add("causal_regulatory_mechanism"); columns.add("intrxn_ids"); columns.add("publication_id"); columns.add("confidence_value"); columns.add("causal_statement"); String query = "select replace(uniprot_ida, 'uniprotkb:','') as uniprot_ida, " + "replace(uniprot_idb, 'uniprotkb:','') as uniprot_idb, " + "causal_regulatory_mechanism, intrxn_ids," + " publication_id, replace(confidence_values, 'SIGNOR-miscore:','') as confidence_value, causal_statement from ppi" + " where" + " uniprot_ida like '%uniprotkb:%' and type_a='psi-mi:MI:0326(protein)' and" + " uniprot_idb like '%uniprotkb:%' and type_b='psi-mi:MI:0326(protein)'" + " and uniprot_ida!=uniprot_idb" + " and length(replace(confidence_values, 'SIGNOR-miscore:',''))>0" + " and replace(confidence_values, 'SIGNOR-miscore:','')!=''" + " and replace(confidence_values, 'SIGNOR-miscore:','')!='-'" + " and confidence_values is not null" + limit; //System.out.println(query); PPIs = DBC.runQuery(query, columns); return PPIs; } private String indicateProgress(String message) { message = message + "|"; System.out.print(message + "\r"); return message; } }
26.519062
312
0.627004
7247b034c6a6085415d613ef08226174043f0dfa
4,905
/* * 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.cassandra.gms; import org.apache.cassandra.diag.DiagnosticEventService; import org.apache.cassandra.gms.GossiperEvent.GossiperEventType; import org.apache.cassandra.locator.InetAddressAndPort; /** * Utility methods for DiagnosticEvent activities. */ final class GossiperDiagnostics { private static final DiagnosticEventService service = DiagnosticEventService.instance(); private GossiperDiagnostics() { } static void markedAsShutdown(Gossiper gossiper, InetAddressAndPort endpoint) { if (isEnabled(GossiperEventType.MARKED_AS_SHUTDOWN)) service.publish(new GossiperEvent(GossiperEventType.MARKED_AS_SHUTDOWN, gossiper, endpoint, null, null)); } static void convicted(Gossiper gossiper, InetAddressAndPort endpoint, double phi) { if (isEnabled(GossiperEventType.CONVICTED)) service.publish(new GossiperEvent(GossiperEventType.CONVICTED, gossiper, endpoint, null, null)); } static void replacementQuarantine(Gossiper gossiper, InetAddressAndPort endpoint) { if (isEnabled(GossiperEventType.REPLACEMENT_QUARANTINE)) service.publish(new GossiperEvent(GossiperEventType.REPLACEMENT_QUARANTINE, gossiper, endpoint, null, null)); } static void replacedEndpoint(Gossiper gossiper, InetAddressAndPort endpoint) { if (isEnabled(GossiperEventType.REPLACED_ENDPOINT)) service.publish(new GossiperEvent(GossiperEventType.REPLACED_ENDPOINT, gossiper, endpoint, null, null)); } static void evictedFromMembership(Gossiper gossiper, InetAddressAndPort endpoint) { if (isEnabled(GossiperEventType.EVICTED_FROM_MEMBERSHIP)) service.publish(new GossiperEvent(GossiperEventType.EVICTED_FROM_MEMBERSHIP, gossiper, endpoint, null, null)); } static void removedEndpoint(Gossiper gossiper, InetAddressAndPort endpoint) { if (isEnabled(GossiperEventType.REMOVED_ENDPOINT)) service.publish(new GossiperEvent(GossiperEventType.REMOVED_ENDPOINT, gossiper, endpoint, null, null)); } static void quarantinedEndpoint(Gossiper gossiper, InetAddressAndPort endpoint, long quarantineExpiration) { if (isEnabled(GossiperEventType.QUARANTINED_ENDPOINT)) service.publish(new GossiperEvent(GossiperEventType.QUARANTINED_ENDPOINT, gossiper, endpoint, quarantineExpiration, null)); } static void markedAlive(Gossiper gossiper, InetAddressAndPort addr, EndpointState localState) { if (isEnabled(GossiperEventType.MARKED_ALIVE)) service.publish(new GossiperEvent(GossiperEventType.MARKED_ALIVE, gossiper, addr, null, localState)); } static void realMarkedAlive(Gossiper gossiper, InetAddressAndPort addr, EndpointState localState) { if (isEnabled(GossiperEventType.REAL_MARKED_ALIVE)) service.publish(new GossiperEvent(GossiperEventType.REAL_MARKED_ALIVE, gossiper, addr, null, localState)); } static void markedDead(Gossiper gossiper, InetAddressAndPort addr, EndpointState localState) { if (isEnabled(GossiperEventType.MARKED_DEAD)) service.publish(new GossiperEvent(GossiperEventType.MARKED_DEAD, gossiper, addr, null, localState)); } static void majorStateChangeHandled(Gossiper gossiper, InetAddressAndPort addr, EndpointState state) { if (isEnabled(GossiperEventType.MAJOR_STATE_CHANGE_HANDLED)) service.publish(new GossiperEvent(GossiperEventType.MAJOR_STATE_CHANGE_HANDLED, gossiper, addr, null, state)); } static void sendGossipDigestSyn(Gossiper gossiper, InetAddressAndPort to) { if (isEnabled(GossiperEventType.SEND_GOSSIP_DIGEST_SYN)) service.publish(new GossiperEvent(GossiperEventType.SEND_GOSSIP_DIGEST_SYN, gossiper, to, null, null)); } private static boolean isEnabled(GossiperEventType type) { return service.isEnabled(GossiperEvent.class, type); } }
43.40708
136
0.734557
a04f08345fa1fc599137175fc7271ad180ed4a32
1,709
package com.katacoda.solver.subcommands; import com.katacoda.solver.models.Configuration; import com.katacoda.solver.models.Hints; import com.katacoda.solver.models.Verifications; import org.jboss.logging.Logger; import picocli.CommandLine.Command; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Parameters; import picocli.CommandLine.Spec; import java.io.PrintWriter; import java.util.concurrent.Callable; @Command(name = "request_hint", hidden = true, description = "Request hint for task an verification number. Called by challenge framework, not by people.") public class SubcommandRequestHint implements Callable<Integer> { private static final Logger LOG = Logger.getLogger(SubcommandRequestHint.class); @Spec CommandSpec spec; @Parameters(index = "0", defaultValue = "0", description = "Seconds since task prompted. (currently ignored)") private int stepUptime = 0; @Parameters(index = "1", defaultValue = "0", description = "Display hint for task.") private int task = 0; @Parameters(index = "2", defaultValue = "0", description = "Hint number of task to show") private int hint = 0; @Override public Integer call() { // TODO consider stepUptime with delay Hints hints = new Hints(); if (task == 0) { task = Configuration.getCurrentTask(); } if (hint == 0) { new Verifications().verify(task); } LOG.info(String.format("Getting hint for task %d, verification %d.", task, hint)); out().printf(hints.getHint(task, hint)); return 0; } private PrintWriter out() { return spec.commandLine().getOut(); } }
29.982456
155
0.684611
9f7a29eb717e1f3ca1475d9cc4ca34c2c86f98a8
607
/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.awt; /** * Listener interface so Java Plug-in can be notified * of changes in AWT modality */ public interface ModalityListener { /** * Called by AWT when it enters a new level of modality */ public void modalityPushed(ModalityEvent ev); /** * Called by AWT when it exits a level of modality */ public void modalityPopped(ModalityEvent ev); }
14.116279
79
0.62603
23bf44a1af0bb85bf79e58b0e1cb8ad5d791ab50
3,695
/* * #%L * BroadleafCommerce Profile * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.profile.core.domain; import org.broadleafcommerce.common.audit.Auditable; import org.broadleafcommerce.common.locale.domain.Locale; import java.io.Serializable; import java.util.List; import java.util.Map; public interface Customer extends Serializable { public Long getId(); public void setId(Long id); public String getUsername(); public void setUsername(String username); public String getPassword(); public void setPassword(String password); public boolean isPasswordChangeRequired(); public void setPasswordChangeRequired(boolean passwordChangeRequired); public String getFirstName(); public void setFirstName(String firstName); public String getLastName(); public void setLastName(String lastName); public String getEmailAddress(); public void setEmailAddress(String emailAddress); public ChallengeQuestion getChallengeQuestion(); public void setChallengeQuestion(ChallengeQuestion challengeQuestion); public String getChallengeAnswer(); public void setChallengeAnswer(String challengeAnswer); public String getUnencodedPassword(); public void setUnencodedPassword(String unencodedPassword); public boolean isReceiveEmail(); public void setReceiveEmail(boolean receiveEmail); public boolean isRegistered(); public void setRegistered(boolean registered); public String getUnencodedChallengeAnswer(); public void setUnencodedChallengeAnswer(String unencodedChallengeAnswer); public Auditable getAuditable(); public void setAuditable(Auditable auditable); public void setCookied(boolean cookied); public boolean isCookied(); public void setLoggedIn(boolean loggedIn); public boolean isLoggedIn(); public void setAnonymous(boolean anonymous); public boolean isAnonymous(); public Locale getCustomerLocale(); public void setCustomerLocale(Locale customerLocale); public Map<String, CustomerAttribute> getCustomerAttributes(); public void setCustomerAttributes(Map<String, CustomerAttribute> customerAttributes); /** * Returns true if this user has been deactivated. * Most implementations will not allow the user to login if they are deactivated. * * @return */ public boolean isDeactivated(); /** * Sets the users deactivated status. * * @param deactivated */ public void setDeactivated(boolean deactivated); public List<CustomerAddress> getCustomerAddresses(); public void setCustomerAddresses(List<CustomerAddress> customerAddresses); public List<CustomerPhone> getCustomerPhones(); public void setCustomerPhones(List<CustomerPhone> customerPhones); public List<CustomerPayment> getCustomerPayments(); public void setCustomerPayments(List<CustomerPayment> customerPayments); public String getTaxExemptionCode(); public void setTaxExemptionCode(String exemption); }
26.775362
89
0.74046
0a6353866bbd6280a16bc8b68512ed7458d368a9
1,121
package co.edu.unbosque.back_cadena_lagenerica.sale_details; import java.io.IOException; import org.springframework.boot.jackson.JsonComponent; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; @JsonComponent public class SaleDetailsSerializer extends JsonSerializer<SaleDetails>{ @Override public void serialize(SaleDetails value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { gen.writeNumberField("codigo_detalle_venta", value.getCodigo_detalle_venta()); gen.writeNumberField("cantidad_producto", value.getCantidad_producto()); gen.writeNumberField("codigo_producto", value.getProducto().getCodigo_producto()); gen.writeNumberField("codigo_venta", value.getVenta().getCodigo_venta()); gen.writeNumberField("valor_total", value.getValor_total()); gen.writeNumberField("valor_venta", value.getValor_venta()); gen.writeNumberField("valoriva", value.getValoriva()); } }
36.16129
92
0.818912
a3d018ae959ecfcdfb9b9e81e7a893cdaee0e407
15,535
/* * Entry.java * Copyright (C) 2010 RWTH Aachen University, Germany * @author Sanchez Villaamil (moa@cs.rwth-aachen.de) * * 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 moa.clusterers.clustree; public class Entry { /** * The actual entry data. */ public ClusKernel data; /** * The buffer of this entry. It can also be seen as the buffer of the child * node, it is here just to simplify the insertion recuersion. */ private ClusKernel buffer; /** * A reference to the next node in the tree. <code>null</code> if we are * at a leaf, or this is an entry is part of a lying <code>Node</code>. */ private Node child; /** * A reference to the Entry's parent Entry */ private Entry parentEntry; /** * A reference to the Node, that contains this Entry */ private Node node; /** * Last time this entry was changed. */ private long timestamp; /** * The timestamp to be used when no operation has yet been done on this * entry. * @see #timestamp */ private static final long defaultTimestamp = 0; /** * Constructor for the entry. To be used when we want to create an empty * entry. Notice that the timestamp will be set to zero, since there is no * reason to know when an empty entry was generated. * @param numberDimensions The dimensionality of the data point in tree * where this entry is used. */ public Entry(int numberDimensions) { this.data = new ClusKernel(numberDimensions); this.buffer = new ClusKernel(numberDimensions); this.child = null; this.timestamp = Entry.defaultTimestamp; } /** * Constructor that creates an <code>Entry</code> that points to the given * node. The values of <code>data</code> will be calculated for this. * @param numberDimensions The dimensionality of the node. * @param node The node to which the new <code>Entry</code> should point. * @param currentTime The timestamp for the moment where this Entry was * was generated. * @see Node * @see #data */ protected Entry(int numberDimensions, Node node, long currentTime, Entry parentEntry, Node containerNode) { this(numberDimensions); this.child = node; this.parentEntry = parentEntry; this.node = containerNode; Entry[] entries = node.getEntries(); for (int i = 0; i < entries.length; i++) { Entry entry = entries[i]; entry.setParentEntry(this); if (entry.isEmpty()) { break; } this.add(entry); } this.timestamp = currentTime; } /** * Constructuctor that creates an <code>Entry</code> with an empty buffer * and the <code>data</code> given by the <code>Kernel</code>. * @param numberDimensions The dimensionality of the information in the * cluster. * @param cluster The cluster from which the information is to be extracted. * @param currentTime The timestamp for the moment where this Entry was * was generated. * @see Kernel * @see #data */ public Entry(int numberDimensions, ClusKernel cluster, long currentTime) { this(numberDimensions); this.data.add(cluster); this.timestamp = currentTime; } /** * extended constructor with containerNode and parentEntry * @param numberDimensions * @param cluster * @param currentTime * @param parentEntry * @param containerNode */ protected Entry(int numberDimensions, ClusKernel cluster, long currentTime, Entry parentEntry, Node containerNode) { this(numberDimensions); this.parentEntry = parentEntry; this.data.add(cluster); this.node = containerNode; this.timestamp = currentTime; } /** * Copy constructor. Everythin is copied, including the child. * @param other */ protected Entry(Entry other) { this.parentEntry = other.parentEntry; this.node = other.node; this.buffer = new ClusKernel(other.buffer); this.data = new ClusKernel(other.data); this.timestamp = other.timestamp; this.child = other.child; if (other.getChild()!=null) for (Entry e : other.getChild().getEntries()){ e.setParentEntry(this); } } public Node getNode() { return node; } public void setNode(Node node) { this.node = node; } /** * Clear the Entry. All points in the buffer and in the data cluster are * lost, the connection to the child is lost and the timestamp is set to * the default value. */ protected void clear() { this.data.clear(); this.buffer.clear(); this.child = null; this.timestamp = Entry.defaultTimestamp; } /** * Clear the <code>data</code> and the <code>buffer Custer</code> in this * entry. This function does not clear the child of this <code>Entry</code>. * @see #data * @see #buffer * @see Kernel */ protected void shallowClear() { this.buffer.clear(); this.data.clear(); } /** * Calculates the distance to the data in this entry. * @param cluster The Kernel cluster to which the distance is to be * calculated. * @return The distance to the data <code>Kernel</code> in this * <code>Entry</code> * @see Kernel * @see #data */ protected double calcDistance(ClusKernel cluster) { return data.calcDistance(cluster); } /** * Calculates the distance to the data in this entry of the data in the * given entry. * @param other The <code>Entry</code> to which the distance is to be * calculated. * @return The distance to the data <code>Kernel</code> in this * <code>Entry</code> of the data <code>Kernel</code> in the other * <code>Entry</code>. * @see Kernel * @see #data */ public double calcDistance(Entry other) { return this.getData().calcDistance(other.getData()); } /** * When this entry is empty, give it it's first values. It makes sense to * have this operation separated from the aggregation, because the * aggregation first weights the values in <code>data</code> and * <code>Kernel</code>, which makes no sense in an empty entry. * @param other The entry with the information to be used to initialize * this entry. * @param currentTime The time at which this is happening. */ protected void initializeEntry(Entry other, long currentTime) { assert (this.isEmpty()); assert (other.getBuffer().isEmpty()); this.data.add(other.data); this.timestamp = currentTime; this.child = other.child; if (child!=null){ for (Entry e : child.getEntries()){ e.setParentEntry(this); } } } /** * Add the data cluster of another entry to the data cluster of this entry. * By using this function the timestamp does not get updated, nor does this * entry get older. * @param other The entry of which the data cluster should be added to * the local data cluster. * @see #data * @see Kernel#add(tree.Kernel) */ public void add(Entry other) { this.data.add(other.data); } /** * Aggregate the <code>data</code> in the <code>Kernel</code> of the other * <code>Entry</code>. * @param other The <code>Entry</code> to be aggregated. * @see #data * @see Kernel */ protected void aggregateEntry(Entry other, long currentTime, double negLambda) { this.data.aggregate(other.data, currentTime - this.timestamp, negLambda); this.timestamp = currentTime; } /** * Aggregate the given <code>Kernel</code> to the <code>data</code> cluster * of this entry. * @param otherData The <code>Entry</code> to be aggregated. * @see #data * @see Kernel */ protected void aggregateCluster(ClusKernel otherData, long currentTime, double negLambda) { this.getData().aggregate(otherData, currentTime - this.timestamp, negLambda); this.timestamp = currentTime; } /** * Aggregate the given <code>Kernel</code> to the <code>buffer</code> * cluster of this entry. * @param pointToInsert The cluster to aggregate to the buffer. * @param currentTime The time at which the aggregation occurs. * @param negLambda A parameter needed to weight the current state of the * buffer. */ protected void aggregateToBuffer(ClusKernel pointToInsert, long currentTime, double negLambda) { ClusKernel currentBuffer = this.getBuffer(); currentBuffer.aggregate(pointToInsert, currentTime - this.timestamp, negLambda); this.timestamp = currentTime; } /** * Merge this entry witht the given <code>Entry</code>. This adds the data * cluster of the given Entry to the data cluster of this entry and sets the * timestamp to the newest one of the the two entries. * @param other The entry from which the data cluster is added. * @see Kernel#add(tree.Kernel) */ protected void mergeWith(Entry other) { // We should only merge entries in leafs, and leafes should have empty // buffers. assert (this.child == null); assert (other.child == null); assert (other.buffer.isEmpty()); this.data.add(other.data); if (this.timestamp < other.timestamp) { this.timestamp = other.timestamp; } } /** * Getter for the buffer. It is the real object, that means side effects are * possible! * @return A reference to the buffer in this entry. */ protected ClusKernel getBuffer() { return buffer; } /** * Return the reference to the child of this <code>Entry</code> to navigate * in the tree. * @return A reference to the child of this <code>Entry</code> */ public Node getChild() { return child; } /** * Getter for the data. It is the real object, that means side effects are * possible! * @return A reference to the data <code>Kernel</code> in this entry. * @see Kernel */ protected ClusKernel getData() { return data; } public Entry getParentEntry() { return parentEntry; } public void setParentEntry(Entry parent) { this.parentEntry = parent; } /** * Setter for the child in this entry. Use to build the tree. * @param child The <code>Node</code> that should be a child of this * <code>Entry</code> * @see Node */ public void setChild(Node child) { this.child = child; } /** * Return the current timestamp. * @return The current timestamp. */ public long getTimestamp() { return timestamp; } /** * Clear the buffer in this entry and return a copy. No side effects are * possible (given that the copy constructor of <code>Kernel</code> makes * a deep copy). * @return A copy of the buffer. */ protected ClusKernel emptyBuffer(long currentTime, double negLambda) { this.buffer.makeOlder(currentTime - this.timestamp, negLambda); ClusKernel bufferCopy = new ClusKernel(this.buffer); this.buffer.clear(); return bufferCopy; } /** * Check if this <code>Entry</code> is empty or not. An <code>Entry</code> * is empty if the <code>data Kernel</code> is empty, since then the buffer * has to be empty. * @return <code>true</code> if the data cluster has no data points, * <code>false</code> otherwise. */ protected boolean isEmpty() { // Assert that if the data cluster is empty, the buffer cluster is // empty too. assert ((this.data.isEmpty() && this.buffer.isEmpty()) || !this.data.isEmpty()); return this.data.isEmpty(); } /** * Overwrites the LS, SS and weightedN in the data cluster of this * <code>Entry</code> to the values of the data cluster in the given * <code>Entry</code>, but adds N and classCount of the cluster in the given * Entry to the data cluster in this one. This function is useful when the * weight of an entry becomes to small, and we want to forget the * information of the old points. * @param newEntry The cluster that should overwrite the information. */ protected void overwriteOldEntry(Entry newEntry) { assert (this.getBuffer().isEmpty()); assert (newEntry.getBuffer().isEmpty()); this.data.overwriteOldCluster(newEntry.data); newEntry.setParentEntry(this.parentEntry); if (newEntry.getChild()!=null) for (Entry e : newEntry.getChild().getEntries()) e.setParentEntry(this); //this.setParentEntry(newEntry.getParentEntry()); this.child=newEntry.child; } /** * This functions reads every entry in the child node and calculates the * corresponding <code>data Kernel</code>. Timestamps are not changed. * @see #data * @see Kerne */ protected void recalculateData() { Node currentChild = this.getChild(); if (currentChild != null) { ClusKernel currentData = this.getData(); currentData.clear(); Entry[] entries = currentChild.getEntries(); for (int i = 0; i < entries.length; i++) { currentData.add(entries[i].getData()); } } else { this.clear(); } } /** * Returns true if this entry is irrelevant with respecto the given * threshold. This is done by comparing the weighted N of this Entry to * the threshold, if it is smaller, than the entry is deemed to be * irrelevant. * @param threshold The threshold under which entries at leafs can be * erased. * @return True if this entry is deemed irrelevant, false otherwise. */ protected boolean isIrrelevant(double threshold) { return this.getData().getWeight() < threshold; } /** * Ages this entrie's data AND buffer according to the given * time and aging constant. * @param currentTime the current time * @param negLambda the aging constant */ protected void makeOlder(long currentTime, double negLambda) { // assert (currentTime > this.timestamp) : "currentTime : " // + currentTime + ", this.timestamp: " + this.timestamp; long diff = currentTime - this.timestamp; this.buffer.makeOlder(diff, negLambda); this.data.makeOlder(diff, negLambda); this.timestamp = currentTime; } }
33.552916
120
0.622337
1e5b9334167a4b5bb842a14c27dfd5b3e83720f4
817
package org.wanglilong.ccm.po; import java.util.Date; public class Transaction extends BasePO{ private String id; private String creditCardId; private Integer amount; private Date time; private String merchant; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCreditCardId() { return creditCardId; } public void setCreditCardId(String creditCardId) { this.creditCardId = creditCardId; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getMerchant() { return merchant; } public void setMerchant(String merchant) { this.merchant = merchant; } }
17.76087
51
0.71481
f76c413ed59285f0f20d3b574accb22a033aca56
1,151
package com.ampota.shared.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import com.ampota.shared.dto.transaction.TransactionInfo; @FeignClient("card") public interface TransactionClient { /** * @RequestBody on Pageable is necessary here for the marshaller to work */ @GetMapping("/api/transaction") ResponseEntity<Page<TransactionInfo>> rqlSearch(@RequestParam String term, @RequestBody Pageable page); @PostMapping("/api/transaction") ResponseEntity<TransactionInfo> save(@RequestBody TransactionInfo txn); @GetMapping("/api/transaction/{id}") ResponseEntity<TransactionInfo> findOneInfo(@PathVariable Long id); }
37.129032
108
0.779322
33126606699bf6bf1fb9ee9a00124d787d2bf062
2,179
package de.gecko.medicats.claml; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "values" }) @XmlRootElement(name = "Label") public class Label implements WithMixedValues { @XmlAttribute(name = "xml:lang", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) private String xmlLang; @XmlAttribute(name = "xml:space") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) private String xmlSpace; @XmlAttribute(name = "variants") @XmlIDREF private List<Object> variants; @XmlElementRefs({ @XmlElementRef(name = "Reference", type = Reference.class), @XmlElementRef(name = "Term", type = Term.class), @XmlElementRef(name = "Para", type = Para.class), @XmlElementRef(name = "IncludeDescendants", type = IncludeDescendants.class), @XmlElementRef(name = "Fragment", type = Fragment.class), @XmlElementRef(name = "List", type = LabelList.class), @XmlElementRef(name = "Table", type = Table.class) }) @XmlMixed private List<Object> values; public String getXmlLang() { return xmlLang; } public String getXmlSpace() { return xmlSpace == null ? "default" : xmlSpace; } /** * @return unmodifiable list */ public List<Object> getVariants() { if (variants == null) variants = new ArrayList<>(); return Collections.unmodifiableList(variants); } @Override public List<Object> getValues() { if (values == null) values = new ArrayList<>(); return Collections.unmodifiableList(values); } }
29.445946
112
0.726939
f023f90b25059f3223afd033c1190fc6c45f5ac7
1,188
package be.aga.dominionSimulator.cards; import be.aga.dominionSimulator.DomCard; import be.aga.dominionSimulator.DomPlayer; import be.aga.dominionSimulator.enums.DomCardName; public class TravellerCard extends DomCard { DomCardName myUpgrade; public TravellerCard(DomCardName domCardName) { super( domCardName); } @Override public void handleCleanUpPhase() { if (owner==null) return; if ((!owner.isHumanOrPossessedByHuman() && owner.wants(myUpgrade)) || (owner.isHumanOrPossessedByHuman() && owner.getEngine().getGameFrame().askPlayer("<html>Exchange "+ this.getName()+" for " + myUpgrade.toHTML() +"</html>", "Resolving " + this.getName().toString()) && owner.getCurrentGame().countInSupply(myUpgrade)>0)){ DomPlayer theOwner = owner; owner.returnToSupply(this); DomCard theTraveller = theOwner.getCurrentGame().takeFromSupply(myUpgrade); theOwner.getDeck().addPhysicalCardWhenNotGained(theTraveller); theOwner.getDeck().justAddToDiscard(theTraveller); return; } super.handleCleanUpPhase(); } }
38.322581
178
0.660774
e960ff0cdff1f4b1f96944335aede1a81cb6d18c
1,994
package org.embulk.output.jdbc; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.embulk.output.jdbc.TimestampFormat; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TimestampFormatTest { @Test public void test() throws ParseException { Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2015/03/04 17:08:09"); Timestamp t = new Timestamp(date.getTime()); { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 9); assertEquals("2015-03-04 17:08:09.000000000", format.format(t)); } { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 0); assertEquals("2015-03-04 17:08:09", format.format(t)); } { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 1); assertEquals("2015-03-04 17:08:09.0", format.format(t)); } t.setNanos(1234567); { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 9); assertEquals("2015-03-04 17:08:09.001234567", format.format(t)); } { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 2); assertEquals("2015-03-04 17:08:09.00", format.format(t)); } { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 3); assertEquals("2015-03-04 17:08:09.001", format.format(t)); } t.setNanos(123456789); { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 9); assertEquals("2015-03-04 17:08:09.123456789", format.format(t)); } { TimestampFormat format = new TimestampFormat("yyyy-MM-dd HH:mm:ss", 1); assertEquals("2015-03-04 17:08:09.1", format.format(t)); } } }
33.233333
93
0.598295
b1dfde084b6d443b7cd7002f01378f26ba454737
205
package org.ernest.applications.trampoline.utils; public class SanitizeActuatorPrefix { public static String clean(String actuatorPrefix){ return actuatorPrefix.replaceFirst("^/",""); } }
25.625
54
0.736585
7f2deb9fb9b33c67ca537b00cd89e3809e53113c
1,431
package de.trho.rpi.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import com.pi4j.io.gpio.Pin; import com.pi4j.wiringpi.Gpio; import de.trho.rpi.core.AbstractAppModule; public class PinTestModule extends AbstractAppModule { private final List<Pin> pins; private final List<Boolean> states; private final long wait; public PinTestModule(long wait, Pin... pins) { super(RunMode.LOOP); this.pins = pins != null ? Arrays.stream(pins).collect(Collectors.toList()) : new ArrayList<>(); this.states = new ArrayList<>(); this.wait = wait; this.pins.forEach(p -> this.states.add(p != null)); logger.info(Gpio.wiringPiSetup() != 0 ? "Wiring PI setup failed." : "Wiring PI setup OK!"); } @Override public void run() { this.setRunning(true); while (this.isRunning()) { try { boolean state; // !! Pin pin; for (int i = 0; i < pins.size(); i++) { state = states.get(i); // !!not null-safe!! pin = pins.get(i); Gpio.digitalWrite(pin.getAddress(), state); System.out.printf("Setting %s to %s", pin, state); this.states.set(i, !state); Thread.sleep(this.wait); } } catch (Exception e) { e.printStackTrace(); this.exit(); break; } } this.setRunning(false); } }
26.5
100
0.60587
be10c972be093c1743f4e0b798246a90c640d2e4
368
package org.firstinspires.ftc.teamcode.Hardware; import com.qualcomm.robotcore.eventloop.opmode.OpMode; public class RobotTeleOpExample extends OpMode { Robot bsgbot = new Robot(); @Override public void init() { bsgbot.initRobot(hardwareMap); } @Override public void loop() { bsgbot.frontLeft.setPower(.25); } }
18.4
54
0.665761
5e77911a8364cf2209ef801db74654ec2764857c
845
package com.zhishiquan.openapi.urls; import com.zhishiquan.openapi.common.URLConstants; /** * 训练营接口url * @author jl */ public final class TeamUrl extends AbstractBaseUrl { private TeamUrl(String name, String url) { super(name, url); } /** * 团队成员列表 */ public static TeamUrl users(boolean isSandbox) { String host = URLConstants.PRODUCT; if(isSandbox) { host = URLConstants.SANDBOX; } return new TeamUrl("团队成员列表", host.concat("/auth/proxy/team/v1/users")); } /** * 邀请管理员 */ public static TeamUrl inviteUser(boolean isSandbox) { String host = URLConstants.PRODUCT; if(isSandbox) { host = URLConstants.SANDBOX; } return new TeamUrl("邀请管理员", host.concat("/auth/proxy/team/v1/inviteUser")); } }
22.837838
83
0.604734
1046020cdd9f3e5ba0ba0789c5f3b5c669921556
5,488
/* * 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.syncope.ext.scimv2.cxf; import java.util.List; import java.util.Map; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxrs.spring.JAXRSServerFactoryBeanDefinitionParser.SpringJAXRSServerFactoryBean; import org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor; import org.apache.cxf.transport.common.gzip.GZIPInInterceptor; import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor; import org.apache.syncope.core.logic.GroupLogic; import org.apache.syncope.core.logic.SCIMDataBinder; import org.apache.syncope.core.logic.SCIMLogic; import org.apache.syncope.core.logic.UserLogic; import org.apache.syncope.core.logic.scim.SCIMConfManager; import org.apache.syncope.core.persistence.api.dao.GroupDAO; import org.apache.syncope.core.persistence.api.dao.UserDAO; import org.apache.syncope.ext.scimv2.api.service.GroupService; import org.apache.syncope.ext.scimv2.api.service.SCIMService; import org.apache.syncope.ext.scimv2.api.service.UserService; import org.apache.syncope.ext.scimv2.cxf.service.GroupServiceImpl; import org.apache.syncope.ext.scimv2.cxf.service.SCIMServiceImpl; import org.apache.syncope.ext.scimv2.cxf.service.UserServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SCIMv2RESTCXFContext { @Autowired private Bus bus; @Autowired private ApplicationContext ctx; @ConditionalOnMissingBean @Bean public SCIMJacksonJsonProvider scimJacksonJsonProvider() { return new SCIMJacksonJsonProvider(); } @ConditionalOnMissingBean @Bean public SCIMExceptionMapper scimExceptionMapper() { return new SCIMExceptionMapper(); } @ConditionalOnMissingBean(name = "scimAddETagFilter") @Bean public AddETagFilter scimAddETagFilter() { return new AddETagFilter(); } @ConditionalOnMissingBean(name = "scimv2Container") @Bean public Server scimv2Container() { SpringJAXRSServerFactoryBean scimv2Container = new SpringJAXRSServerFactoryBean(); scimv2Container.setBus(bus); scimv2Container.setAddress("/scim"); scimv2Container.setStaticSubresourceResolution(true); scimv2Container.setBasePackages(List.of( "org.apache.syncope.ext.scimv2.api.service", "org.apache.syncope.ext.scimv2.cxf.service")); scimv2Container.setProperties(Map.of("convert.wadl.resources.to.dom", "false")); scimv2Container.setInInterceptors(List.of( ctx.getBean(GZIPInInterceptor.class), ctx.getBean(JAXRSBeanValidationInInterceptor.class))); scimv2Container.setOutInterceptors(List.of( ctx.getBean(GZIPOutInterceptor.class))); scimv2Container.setProviders(List.of( scimJacksonJsonProvider(), scimExceptionMapper(), scimAddETagFilter())); scimv2Container.setApplicationContext(ctx); return scimv2Container.create(); } @ConditionalOnMissingBean @Bean @Autowired public SCIMService scimService( final UserDAO userDAO, final GroupDAO groupDAO, final UserLogic userLogic, final GroupLogic groupLogic, final SCIMDataBinder binder, final SCIMConfManager confManager, final SCIMLogic scimLogic) { return new SCIMServiceImpl(userDAO, groupDAO, userLogic, groupLogic, binder, confManager, scimLogic); } @ConditionalOnMissingBean @Bean @Autowired public GroupService scimv2GroupService( final UserDAO userDAO, final GroupDAO groupDAO, final UserLogic userLogic, final GroupLogic groupLogic, final SCIMDataBinder binder, final SCIMConfManager confManager) { return new GroupServiceImpl(userDAO, groupDAO, userLogic, groupLogic, binder, confManager); } @ConditionalOnMissingBean @Bean @Autowired public UserService scimv2UserService( final UserDAO userDAO, final GroupDAO groupDAO, final UserLogic userLogic, final GroupLogic groupLogic, final SCIMDataBinder binder, final SCIMConfManager confManager) { return new UserServiceImpl(userDAO, groupDAO, userLogic, groupLogic, binder, confManager); } }
37.333333
109
0.729956
d199ee783003eff33ae55bfdc5913aa93a1fce7c
1,204
package globant.appFarmer.models.request; import javax.validation.constraints.Digits; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import java.math.BigDecimal; public class BoxEggRequest { @NotNull(message = "color is required.") private long color; @NotNull(message = "price is required") @Digits(integer = 8, fraction = 2, message = "the price cannot have more than two decimal places.") @Positive private BigDecimal price; @Positive private int quantityEgg; @Positive private int stock; public long getColor() { return color; } public void setColor(long color) { this.color = color; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public int getQuantityEgg() { return quantityEgg; } public void setQuantityEgg(int quantityEgg) { this.quantityEgg = quantityEgg; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } }
20.40678
103
0.658638
ae9cb4e92794b76e5b0045d8e0084f3ac3032ed9
2,993
package bead01; public class Parser { private enum Rule { S, S2, l0, T1, T2, T3, T4, T5 } private static Tokenizer t; private static Rule currentRule; private static boolean isSigned; // S -> S' | sS' private static void S(Terminal input) { if (input == Terminal.s) { isSigned = true; } currentRule = Rule.S2; } // S' -> pl0 | zT2 | dT4 private static void S2(Terminal input) { switch (input) { case p: currentRule = Rule.l0; break; case z: currentRule = Rule.T2; break; case d: currentRule = Rule.T4; break; default: throw new InvalidValueException(); } } // l0 -> dT1 private static void l0(Terminal input) { if (input == Terminal.d) { currentRule = Rule.T1; } else { throw new InvalidValueException(); } } // T1 -> dT1 | e private static void T1(Terminal input) { if (input == Terminal.d) { currentRule = Rule.T1; } else { throw new InvalidValueException(); } } // T2 -> pT2 | e private static void T2(Terminal input) { if (input == Terminal.p) { currentRule = Rule.T3; } else { throw new InvalidValueException(); } } // T3 -> dT3 | e private static void T3(Terminal input) { if (input == Terminal.d) { currentRule = Rule.T3; } else { throw new InvalidValueException(); } } // T4 -> dT4 | pT5 | e private static void T4(Terminal input) { switch (input) { case d: currentRule = Rule.T4; break; case p: currentRule = Rule.T5; break; default: throw new InvalidValueException(); } } // T5 -> dT5 | e private static void T5(Terminal input) { if (input == Terminal.d) { currentRule = Rule.T5; } else { throw new InvalidValueException(); } } private static void useRule(Terminal input) { switch(currentRule) { case S: S(input); break; case S2: S2(input); break; case l0: l0(input); break; case T1: T1(input); break; case T2: T2(input); break; case T3: T3(input); break; case T4: T4(input); break; case T5: T5(input); break; default: throw new InvalidValueException(); } } public static String result() { String output = isSigned ? t.getStr().substring(1) : t.getStr(); switch(currentRule) { case T2: case T3: case T5: return "OK ".concat(output); case T1: return "OK 0".concat(output); case T4: return "OK ".concat(output.concat(".0")); default: // there is no N -> e rule type rule in the currentRule return "FAIL"; } } public static String Parse(String input) { t = new Tokenizer(input); isSigned = false; t.First(); try { currentRule = Rule.S; useRule(t.Current()); // S rule decides whether the input is signed or not if (isSigned) { t.Next(); } while(!t.End()) { useRule(t.Current()); t.Next(); } } catch ( InvalidValueException e) { return "FAIL"; } return result(); } public static void main(String[] args) { System.out.println(Parse("asd")); } }
18.25
66
0.605747
f5989763680245655d977ab2271e01564e979395
409
package com.ctrip.framework.apollo.portal.spi.defaultimpl; import com.ctrip.framework.apollo.core.enums.Env; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.spi.MQService; public class DefaultMQService implements MQService { @Override public void sendPublishMsg(Env env, ReleaseHistoryBO releaseHistory) { //do nothing } }
27.266667
74
0.782396
90b250c40c3931bdb0827d27bbf6f9fd299f84c8
4,127
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.hybrid.appservice.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.hybrid.appservice.models.LocalizableString; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; /** Usage of the quota resource. */ @Fluent public final class CsmUsageQuotaInner { @JsonIgnore private final ClientLogger logger = new ClientLogger(CsmUsageQuotaInner.class); /* * Units of measurement for the quota resource. */ @JsonProperty(value = "unit") private String unit; /* * Next reset time for the resource counter. */ @JsonProperty(value = "nextResetTime") private OffsetDateTime nextResetTime; /* * The current value of the resource counter. */ @JsonProperty(value = "currentValue") private Long currentValue; /* * The resource limit. */ @JsonProperty(value = "limit") private Long limit; /* * Quota name. */ @JsonProperty(value = "name") private LocalizableString name; /** * Get the unit property: Units of measurement for the quota resource. * * @return the unit value. */ public String unit() { return this.unit; } /** * Set the unit property: Units of measurement for the quota resource. * * @param unit the unit value to set. * @return the CsmUsageQuotaInner object itself. */ public CsmUsageQuotaInner withUnit(String unit) { this.unit = unit; return this; } /** * Get the nextResetTime property: Next reset time for the resource counter. * * @return the nextResetTime value. */ public OffsetDateTime nextResetTime() { return this.nextResetTime; } /** * Set the nextResetTime property: Next reset time for the resource counter. * * @param nextResetTime the nextResetTime value to set. * @return the CsmUsageQuotaInner object itself. */ public CsmUsageQuotaInner withNextResetTime(OffsetDateTime nextResetTime) { this.nextResetTime = nextResetTime; return this; } /** * Get the currentValue property: The current value of the resource counter. * * @return the currentValue value. */ public Long currentValue() { return this.currentValue; } /** * Set the currentValue property: The current value of the resource counter. * * @param currentValue the currentValue value to set. * @return the CsmUsageQuotaInner object itself. */ public CsmUsageQuotaInner withCurrentValue(Long currentValue) { this.currentValue = currentValue; return this; } /** * Get the limit property: The resource limit. * * @return the limit value. */ public Long limit() { return this.limit; } /** * Set the limit property: The resource limit. * * @param limit the limit value to set. * @return the CsmUsageQuotaInner object itself. */ public CsmUsageQuotaInner withLimit(Long limit) { this.limit = limit; return this; } /** * Get the name property: Quota name. * * @return the name value. */ public LocalizableString name() { return this.name; } /** * Set the name property: Quota name. * * @param name the name value to set. * @return the CsmUsageQuotaInner object itself. */ public CsmUsageQuotaInner withName(LocalizableString name) { this.name = name; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (name() != null) { name().validate(); } } }
25.79375
95
0.63654
99fdc51206c0fb389ba810fc07739d81fac49101
8,043
/* * 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.samza.runtime; import java.time.Duration; import java.util.UUID; import org.apache.samza.SamzaException; import org.apache.samza.application.StreamApplication; import org.apache.samza.config.ApplicationConfig; import org.apache.samza.config.Config; import org.apache.samza.config.JobConfig; import org.apache.samza.coordinator.stream.CoordinatorStreamSystemConsumer; import org.apache.samza.execution.ExecutionPlan; import org.apache.samza.execution.StreamManager; import org.apache.samza.job.ApplicationStatus; import org.apache.samza.job.JobRunner; import org.apache.samza.metrics.MetricsRegistryMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.samza.job.ApplicationStatus.*; /** * This class implements the {@link ApplicationRunner} that runs the applications in a remote cluster */ public class RemoteApplicationRunner extends AbstractApplicationRunner { private static final Logger LOG = LoggerFactory.getLogger(RemoteApplicationRunner.class); private static final long DEFAULT_SLEEP_DURATION_MS = 2000; public RemoteApplicationRunner(Config config) { super(config); } @Override public void runTask() { throw new UnsupportedOperationException("Running StreamTask is not implemented for RemoteReplicationRunner"); } /** * Run the {@link StreamApplication} on the remote cluster * @param app a StreamApplication */ @Override public void run(StreamApplication app) { StreamManager streamManager = null; try { streamManager = buildAndStartStreamManager(); // TODO: run.id needs to be set for standalone: SAMZA-1531 // run.id is based on current system time with the most significant bits in UUID (8 digits) to avoid collision String runId = String.valueOf(System.currentTimeMillis()) + "-" + UUID.randomUUID().toString().substring(0, 8); LOG.info("The run id for this run is {}", runId); // 1. initialize and plan ExecutionPlan plan = getExecutionPlan(app, runId, streamManager); writePlanJsonFile(plan.getPlanAsJson()); // 2. create the necessary streams if (plan.getApplicationConfig().getAppMode() == ApplicationConfig.ApplicationMode.BATCH) { streamManager.clearStreamsFromPreviousRun(getConfigFromPrevRun()); } streamManager.createStreams(plan.getIntermediateStreams()); // 3. submit jobs for remote execution plan.getJobConfigs().forEach(jobConfig -> { LOG.info("Starting job {} with config {}", jobConfig.getName(), jobConfig); JobRunner runner = new JobRunner(jobConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Failed to run application", t); } finally { if (streamManager != null) { streamManager.stop(); } } } @Override public void kill(StreamApplication app) { StreamManager streamManager = null; try { streamManager = buildAndStartStreamManager(); ExecutionPlan plan = getExecutionPlan(app, streamManager); plan.getJobConfigs().forEach(jobConfig -> { LOG.info("Killing job {}", jobConfig.getName()); JobRunner runner = new JobRunner(jobConfig); runner.kill(); }); } catch (Throwable t) { throw new SamzaException("Failed to kill application", t); } finally { if (streamManager != null) { streamManager.stop(); } } } @Override public ApplicationStatus status(StreamApplication app) { StreamManager streamManager = null; try { boolean hasNewJobs = false; boolean hasRunningJobs = false; ApplicationStatus unsuccessfulFinishStatus = null; streamManager = buildAndStartStreamManager(); ExecutionPlan plan = getExecutionPlan(app, streamManager); for (JobConfig jobConfig : plan.getJobConfigs()) { ApplicationStatus status = getApplicationStatus(jobConfig); switch (status.getStatusCode()) { case New: hasNewJobs = true; break; case Running: hasRunningJobs = true; break; case UnsuccessfulFinish: unsuccessfulFinishStatus = status; break; case SuccessfulFinish: break; default: // Do nothing } } if (hasNewJobs) { // There are jobs not started, report as New return New; } else if (hasRunningJobs) { // All jobs are started, some are running return Running; } else if (unsuccessfulFinishStatus != null) { // All jobs are finished, some are not successful return unsuccessfulFinishStatus; } else { // All jobs are finished successfully return SuccessfulFinish; } } catch (Throwable t) { throw new SamzaException("Failed to get status for application", t); } finally { if (streamManager != null) { streamManager.stop(); } } } /* package private */ ApplicationStatus getApplicationStatus(JobConfig jobConfig) { JobRunner runner = new JobRunner(jobConfig); ApplicationStatus status = runner.status(); LOG.debug("Status is {} for job {}", new Object[]{status, jobConfig.getName()}); return status; } /** * Waits until the application finishes. */ public void waitForFinish() { waitForFinish(Duration.ofMillis(0)); } /** * Waits for {@code timeout} duration for the application to finish. * If timeout &lt; 1, blocks the caller indefinitely. * * @param timeout time to wait for the application to finish * @return true - application finished before timeout * false - otherwise */ public boolean waitForFinish(Duration timeout) { JobConfig jobConfig = new JobConfig(config); boolean finished = true; long timeoutInMs = timeout.toMillis(); long startTimeInMs = System.currentTimeMillis(); long timeElapsed = 0L; long sleepDurationInMs = timeoutInMs < 1 ? DEFAULT_SLEEP_DURATION_MS : Math.min(timeoutInMs, DEFAULT_SLEEP_DURATION_MS); ApplicationStatus status; try { while (timeoutInMs < 1 || timeElapsed <= timeoutInMs) { status = getApplicationStatus(jobConfig); if (status == SuccessfulFinish || status == UnsuccessfulFinish) { LOG.info("Application finished with status {}", status); break; } Thread.sleep(sleepDurationInMs); timeElapsed = System.currentTimeMillis() - startTimeInMs; } if (timeElapsed > timeoutInMs) { LOG.warn("Timed out waiting for application to finish."); finished = false; } } catch (Exception e) { LOG.error("Error waiting for application to finish", e); throw new SamzaException(e); } return finished; } private Config getConfigFromPrevRun() { CoordinatorStreamSystemConsumer consumer = new CoordinatorStreamSystemConsumer(config, new MetricsRegistryMap()); consumer.register(); consumer.start(); consumer.bootstrap(); consumer.stop(); Config cfg = consumer.getConfig(); LOG.info("Previous config is: " + cfg.toString()); return cfg; } }
33.65272
117
0.680343
4cc51daece880b1c31696726adec7f6add03d462
1,736
package at.technikumwien.hashtable.command; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Scanner; import at.technikumwien.hashtable.GsonHashtableWrapper; import at.technikumwien.hashtable.Hashtable; import at.technikumwien.hashtable.Stock; import com.google.gson.Gson; public class SaveCommand implements Runnable { private final Hashtable<String, String> abbrHashtable; private final Hashtable<String, Stock> stockHashtable; private final Scanner scanner; private final Gson gson; // ////////////////////////////////////////////////////////////////////////// // Init // ////////////////////////////////////////////////////////////////////////// public SaveCommand(Hashtable<String, String> abbrHashtable, Hashtable<String, Stock> stockHashtable, Scanner scanner,Gson gson) { this.abbrHashtable = abbrHashtable; this.stockHashtable = stockHashtable; this.scanner = scanner; this.gson = gson; } // ////////////////////////////////////////////////////////////////////////// // Methoden // ////////////////////////////////////////////////////////////////////////// @Override public void run() { System.out.print("New file name (____.json): "); String filename = scanner.nextLine(); String json = gson.toJson(new GsonHashtableWrapper(abbrHashtable, stockHashtable)); try { Files.write(Path.of(filename + ".json"), json.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { System.err.println("Error writing file"); } } }
35.428571
135
0.576037
13ff82db6b2e1f6c0dd091f648c90b80f1a7ade9
327
package com.github.design.component; /** * 组合模式抽象根节点 */ public interface IStaff { /** * 枝干节点获取子节点的方法 */ IStaff getChild(int index); /** * 枝干节点增加子节点的方法 */ void addChild(IStaff child); /** * 枝干节点移除子节点的方法 */ void removeChild(IStaff child); /** * 组和对象共有的行为方法 */ void information(); }
11.678571
36
0.593272
467aa66a610dc2a55399612e34f906918edc98f0
1,386
package com.deer.wms.produce.manage.model; /** * @Author: hy * @Date: 2019/7/21 18:08 * @Version 1.0 * * 物料基础信息,集成库存、公司、供应商、单位等信息 * */ public class MaterialsInfoDto extends MaterialsInfo{ private String positionName; private Float quantity; private String companyName; private String unitName; private String parentName; private String supplierName; public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } public String getPositionName() { return positionName; } public void setPositionName(String positionName) { this.positionName = positionName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public Float getQuantity() { return quantity; } public void setQuantity(Float quantity) { this.quantity = quantity; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } }
20.086957
54
0.649351
4ebeb37d8756a1514a0240f60e7f06b4468b697c
7,759
// SPDX-License-Identifier: Apache-2.0 // Copyright Contributors to the OpenTimelineIO Project. package io.opentimeline.opentimelineio; import io.opentimeline.OTIONative; import io.opentimeline.OTIOObject; import java.util.*; import java.util.function.BiConsumer; import java.util.stream.Collectors; /** * AnyDictionary has the same API as java.util.Map. * It is a Map&lt;String, Any&gt;. */ public class AnyDictionary extends OTIOObject implements Map<String, Any> { public AnyDictionary() { this.initObject(); } AnyDictionary(OTIONative otioNative) { this.nativeManager = otioNative; } private void initObject() { this.initialize(); this.nativeManager.className = this.getClass().getCanonicalName(); } private native void initialize(); /** * Holds a key, value pair.<br> * String key, Any value */ public static class AnyEntry implements Entry<String, Any> { private String key = null; private Any value = null; private AnyEntry(String key, Any value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public Any getValue() { return value; } @Override public Any setValue(Any any) { Any oldAny = value; value = any; return oldAny; } } public class Iterator extends OTIOObject implements java.util.Iterator<AnyEntry> { private boolean startedIterating = false; private Iterator(AnyDictionary anyDictionary) { this.initObject(anyDictionary); } Iterator(OTIONative otioNative) { this.nativeManager = otioNative; } private void initObject(AnyDictionary anyDictionary) { this.initialize(anyDictionary); this.nativeManager.className = this.getClass().getCanonicalName(); } private native void initialize(AnyDictionary anyDictionary); public boolean hasNext() { if (!startedIterating && size() > 0) return true; return hasNextNative(AnyDictionary.this); } public boolean hasPrevious() { return hasPreviousNative(AnyDictionary.this); } public AnyDictionary.AnyEntry next() { if (!startedIterating) { startedIterating = true; return new AnyEntry(getKey(), getValue()); } if (!hasNext()) { throw new NoSuchElementException(); } nextNative(); return new AnyEntry(getKey(), getValue()); } public AnyDictionary.AnyEntry previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } previousNative(); return new AnyEntry(getKey(), getValue()); } private native void nextNative(); private native void previousNative(); private native boolean hasNextNative(AnyDictionary anyDictionary); private native boolean hasPreviousNative(AnyDictionary anyDictionary); public native String getKey(); public native Any getValue(); } public AnyDictionary.Iterator iterator() { return new AnyDictionary.Iterator(this); } public native boolean containsKey(String key); public native Any get(String key); /** * The previous value is returned, if an existing key is passed. * null is returned, if a new pair is passed. * * @param key String key * @param value Any value * @return previous value if an existing key is passed, otherwise null */ public native Any put(String key, Any value); @Override public Any remove(Object o) { return null; } @Override public void putAll(Map<? extends String, ? extends Any> map) { } /** * The previous value associated with the key is returned. * null is returned if no such key is mapped. */ public native Any replace(String key, Any value); public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(Object o) { if (o instanceof String) return containsKey((String) o); return false; } @Override public boolean containsValue(Object o) { return false; } @Override public Any get(Object o) { if (o instanceof String) return get((String) o); return null; } public native int size(); public native void clear(); @Override public Set<String> keySet() { Set<String> keys = new HashSet<>(); Iterator iterator = iterator(); while (iterator.hasNext()) { AnyEntry element = iterator.next(); keys.add(element.getKey()); } try { iterator.close(); } catch (Exception e) { e.printStackTrace(); } return keys; } @Override public Collection<Any> values() { AnyVector anyVector = new AnyVector(); Iterator iterator = iterator(); while (iterator.hasNext()) { AnyEntry element = iterator.next(); anyVector.add(element.getValue()); } try { iterator.close(); } catch (Exception e) { e.printStackTrace(); } return anyVector; } @Override public Set<Entry<String, Any>> entrySet() { Set<Entry<String, Any>> elements = new HashSet<>(); Iterator iterator = iterator(); while (iterator.hasNext()) { elements.add(iterator.next()); } try { iterator.close(); } catch (Exception e) { e.printStackTrace(); } return elements; } @Override public void forEach(BiConsumer<? super String, ? super Any> action) { Iterator iterator = iterator(); while (iterator.hasNext()) { AnyEntry anyEntry = iterator.next(); action.accept(anyEntry.getKey(), anyEntry.getValue()); } try { iterator.close(); } catch (Exception e) { e.printStackTrace(); } } public native int remove(String key); public boolean equals(AnyDictionary anyDictionary) { if (size() != anyDictionary.size()) return false; Iterator thisIterator = iterator(); Iterator otherIterator = anyDictionary.iterator(); while (thisIterator.hasNext() && otherIterator.hasNext()) { AnyEntry thisElement = thisIterator.next(); AnyEntry otherElement = otherIterator.next(); if (!(thisElement.key.equals(otherElement.key)) || !thisElement.value.equals(otherElement.value)) return false; } try { thisIterator.close(); otherIterator.close(); } catch (Exception e) { e.printStackTrace(); } return true; } @Override public boolean equals(Object obj) { if (!(obj instanceof AnyDictionary)) return false; return this.equals((AnyDictionary) obj); } @Override public String toString() { String values = this.entrySet().stream() .map(thisElement -> thisElement.getKey().concat("=").concat(thisElement.getValue().toString())) .collect(Collectors.joining(", ")); return this.getClass().getCanonicalName() + "{" + values + "}"; } }
26.66323
111
0.571465
85187267a6da3875f3da78b750d9cfa7269d021b
2,307
package api.util; /** * The Class Sextuple. * * @param <A> * the generic type * @param <B> * the generic type * @param <C> * the generic type * @param <D> * the generic type * @param <E> * the element type * @param <F> * the generic type * @author Gwindow */ public class Sextuple<A, B, C, D, E, F> { /** The a. */ private A a; /** The b. */ private B b; /** The c. */ private C c; /** The d. */ private D d; /** The e. */ private E e; /** The f. */ private F f; /** * Instantiates a new sextuple. * * @param a * the a * @param b * the b * @param c * the c * @param d * the d * @param e * the e * @param f * the f */ public Sextuple(A a, B b, C c, D d, E e, F f) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; } /** * Gets the a. * * @return the a */ public A getA() { return a; } /** * Gets the b. * * @return the b */ public B getB() { return b; } /** * Gets the c. * * @return the c */ public C getC() { return c; } /** * Gets the d. * * @return the d */ public D getD() { return d; } /** * Sets the a. * * @param a * the new a */ public void setA(A a) { this.a = a; } /** * Sets the b. * * @param b * the new b */ public void setB(B b) { this.b = b; } /** * Sets the c. * * @param c * the new c */ public void setC(C c) { this.c = c; } /** * Sets the d. * * @param d * the new d */ public void setD(D d) { this.d = d; } /** * Gets the e. * * @return the e */ public E getE() { return e; } /** * Sets the e. * * @param e * the new e */ public void setE(E e) { this.e = e; } /** * Gets the f. * * @return the f */ public F getF() { return f; } /** * Sets the f. * * @param f * the new f */ public void setF(F f) { this.f = f; } /* (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return a + "," + b + "," + c + "," + d + "," + e + "," + f; } }
12.271277
61
0.416558
0954d6ed104491b39c63483b1f32b9997e7900b1
3,519
package util.bfs; import java.util.Collection; import java.util.Objects; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import com.google.common.collect.Sets; public class BFS { /** * Applies a BFS search to the given State and returns the goal state when found. * @param init - initial state * @param goal - tests if given state is goal state * @param nextMoves - function to return a set of valid moves from a given state * @return */ public static <T> T solve(T init, Predicate<T> goal, Function<T, Collection<T>> nextMoves) { return solve(init, goal, nextMoves, null); } /** * Applies a BFS search to the given State and returns the goal state when found. * @param init - initial state * @param goal - tests if given state is goal state * @param nextMoves - function to return a set of valid moves from a given state * @Param prune - accepts the current state and history and returns a pruned collection of states; useful when non-trivial pruning is required. * @return goal state when reached */ public static <T> T solve(T init, Predicate<T> goal, Function<T, Collection<T>> nextMoves, BiFunction<Set<T>, Set<T>, Set<T>> prune) { T answer = null; Objects.requireNonNull(init); Objects.requireNonNull(nextMoves); Objects.requireNonNull(goal); Set<T> processedStates = Sets.newLinkedHashSet(); Set<T> currentStates = Sets.newLinkedHashSet(); currentStates.add(init); outer: while (!currentStates.isEmpty()) { Set<T> newStates = Sets.newLinkedHashSet(); for (T state : currentStates) { if (goal.test(state)) { answer = state; break outer; } processedStates.add(state); newStates.addAll((Collection<T>) nextMoves.apply(state)); } newStates.removeAll(processedStates); if (prune != null) { newStates = prune.apply(newStates, processedStates); } currentStates = newStates; } return answer; } /** * * @param init - initial state * @param nextMoves - function to return a set of valid moves from a given state * @param accept - tests if given state should be accumulated into answers * @return set of states which passed accumulator */ public static <T extends State> Set<T> accumulate(T init, Predicate<T> accept, Function<T, Collection<T>> nextMoves) { Set<T> answers = Sets.newLinkedHashSet(); Objects.requireNonNull(init); Objects.requireNonNull(accept); Objects.requireNonNull(nextMoves); Set<T> processedStates = Sets.newLinkedHashSet(); Set<T> currentStates = Sets.newLinkedHashSet(); currentStates.add(init); while (!currentStates.isEmpty()) { Set<T> newStates = Sets.newLinkedHashSet(); for (T state : currentStates) { if (accept.test(state)) { answers.add(state); } processedStates.add(state); newStates.addAll((Collection<T>) nextMoves.apply(state)); newStates.removeAll(processedStates); } currentStates = newStates; } return answers; } }
32.88785
148
0.608127
2c3abe0144195c24c90655052eb73d04cab08820
1,477
/* * Copyright 2006-2021 Marcel Baumann * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package net.tangly.ui.components; import com.vaadin.flow.component.select.Select; import net.tangly.core.codes.Code; import net.tangly.core.codes.CodeType; import java.util.Objects; /** * Selection field for a reference code and all its values. * <p>Beware that the selected item can be null when {@link com.vaadin.flow.component.select.Select#setEmptySelectionAllowed(boolean)} is set to true.</p> * * @param <T> reference code to display * @see Code */ public class CodeField<T extends Code> extends Select<T> { private final CodeType<T> codeType; public CodeField(CodeType<T> codeType, String label) { setLabel(label); this.codeType = codeType; setItemLabelGenerator(o -> (Objects.isNull(o) ? "" : o.code())); setItems(codeType.codes()); setItemEnabledProvider(o -> (Objects.isNull(o) ? true : o.isEnabled())); } }
37.871795
156
0.717671
6665943f604635810deed312dc72a9b230130b71
338
package com.peng.commonlib.ui.base; /** * create by Mr.Q on 2019/3/11. * 类介绍: * 1、全局的终止操作 * 2、弹出终止对话框,回退到登录界面 */ public interface OnTerminalAction { /** * 账号认证失败,可能是因为 token 失效了 * @param msg */ void showUnauthorized(String msg); /** * 账户不可用 */ void showInvalidAccountRecord(); }
15.363636
38
0.576923
deefd4d9d19b396b048384087fdc688a5acfd7b7
786
package kr.co.popone.fitts.feature.store.bookmark; import kotlin.jvm.functions.Function0; import kotlin.jvm.internal.Lambda; import kr.co.popone.fitts.ui.decorator.FirstItemMarginDecorator; import kr.co.popone.fitts.ui.decorator.FirstItemMarginDecorator.Builder; import org.jetbrains.annotations.NotNull; final class ShopBookmarkActivity$decorator$2 extends Lambda implements Function0<FirstItemMarginDecorator> { public static final ShopBookmarkActivity$decorator$2 INSTANCE = new ShopBookmarkActivity$decorator$2(); ShopBookmarkActivity$decorator$2() { super(0); } @NotNull public final FirstItemMarginDecorator invoke() { return new Builder().setFirstItemDecorator(5, 0, 0, 0).setItemDecorator(0, 0, 0, 0).build(); } }
37.428571
109
0.754453
3677a158bd742d9e7c5f17990e7f2d83e5b6cb98
1,819
/* * Copyright (c) 2020 Vikash Madhow */ package ma.vi.esql.parser.expression; import ma.vi.esql.parser.Context; import java.util.Map; import static ma.vi.base.string.Escape.escapeJsonString; import static ma.vi.esql.parser.Translatable.Target.JSON; /** * Logical or operator in ESQL. * * @author Vikash Madhow (vikash.madhow@gmail.com) */ public class LogicalOr extends RelationalOperator { public LogicalOr(Context context, Expression<?, String> expr1, Expression<?, String> expr2) { super(context, "or", expr1, expr2); } public LogicalOr(LogicalOr other) { super(other); } @Override public LogicalOr copy() { if (!copying()) { try { copying(true); return new LogicalOr(this); } finally { copying(false); } } else { return this; } } @Override protected String trans(Target target, Map<String, Object> parameters) { switch (target) { case JSON, JAVASCRIPT -> { String e = expr1().translate(target, parameters) + " || " + expr2().translate(target, parameters); return target == JSON ? '"' + escapeJsonString(e) + '"' : e; } case SQLSERVER -> { if (ancestor("on") == null && ancestor("where") == null && ancestor("having") == null) { /* * For SQL Server, boolean expressions outside of where and having * clauses are not allowed and we simulate it with bitwise operations. */ return "cast(" + expr1().translate(target, parameters) + " | " + expr2().translate(target, parameters) + " as bit)"; } else { return super.trans(target, parameters); } } default -> { return super.trans(target, parameters); } } } }
25.985714
126
0.583288
1625fc2b456591244ea07abc66a6060497d4001f
3,216
package io.basestar.graphql.transform; import io.basestar.graphql.GraphQLStrategy; import io.basestar.graphql.GraphQLUtils; import io.basestar.schema.InstanceSchema; import io.basestar.schema.use.*; import lombok.RequiredArgsConstructor; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public interface GraphQLRequestTransform { Map<String, Object> fromRequest(InstanceSchema schema, Map<String, Object> input); @RequiredArgsConstructor class Default implements GraphQLRequestTransform { private final GraphQLStrategy strategy; @Override public Map<String, Object> fromRequest(final InstanceSchema schema, final Map<String, Object> input) { if (input == null) { return null; } else { final Map<String, Object> result = new HashMap<>(); schema.getProperties().forEach((k, prop) -> { if (input.containsKey(k)) { result.put(k, fromRequest(prop.typeOf(), input.get(k))); } }); return result; } } protected Object fromRequest(final Use<?> type, final Object value) { if (value == null) { return null; } else { return type.visit(new Use.Visitor.Defaulting<Object>() { @Override public <T> Object visitDefault(final Use<T> type) { return type.create(value); } @Override public <T> Object visitArray(final UseArray<T> type) { return ((Collection<?>) value).stream() .map(v -> fromRequest(type.getType(), v)) .collect(Collectors.toList()); } @Override public <T> Object visitSet(final UseSet<T> type) { return ((Collection<?>) value).stream() .map(v -> fromRequest(type.getType(), v)) .collect(Collectors.toSet()); } @Override @SuppressWarnings("unchecked") public <T> Object visitMap(final UseMap<T> type) { final Map<String, Object> result = new HashMap<>(); ((Collection<Map<String, ?>>) value).forEach(v -> { final String key = (String) v.get(GraphQLUtils.MAP_KEY); final Object value = fromRequest(type.getType(), v.get(GraphQLUtils.MAP_VALUE)); result.put(key, value); }); return result; } @Override @SuppressWarnings("unchecked") public Object visitStruct(final UseStruct type) { return fromRequest(type.getSchema(), (Map<String, Object>) value); } }); } } } }
34.956522
110
0.493781