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
ffcde8b55e72b94f8513981553d61b292c8b93cd
494
package sqlite.feature.in.case2; import java.util.List; import com.abubusoft.kripton.android.annotation.BindDao; import com.abubusoft.kripton.android.annotation.BindSqlInsert; import com.abubusoft.kripton.android.annotation.BindSqlParam; import com.abubusoft.kripton.android.annotation.BindSqlSelect; @BindDao(City.class) public interface DaoCity { @BindSqlInsert long insert(City bean); @BindSqlSelect(where="id in (:{args})") List<City> selectAll(@BindSqlParam long ... args); }
24.7
62
0.789474
1a8e1bb0a0e398816af5c219eef5584f891fda07
5,866
/* * 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.kafka.metadata; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Replicas { /** * An empty replica array. */ public final static int[] NONE = new int[0]; /** * Convert an array of integers to a list of ints. * * @param array The input array. * @return The output list. */ public static List<Integer> toList(int[] array) { if (array == null) return null; ArrayList<Integer> list = new ArrayList<>(array.length); for (int i = 0; i < array.length; i++) { list.add(array[i]); } return list; } /** * Convert a list of integers to an array of ints. * * @param list The input list. * @return The output array. */ public static int[] toArray(List<Integer> list) { if (list == null) return null; int[] array = new int[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } /** * Copy an array of ints. * * @param array The input array. * @return A copy of the array. */ public static int[] clone(int[] array) { int[] clone = new int[array.length]; System.arraycopy(array, 0, clone, 0, array.length); return clone; } /** * Check that a replica set is valid. * * @param replicas The replica set. * @return True if none of the replicas are negative, and there are no * duplicates. */ public static boolean validate(int[] replicas) { if (replicas.length == 0) return true; int[] sortedReplicas = clone(replicas); Arrays.sort(sortedReplicas); int prev = sortedReplicas[0]; if (prev < 0) return false; for (int i = 1; i < sortedReplicas.length; i++) { int replica = sortedReplicas[i]; if (prev == replica) return false; prev = replica; } return true; } /** * Check that an isr set is valid. * * @param replicas The replica set. * @param isr The in-sync replica set. * @return True if none of the in-sync replicas are negative, there are * no duplicates, and all in-sync replicas are also replicas. */ public static boolean validateIsr(int[] replicas, int[] isr) { if (isr.length == 0) return true; if (replicas.length == 0) return false; int[] sortedReplicas = clone(replicas); Arrays.sort(sortedReplicas); int[] sortedIsr = clone(isr); Arrays.sort(sortedIsr); int j = 0; if (sortedIsr[0] < 0) return false; int prevIsr = -1; for (int i = 0; i < sortedIsr.length; i++) { int curIsr = sortedIsr[i]; if (prevIsr == curIsr) return false; prevIsr = curIsr; while (true) { if (j == sortedReplicas.length) return false; int curReplica = sortedReplicas[j++]; if (curReplica == curIsr) break; } } return true; } /** * Returns true if an array of replicas contains a specific value. * * @param replicas The replica array. * @param value The value to look for. * * @return True only if the value is found in the array. */ public static boolean contains(int[] replicas, int value) { for (int i = 0; i < replicas.length; i++) { if (replicas[i] == value) return true; } return false; } /** * Copy a replica array without any occurrences of the given value. * * @param replicas The replica array. * @param value The value to filter out. * * @return A new array without the given value. */ public static int[] copyWithout(int[] replicas, int value) { int size = 0; for (int i = 0; i < replicas.length; i++) { if (replicas[i] != value) { size++; } } int[] result = new int[size]; int j = 0; for (int i = 0; i < replicas.length; i++) { int replica = replicas[i]; if (replica != value) { result[j++] = replica; } } return result; } /** * Copy a replica array with the given value. * * @param replicas The replica array. * @param value The value to add. * * @return A new array with the given value. */ public static int[] copyWith(int[] replicas, int value) { int[] newReplicas = new int[replicas.length + 1]; System.arraycopy(replicas, 0, newReplicas, 0, replicas.length); newReplicas[newReplicas.length - 1] = value; return newReplicas; } }
32.40884
88
0.549267
a2af9eb1dd6c84f7419480e236619902d3579d6d
1,929
package com.snaker.system.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.snaker.common.annotation.Excel; import com.snaker.common.core.domain.BaseEntity; /** * 用户喜好对象 sys_user_favor * * @author snaker * @date 2020-12-02 */ public class SysUserFavor extends BaseEntity { private static final long serialVersionUID = 1L; /** 主键 */ private String id; /** 用户ID */ @Excel(name = "用户ID") private Long userId; /** 路由路径 */ @Excel(name = "路由路径") private String routerPath; /** 类型 */ @Excel(name = "类型") private String type; /** 记录 */ @Excel(name = "记录") private String record; public void setId(String id) { this.id = id; } public String getId() { return id; } public void setUserId(Long userId) { this.userId = userId; } public Long getUserId() { return userId; } public void setRouterPath(String routerPath) { this.routerPath = routerPath; } public String getRouterPath() { return routerPath; } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setRecord(String record) { this.record = record; } public String getRecord() { return record; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("userId", getUserId()) .append("routerPath", getRouterPath()) .append("type", getType()) .append("record", getRecord()) .append("createTime", getCreateTime()) .append("updateTime", getUpdateTime()) .toString(); } }
20.09375
71
0.577501
4fbad07111a6d5d62c5f6c36be3609365cebd36a
3,285
package simulator.model; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; public class RoadMap { private List<Junction> junctionList; private List<Road> roadList; private List<Vehicle> vehicleList; private Map<String,Junction> junctionMap; private Map<String,Road> roadMap; private Map<String,Vehicle> vehicleMap; RoadMap() { this.junctionList = new ArrayList<Junction>(); this.roadList = new ArrayList<Road>(); this.vehicleList = new ArrayList<Vehicle>(); this.junctionMap = new HashMap<String,Junction>(); this.roadMap = new HashMap<String,Road>(); this.vehicleMap = new HashMap<String,Vehicle>(); } void addJunction(Junction j) { if(junctionList.contains(j)) throw new IllegalArgumentException("Junction cannot be added in RoadMap."); junctionList.add(j); junctionMap.put(j._id, j); } void addRoad(Road r){ if(!roadList.contains(r) && junctionMap.containsValue(r.getSourceJunction()) && junctionMap.containsValue(r.getDestinationJunction())) { roadList.add(r); roadMap.put(r._id, r); } else throw new IllegalArgumentException("Road cannot be added in RoadMap"); } private boolean itineraryIsValid(Vehicle v) { boolean isValid = true; int i = 0; while(i < v.getItinerary().size() - 1 && isValid) { Junction src = v.getItinerary().get(i); Junction dest = v.getItinerary().get(i + 1); Road r = src.roadTo(dest); isValid = roadList.contains(r); i++; } return isValid; } void addVehicle(Vehicle v){ if(!vehicleList.contains(v) && itineraryIsValid(v)) { vehicleList.add(v); vehicleMap.put(v._id, v); } else throw new IllegalArgumentException("Vehicle cannot be added in RoadMap"); } public Junction getJunction(String id) { return junctionMap.get(id); } public Road getRoad(String id) { return roadMap.get(id); } public Vehicle getVehicle(String id) { return vehicleMap.get(id); } public List<Junction>getJunctions(){ return Collections.unmodifiableList(junctionList); } public List<Road>getRoads(){ return Collections.unmodifiableList(roadList); } public List<Vehicle>getVehicles(){ return Collections.unmodifiableList(vehicleList); } void reset() { junctionList.clear(); roadList.clear(); vehicleList.clear(); junctionMap.clear(); roadMap.clear(); vehicleMap.clear(); } public JSONObject report() { JSONObject roadMapInfo = new JSONObject(); JSONArray junctionsReport = new JSONArray(); JSONArray roadsReport = new JSONArray(); JSONArray vehiclesReport = new JSONArray(); List<Junction> jl = Collections.unmodifiableList(new ArrayList<>(junctionList)); List<Road> rl = Collections.unmodifiableList(new ArrayList<>(roadList)); List<Vehicle> vl = Collections.unmodifiableList(new ArrayList<>(vehicleList)); for(Junction j: jl) junctionsReport.put(j.report()); for(Road r: rl) roadsReport.put(r.report()); for(Vehicle v: vl) vehiclesReport.put(v.report()); roadMapInfo.put("junctions", junctionsReport); roadMapInfo.put("roads", roadsReport); roadMapInfo.put("vehicles", vehiclesReport); return roadMapInfo; } }
24.333333
138
0.709285
ddea00edd037dbcb152909a9309ab8ffa36127a1
336
package io.netty.cases.chapter.demo18; import io.netty.channel.socket.nio.NioSocketChannel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by 李林峰 on 2018/9/6. */ public class HttpSessions { public static Map<String, NioSocketChannel> channelMap = new ConcurrentHashMap<>(); }
22.4
88
0.729167
e9d94bc736508dc8964c831c497d7d4e83858728
931
import java.text.DecimalFormat; public class IPhone extends SmartPhone { protected int iMessages; public static final double IMESSAGE_RATE = .35; public IPhone (String numberIn, int textsIn, int minutesIn, int dataIn, int iMessagesIn) { super(numberIn, textsIn, minutesIn, dataIn); iMessages = iMessagesIn; } public int getIMessages() { return iMessages; } public void setIMessages(int iMessagesIn) { iMessages = iMessagesIn; } public double calculateBill() { double bill = 0.0; bill = super.calculateBill(); bill += (iMessages * IMESSAGE_RATE); return bill; } public void resetBill() { super.resetBill(); iMessages = 0; } public String toString() { String output = ""; output += super.toString() + ", " + iMessages + " iMessages"; return output; } }
19.808511
67
0.598281
f6a5fc037a9efb0f1bb106e17545b8510d7d2259
1,124
package org.sag.acminer.phases.acminer.dw; import org.sag.acminer.database.defusegraph.id.Identifier; public class UnknownConstant extends DataWrapper implements Constant { /* We remove any soot identifying information because holding it does not * give us any additional info and we want to make this in-line with all * the other constants which remove such information. The only ones that * might hold such information are the variables because method and field * refs are still important. */ private final String val; public UnknownConstant(Identifier val) { super(Identifier.getUnknownConstantId(val.toString())); this.val = val.toString(); } private UnknownConstant(UnknownConstant p) { this(p.getIdentifier().clone()); } public boolean equals(Object o) { if(this == o) return true; if(o == null || !(o instanceof UnknownConstant)) return false; return val.equals(((UnknownConstant)o).val); } public int hashCode() { return val.hashCode(); } public String toString() { return val; } public UnknownConstant clone() { return new UnknownConstant(this); } }
24.977778
74
0.728648
df758a1e59f1e2ef5905398ba6bc0fe67a1ce7d5
3,415
/* * Copyright 2018 UGURCAN YILDIRIM * * 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 mobi.mergen.androidshowcase.ui.base; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.blankj.utilcode.util.LogUtils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.inject.Inject; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.lifecycle.LiveData; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import dagger.android.support.DaggerFragment; import mobi.mergen.androidshowcase.viewmodel.ViewModelFactory; public abstract class BaseFragment<V extends ViewDataBinding, M extends BaseViewModel> extends DaggerFragment { @Inject ViewModelFactory viewModelFactory; private V binding; private M viewModel; private List<LiveData> observedDataList; public abstract int layoutRes(); public abstract Class<M> viewModelClass(); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { LogUtils.d("onCreateView()", getClass().getSimpleName()); binding = DataBindingUtil.inflate( inflater, layoutRes(), container, false); viewModel = ViewModelProviders.of(this, viewModelFactory) .get(viewModelClass()); observedDataList = new ArrayList<>(); getLifecycle().addObserver(viewModel); return binding.getRoot(); } public V getBinding() { return binding; } public M getViewModel() { return viewModel; } public <D> void observe(LiveData<D> liveData, Observer<D> observer) { observedDataList.add(liveData); liveData.observe(this, observer); } @Override public void onDestroyView() { super.onDestroyView(); LogUtils.d("onDestroyView()", getClass().getSimpleName()); stopObservingData(); getLifecycle().removeObserver(viewModel); binding.unbind(); binding = null; } private void stopObservingData() { Iterator<LiveData> iterator = observedDataList.iterator(); while (iterator.hasNext()) { LiveData liveData = iterator.next(); liveData.removeObservers(this); iterator.remove(); } observedDataList = null; } @Override public void onStart() { super.onStart(); LogUtils.d("onStart()", getClass().getSimpleName()); } @Override public void onStop() { super.onStop(); LogUtils.d("onStop()", getClass().getSimpleName()); } }
28.458333
93
0.686969
331094d5f021a194712f6cd3834a38f8723904b7
2,358
package math.easy; import java.util.ArrayList; import java.util.List; /** * 412. Fizz Buzz * * @author yclimb * @date 2020/12/29 */ public class FizzBuzz { public static void main(String[] args) { test(); } /** * Fizz Buzz * 写一个程序,输出从 1 到 n 数字的字符串表示。 * * 1. 如果 n 是3的倍数,输出“Fizz”; * * 2. 如果 n 是5的倍数,输出“Buzz”; * * 3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。 * * 示例: * * n = 15, * * 返回: * [ * "1", * "2", * "Fizz", * "4", * "Buzz", * "Fizz", * "7", * "8", * "Fizz", * "Buzz", * "11", * "Fizz", * "13", * "14", * "FizzBuzz" * ] * * 作者:力扣 (LeetCode) * 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xngt85/ * 链接:https://leetcode-cn.com/problems/fizz-buzz/ * 来源:力扣(LeetCode) * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ private static void test() { int n = 15; //List<String> list = fizzBuzz(n); List<String> list = fizzBuzz2(n); System.out.println(list.toString()); } public static List<String> fizzBuzz(int n) { String f = "Fizz"; String b = "Buzz"; List<String> list = new ArrayList<>(n); StringBuilder tmp = new StringBuilder(); for (int i = 1; i <= n; i++) { if (i % 3 == 0) { tmp.append(f); } if (i % 5 == 0) { tmp.append(b); } if (tmp.length() == 0) { tmp.append(i); } list.add(tmp.toString()); tmp.setLength(0); } return list; } public static List<String> fizzBuzz2(int n) { String f = "Fizz"; String b = "Buzz"; String fb = "FizzBuzz"; List<String> list = new ArrayList<>(n); for (int i = 1; i <= n; i++) { boolean b3 = (i % 3 == 0); boolean b5 = (i % 5 == 0); if (b3 && b5) { list.add(fb); } else if (b3) { list.add(f); } else if (b5) { list.add(b); } else { list.add(String.valueOf(i)); } } return list; } }
22.457143
84
0.409669
5d3e94a6ddf3b20cdc4f9f915c89e7ce4fb3abdf
1,480
/* * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.format.formatter.intellij.codestyle; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; /** * Adapter class to expose an IntelliJ {@link com.intellij.openapi.editor.Document} as an * Eclipse {@link org.eclipse.jface.text.Document}. * * @author Phillip Webb */ class EclipseDocumentAdapter extends Document { private final com.intellij.openapi.editor.Document intellijDocument; EclipseDocumentAdapter(com.intellij.openapi.editor.Document intellijDocument) { super(intellijDocument.getText()); this.intellijDocument = intellijDocument; } @Override public void replace(int pos, int length, String text, long modificationStamp) throws BadLocationException { super.replace(pos, length, text, modificationStamp); this.intellijDocument.replaceString(pos, pos + length, text); } }
33.636364
108
0.766216
fc37ab0debc35f76629769d0791004e7431cd8f2
335
package org.parcore.api.client.auth; /** * PAR API * <p> * OAuthFlow * <p> * OpenAPI spec version: 1.0.0 * <p> * This class is based on code auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git */ public enum OAuthFlow { accessCode, implicit, password, application }
20.9375
84
0.695522
e6126e0495b6fda8b14d691bf97912952583a0a8
339
package com.explore.dao; import com.explore.pojo.Coach; public interface CoachMapper { int deleteByPrimaryKey(Integer id); int insert(Coach record); int insertSelective(Coach record); Coach selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Coach record); int updateByPrimaryKey(Coach record); }
19.941176
50
0.752212
78c622f32181fc4a12f7eecfada139ed7341531c
860
package com.github.robsonbittencourt.salesparser.file.parser; import com.github.robsonbittencourt.salesparser.domain.Salesman; import org.springframework.stereotype.Service; import java.math.BigDecimal; @Service final class SalesmanLineParser extends AbstractLineParser { public static final int CPF_POSITION = 1; public static final int NAME_POSITION = 2; public static final int SALARY_POSITION = 3; @Override public Salesman parseLine(String line) { String cpf = getString(line, CPF_POSITION); String name = getString(line, NAME_POSITION); BigDecimal salary = getBigDecimal(line, SALARY_POSITION); return new Salesman(cpf, name, salary); } @Override protected String separator() { return "ç"; } @Override protected int fieldsQuantity() { return 4; } }
24.571429
65
0.706977
faa7636a4eabceff90f9c8195fa72f43dc4b0e34
6,304
// // Copyright (c) 2017-present, ViroMedia, Inc. // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.viro.core; import java.lang.ref.WeakReference; /** * The PhysicsWorld encapsulates the physics simulation associated with the {@link Scene}. Each * Scene automatically creates a PhysicsWorld upon construction. This object can be used to set * global physics properties like gravity. * <p> * For an extended discussion of physics in Viro, refer to the <a href="https://virocore.viromedia.com/docs/physics">Physics * Guide</a>. */ public class PhysicsWorld { /** * Callback used when hit tests are completed. This callback does not indicate what collisions * occurred: each PhysicsBody's individual {@link PhysicsBody.CollisionListener} * will receive those collision callbacks. */ public interface HitTestListener { /** * Invoked when a hit test has completed. Each individual {@link PhysicsBody} receives in * its {@link PhysicsBody.CollisionListener} a {@link * PhysicsBody.CollisionListener#onCollided(String, Vector, Vector)} * upon collision. This callback only returns if there was any hit. * * @param hasHit True if the hit test intersected with anything. */ void onComplete(boolean hasHit); } private WeakReference<Scene> mScene; /** * @hide * @param scene */ PhysicsWorld(Scene scene) { mScene = new WeakReference<Scene>(scene); } /** * Set the constant gravity force to use in the physics simulation. Gravity globally accelerates * physics bodies in a specific direction. This defaults to Earth's gravitational force: {0, * -9.81, 0}. Not all physics bodies need to respond to gravity: this can be set via {@link * PhysicsBody#setUseGravity(boolean)}. * * @param gravity The gravity vector to use. */ public void setGravity(Vector gravity) { Scene scene = mScene.get(); if (scene != null) { scene.setPhysicsWorldGravity(gravity.toArray()); } } /** * Enable or disable physics 'debug draw' mode. When this mode is enabled, the physics shapes * will be drawn around each object with a PhysicsBody. This is useful for understanding what * approximations the physics simulation is using during its computations. * * @param debugDraw True to enable debug draw mode. */ public void setDebugDraw(boolean debugDraw) { Scene scene = mScene.get(); if (scene != null) { scene.setPhysicsDebugDraw(debugDraw); } } /** * Find collisions between the ray from <tt>from</tt> to <tt>to</tt> with any {@link Node} objects * that have physics bodies. Each individual {@link PhysicsBody} will receive in * its {@link PhysicsBody.CollisionListener} a {@link * PhysicsBody.CollisionListener#onCollided(String, Vector, Vector)} * event upon collision. The event will contain the tag given to this intersection test. * * @param from The source of the ray. * @param to The destination of the ray. * @param closest True to only collide with the closest object. * @param tag The tag to use to identify this ray test in the <tt>onCollision</tt> callback of each {@link PhysicsBody}. * @param callback The {@link HitTestListener} to use, which will be invoked when the test is completed. */ public void findCollisionsWithRayAsync(Vector from, Vector to, boolean closest, String tag, HitTestListener callback) { Scene scene = mScene.get(); if (scene != null) { scene.findCollisionsWithRayAsync(from.toArray(), to.toArray(), closest, tag, callback); } } /** * Find collisions between the {@link PhysicsShape} cast from <tt>from</tt> to <tt>to</tt> with * any {@link Node} objects that have physics bodies. Each individual {@link PhysicsBody} will * receive in its {@link PhysicsBody.CollisionListener} a {@link * PhysicsBody.CollisionListener#onCollided(String, Vector, Vector)} event * upon collision. The event will contain the tag given to this intersection test. * * @param from The source of the ray. * @param to The destination of the ray. * @param shape The shape to use for the collision test. Only {@link PhysicsShapeSphere} and * {@link PhysicsShapeBox} are supported. * @param tag The tag to use to identify this ray test in the <tt>onCollision</tt> callback * of each {@link PhysicsBody}. * @param callback The {@link HitTestListener} to use, which will be invoked when the test is * completed. */ public void findCollisionsWithShapeAsync(Vector from, Vector to, PhysicsShape shape, String tag, HitTestListener callback) { Scene scene = mScene.get(); if (scene != null) { scene.findCollisionsWithShapeAsync(from.toArray(), to.toArray(), shape.getType(), shape.getParams(), tag, callback); } } }
44.083916
124
0.667513
0e466be6414eb049ad431d070170c2419f8ff049
10,974
package de.pxlab.pxl; import java.awt.*; import java.util.ArrayList; import de.pxlab.util.StringExt; /** * A paragraph of text. The text is shown in single line mode if it is only a * single line of text and in paragraph mode if the text contains multiple * lines. Single line mode is used if the text object contains only a single * string, the string does not contain any newline characters, and line wrapping * is turned off. In all other cases the text is shown in paragraph mode. In * single line mode the text reference point codes refer to the single line. In * paragraph mode the text reference point codes refer to the whole paragraph. * In this case the line width parameter must be defined. * * @version 0.3.1 */ /* * * 01/26/01 use an ExPar for color 03/15/01 made reference point and lineskip * factor object variables 03/23/01 added line breaking features * * 2007/06/16 allow pixel reference positioning for internal access */ // public class TextParagraphElement extends DisplayElement implements // PositionReferenceCodes { public class TextParagraphElement extends DisplayElement { /** Text content of this text element. */ protected String[] text = new String[1]; /** The Font for this text object. */ protected Font font = null; /** Emphasized font style. */ protected int emFontStyle = Font.BOLD; /** The emphasized Font for this text object. */ protected Font emFont = null; /** If true then the first line of the text is emphasized. */ protected boolean emphasizeFirstLine = false; /** * If false then single lines of text are treated differently in vertical * alignment than paragraphs. If true then single lines are treated like * paragraphs. False by default. */ protected boolean strictParagraphMode = false; public void setStrictParagraphMode(boolean m) { strictParagraphMode = m; } /** Reference point for text positioning. */ protected int referencePoint = PositionReferenceCodes.BASE_CENTER; /** * True if the vertical position reference should refer to pixels instead of * text lines. */ private boolean pixelPositionReference = false; /** Alignment of lines within a multiline paragraph. */ protected int alignment = AlignmentCodes.CENTER; /** * The actual lineskip is the font's natural lineskip multiplied by this * factor. */ protected double lineSkipFactor = 1.0; /** If true then automatic line wrapping is done. */ protected boolean wrapLines = false; public TextParagraphElement(ExPar i) { type = DisplayElement.TEXT; colorPar = i; setSize(10000, 1); } public TextParagraphElement(int i) { type = DisplayElement.TEXT; colorPar = new ExPar(ExParTypeCodes.COLOR, new ExParValue(new ExParExpression( i)), "Letter color"); setSize(10000, 1); } FontMetrics fontMetrics; public void show() { if (text == null) return; graphics2D.setColor(colorPar.getDevColor()); graphics2D.setFont(font); fontMetrics = graphics2D.getFontMetrics(font); ArrayList par = new ArrayList(30); if (Debug.isActive(Debug.TEXTPOS)) { graphics2D.drawLine(location.x - 200, location.y, location.x + 200, location.y); graphics2D.drawLine(location.x, location.y - 200, location.x, location.y + 200); } if (wrapLines) { // Explicit lines are kept ArrayList pl = new ArrayList(5); for (int i = 0; i < text.length; i++) { pl.addAll(StringExt.getTextParagraph(text[i])); // System.out.println("Current size of pl: " + pl.size()); // for (int j = 0; j < pl.size(); j++) System.out.println(" " // +j+": " + (String)pl.get(j)); } for (int i = 0; i < pl.size(); i++) { par.addAll(StringExt.getTextParagraph((String) pl.get(i), fontMetrics, size.width)); // System.out.println("Current size of par: " + par.size()); // for (int j = 0; j < par.size(); j++) System.out.println(" " // +j+": " + (String)par.get(j)); } } else { // Do not break lines but look for '\n' characters and // respect every single string as a single line for (int i = 0; i < text.length; i++) { // System.out.println("TextParagraphElement.show() text[" + i + // "] = " + text[i]); par.addAll(StringExt.getTextParagraph(text[i])); } } if (par.size() > 1 || strictParagraphMode) { showMultipleLines(par); } else if (par.size() == 1) { showSingleLine((String) (par.get(0))); } if (Debug.isActive(Debug.TEXTPOS)) { Rectangle bounds = getBounds(); graphics2D .drawRect(bounds.x, bounds.y, bounds.width, bounds.height); } } private void showSingleLine(String txt) { // System.out.println("TextParagraphElement.showSingleLine(): " + txt); int x = locX(referencePoint, location.x, fontMetrics.stringWidth(txt)); int y = textLocY(referencePoint, location.y, fontMetrics.getAscent()); graphics2D.drawString(txt, x, y); setBounds(x, y - fontMetrics.getAscent(), fontMetrics.stringWidth(txt), fontMetrics.getAscent() + fontMetrics.getDescent()); } private void showMultipleLines(ArrayList textPar) { // System.out.println("TextParagraphElement.showMultipleLines(): " + // textPar.size()); // lineskip is the number of screen lines per line of text int lineskip = (int) (fontMetrics.getHeight() * lineSkipFactor + 0.5); int n = textPar.size(); // These are the x- and y-shifts for every line of text int[] dxp = new int[n]; int[] dyp = new int[n]; // width of the widest line int maxWidth = 0; // Compute the y-position of the first line. The default is // dy==2 and the first line is at the reference point. yy is // initialized to the position of the first line of text // relative to the reference point int yy = 0; // System.out.println("referencePoint="+referencePoint+", alignment="+alignment+", dx="+dx+", dy="+dy); int dx = referencePoint / 3; int dy = referencePoint % 3; if (pixelPositionReference) { // System.out.println("Pixel wise reference"); if (dy == 0) { // The last line is at the reference point yy = -(n - 1) * lineskip; } else if (dy == 1) { // The middle line is at the reference point. Odd // numbered paragraphs round down yy = -((n - 1) * lineskip - fontMetrics.getAscent()) / 2; } else if (dy == 2) { yy = fontMetrics.getAscent(); } } else { if (dy == 0) { // The last line is at the reference point yy = -(n - 1) * lineskip; } else if (dy == 1) { // The middle line is at the reference point. Odd // numbered paragraphs round down yy = -(n / 2) * lineskip; } } int boundy = location.y + yy - lineskip; for (int i = 0; i < n; i++) { int sw = fontMetrics.stringWidth((String) textPar.get(i)); dxp[i] = (alignment <= 0) ? 0 : (-sw / 2 * alignment); if (sw > maxWidth) maxWidth = sw; dyp[i] = yy; // System.out.println("yy = " + yy + ", lineskip = " + lineskip); yy += lineskip; } int ref_dx = -dx * (maxWidth / 2); int alg_dx = alignment * (maxWidth / 2); int xp = location.x + ref_dx + alg_dx; if (emphasizeFirstLine) { graphics2D.setFont(emFont); graphics2D.drawString((String) textPar.get(0), xp + dxp[0], location.y + dyp[0]); graphics2D.setFont(font); for (int i = 1; i < n; i++) { graphics2D.drawString((String) textPar.get(i), xp + dxp[i], location.y + dyp[i]); } } else { for (int i = 0; i < n; i++) { graphics2D.drawString((String) textPar.get(i), xp + dxp[i], location.y + dyp[i]); } } setBounds(location.x + ref_dx, boundy, maxWidth, n * lineskip); } public void setProperties(String[] txt, String ff, int fst, int fs, int x, int y, int w, int ref, int align, boolean em1st, boolean wrp, double lskp) { /* * System.out.println("Text = " + txt[0]); System.out.println("Font = " * + ff); System.out.println("Ref = " + ref); * System.out.println("Ali = " + align); System.out.println("x = " + x + * " y = " + y); */ setText(txt); setFont(ff, fst, fs); setLocation(x, y); setSize(w, 1); setReferencePoint(ref); alignment = align; wrapLines = wrp; emphasizeFirstLine = em1st; if (emphasizeFirstLine) { setEmFont(ff, fs); } lineSkipFactor = lskp; } public void setWrapLines(boolean w) { wrapLines = w; } /** Set a TEXT object's text string. */ public void setText(String[] t) { text = t; } /** Set a TEXT object's text string. */ public void setText(String t) { text = new String[1]; text[0] = t; } /** Get a TEXT object's text string. */ public String[] getText() { return (text); } /** Set the text paragraph's reference point. */ public void setReferencePoint(int p) { referencePoint = Math.abs(p) % 9; } /** * Set the text paragraph's reference point. If this method is called then * the vertical reference is computed relative to the paragraph's pixel size * instead of with reference to its text lines. * * @param p * the position reference code. */ public void setPixelReferencePoint(int p) { pixelPositionReference = true; referencePoint = Math.abs(p) % 9; } /** Get a TEXT object's reference position code. */ public int getReferencePoint() { return (referencePoint); } /** Set a TEXT object's reference position code. */ public void setAlignment(int p) { alignment = Math.abs(p) % 3; } /** Get a TEXT object's reference position code. */ public int getAlignment() { return (alignment); } /** * Set the line skip factor which is used to multiply the font's character * height for finding the actual line skip. */ public void setLineSkipFactor(double d) { lineSkipFactor = d; } /** Get the line skip factor. */ public double getLineSkipFactor() { return (lineSkipFactor); } /** Set a TEXT object's font. */ public void setFont(Font fnt) { font = fnt; } /** * Set the font of this text element if the new font properties are * different from the current font. */ public void setFont(String fn, int ft, int fs) { if ((font == null) || (!(font.getName().equals(fn))) || (font.getStyle() != ft) || (font.getSize() != fs)) { // System.out.println("Setting font family " + fn + " using style " // + ft + " at size " + fs + "pt"); font = new Font(fn, ft, fs); } } public void setEmFont(String fn, int fs) { if ((emFont == null) || (!(emFont.getName().equals(fn))) || (emFont.getStyle() != emFontStyle) || (emFont.getSize() != fs)) { // System.out.println("Setting font family " + fn + " using style " // + ft + " at size " + fs + "pt"); emFont = new Font(fn, emFontStyle, fs); } } /** Get a TEXT object's font. */ public Font getFont() { return (font); } }
32.467456
106
0.630126
42edd2888e7ac0f72be71e5f51fd9b2996745825
780
package com.yuzhouwan.hacker.algorithms.leetcode.array; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Copyright @ 2019 yuzhouwan.com * All right reserved. * Function: com.yuzhouwan.hacker.algorithms.leetcode.array * * @author Benedict Jin * @since 2016/9/6 */ public class ShuffleArraySolutionTest { @Test public void operate() { int[] nums = new int[]{1, 2, 3}; ShuffleArraySolution shuffleArraySolution = new ShuffleArraySolution(nums); for (int shuffle : shuffleArraySolution.shuffle()) { System.out.print(shuffle); } int[] origin = shuffleArraySolution.reset(); for (int i = 0; i < origin.length; i++) { assertEquals(nums[i], origin[i]); } } }
25.16129
83
0.64359
d7b500a569b1207052f44a3e74c29dd454c2fa2f
16,854
/* (C) Copyright 2013-2016 The RISCOSS Project Consortium 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. */ /** * @author Alberto Siena **/ package eu.riscoss.client; import java.util.ArrayList; import org.fusesource.restygwt.client.JsonCallback; import org.fusesource.restygwt.client.Method; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.OpenEvent; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.json.client.JSONValue; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.MenuItemSeparator; import com.google.gwt.user.client.ui.PopupPanel.PositionCallback; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; import eu.riscoss.client.codec.CodecSiteMap; import eu.riscoss.client.ui.ClickWrapper; import eu.riscoss.client.ui.FramePanel; import eu.riscoss.shared.CookieNames; import eu.riscoss.shared.JSiteMap; import eu.riscoss.shared.JSiteMap.JSitePage; import eu.riscoss.shared.JSiteMap.JSiteSection; import gwtupload.client.IUploader; import gwtupload.client.SingleUploader; import gwtupload.client.IFileInput.FileInputType; import gwtupload.client.IUploader.OnFinishUploaderHandler; import gwtupload.client.IUploader.UploadedInfo; public class RiscossWebApp implements EntryPoint { abstract class MenuCommand implements Command { private String url; public MenuCommand( String url ) { this.url = url; } public String getUrl() { return this.url; } } VerticalPanel main; FramePanel currentPanel = null; SimplePanel background; SimplePanel margin; String username; public void onModuleLoad() { String domain = Cookies.getCookie( CookieNames.DOMAIN_KEY ); Log.println( "Current domain: " + domain ); RiscossCall.fromCookies().withDomain(null).auth().fx( "username" ).get( new JsonCallback() { @Override public void onSuccess( Method method, JSONValue response ) { if( response != null ) { if( response.isString() != null ) username = response.isString().stringValue(); } if( username == null ) username = ""; Log.println( "username: " + username ); RiscossJsonClient.selectDomain( RiscossCall.getDomain(), new JsonCallback() { @Override public void onSuccess( Method method, JSONValue response ) { Log.println( "Domain check response: " + response ); if( response == null ) showDomainSelectionDialog(); else if( response.isString() == null ) showDomainSelectionDialog(); else loadSitemap(); } @Override public void onFailure( Method method, Throwable exception ) { Window.alert( exception.getMessage() ); } } ); } @Override public void onFailure( Method method, Throwable exception ) { Window.alert( exception.getMessage() ); } }); } boolean confFileLoaded = false; JSiteMap sitemap; void loadSitemap() { RiscossCall.fromCookies().admin().fx( "sitemap" ).get( new JsonCallback() { @Override public void onSuccess( Method method, JSONValue response ) { CodecSiteMap codec = GWT.create( CodecSiteMap.class ); sitemap = codec.decode( response ); RiscossJsonClient.checkImportFiles( new JsonCallback() { @Override public void onFailure(Method method, Throwable exception) { Window.alert(exception.getMessage()); } @Override public void onSuccess(Method method, JSONValue response) { if (response.isObject().get("confFile").isBoolean().booleanValue()) confFileLoaded = true; showUI( sitemap ); } }); } @Override public void onFailure( Method method, Throwable exception ) { Window.alert( exception.getMessage() ); } }); } void showUI( JSiteMap sitemap) { Log.println( "Loading UI for domain " + sitemap.domain ); VerticalPanel vPanel = new VerticalPanel(); MenuBar menu = new MenuBar(); menu.setWidth(" 100% "); menu.setAnimationEnabled(true); menu.setStyleName("mainMenu"); MenuBar account = new MenuBar(true); account.setStyleName("subMenu"); account.setAnimationEnabled(true); menu.addItem( username + " (" + sitemap.domain + ")", account); account.addItem("Change domain", new Command() { @Override public void execute() { showDomainSelectionDialog(); } }); account.addItem("Logout", new Command() { @Override public void execute() { Cookies.removeCookie( CookieNames.TOKEN_KEY ); Cookies.removeCookie( CookieNames.DOMAIN_KEY ); Window.Location.reload(); } }); for( JSiteSection subsection : sitemap.getRoot().subsections() ) { if( subsection.pages().size() < 1 ) continue; if ( subsection.getLabel().equals("untracked") ) continue; MenuBar submenu = new MenuBar(true); submenu.setStyleName("subMenu"); submenu.setAnimationEnabled(true); menu.addItem( subsection.getLabel(), submenu); for( JSitePage page : subsection.pages() ) { access.add(page.getLabel()); submenu.addItem( page.getLabel(), new MenuCommand( page.getUrl() ) { @Override public void execute() { loadPanel( getUrl() ); } }); } if (subsection.getLabel().equals("Configure")) { final Button b = new Button("ye"); final SingleUploader upload = new SingleUploader(FileInputType.CUSTOM.with(b)); upload.setTitle("Upload new entities document"); upload.setAutoSubmit(true); upload.setServletPath(upload.getServletPath() + "?t=importentities&domain=" + RiscossJsonClient.getDomain()+"&token="+RiscossCall.getToken()); upload.addOnFinishUploadHandler(new OnFinishUploaderHandler() { @Override public void onFinish(IUploader uploader) { Log.println("OnFinish"); UploadedInfo info = uploader.getServerInfo(); String name = info.name; String response = uploader.getServerMessage().getMessage(); if (confFileLoaded) { RiscossJsonClient.importEntities(new JsonCallback() { @Override public void onFailure(Method method, Throwable exception) { Window.alert(exception.getMessage()); } @Override public void onSuccess(Method method, JSONValue response) { Window.alert("Entity information imported correctly"); loadPanel("entities.jsp"); } }); } else { Window.alert("Missing config xml file. Please, contact an administrator"); } } }); submenu.addSeparator(); submenu.addItem("Import entities", new MenuCommand( "Import entities" ) { @Override public void execute() { upload.fireEvent(new ClickEvent() {}); b.fireEvent(new ClickEvent() {}); } }); vPanel.add(upload); upload.setVisible(false); } } MenuBar helpUs = new MenuBar(true); helpUs.setStyleName("subMenu"); helpUs.setAnimationEnabled(true); menu.addItem("Help us", helpUs); helpUs.addItem("User feedback", new Command() { @Override public void execute() { Window.open( "http://www.essi.upc.edu/~e-survey/index.php?sid=356784&lang=en", "_self", ""); } }); helpUs.addItem("Expert feedback", new Command() { @Override public void execute() { Window.open( "http://www.essi.upc.edu/~e-survey/index.php?sid=91563&lang=en", "_self", ""); } }); HorizontalPanel hPanel = new HorizontalPanel(); VerticalPanel north = new VerticalPanel(); // Image logo = new Image( "http://riscossplatform.ow2.org/riscoss/wiki/wiki1/download/ColorThemes/RISCOSS_2/logo_riscoss_DSP.png" ); Image logo = new Image( "resources/logo_riscoss_DSP.png" ); logo.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { loadPanel("dashboard.jsp"); } }); logo.setStyleName("logo"); north.add( logo ); north.setHeight("5%"); // any value here seems to resolve the firefox problem of showing only a small frame on the right side Label version = new Label("v1.6.0"); version.setStyleName("version"); north.add(version); //north.setWidth("100%"); hPanel.add(north); //Comment this line if you don't need shortcuts generateShortcuts(); hPanel.add(shortcuts); hPanel.setWidth("100%"); vPanel.add(hPanel); vPanel.add(menu); vPanel.setWidth("100%"); RootPanel.get().add( vPanel ); RootPanel.get().setStyleName("root"); loadPanel("dashboard.jsp"); } HorizontalPanel shortcuts = new HorizontalPanel(); ArrayList<String> access = new ArrayList<>(); public void generateShortcuts() { shortcuts.setStyleName("float-right"); shortcuts.setHeight("100%"); Boolean b1 = false; Boolean b2 = false; Boolean b3 = false; //Entity-layer shortcut SimplePanel s1 = new SimplePanel(); s1.setStyleName("shortcut-1"); s1.setWidth("200px"); s1.setHeight("100px"); VerticalPanel v = new VerticalPanel(); if (access.contains("Entities")) { b1 = true; Anchor entities = new Anchor ("entities to be analysed updated"); entities.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { loadPanel("entities.jsp"); } }); HTMLPanel l1 = new HTMLPanel("Before you can run risk analysis, you need to have the <span id='entities'></span>."); l1.add(entities, "entities"); v.add(l1); } if (access.contains("Layers")) { b1 = true; Anchor layers = new Anchor ("defining a hierarchy of layers"); layers.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { loadPanel("layers.jsp"); } }); HTMLPanel l2 = new HTMLPanel("Entities can be organized hierarchically <span id='layers'></span>."); l2.add(layers, "layers"); v.add(l2); } s1.add(v); //Riskconf-model shortcut SimplePanel s2 = new SimplePanel(); s2.setWidth("200px"); s2.setHeight("100px"); s2.setStyleName("shortcut-2"); VerticalPanel vv = new VerticalPanel(); if (access.contains("Risk Configurations")) { b2 = true; Anchor riskconfs = new Anchor("defining risks configurations"); riskconfs.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { loadPanel("riskconfs.jsp"); } }); HTMLPanel l3 = new HTMLPanel("The risk analysis needs to be configured <span id='riskconfs'></span>."); l3.add(riskconfs, "riskconfs"); vv.add(l3); } if (access.contains("Models")) { b2 = true; Anchor models = new Anchor("uploaded models"); models.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { loadPanel("models.jsp"); } }); HTMLPanel l4 = new HTMLPanel("The risk configurations use the <span id='models'></span>."); l4.add(models, "models"); vv.add(l4); } s2.setWidget(vv); //analysis-browse shortcut SimplePanel s3 = new SimplePanel(); s3.setWidth("200px"); s3.setHeight("100px"); s3.setStyleName("shortcut-3"); VerticalPanel vvv = new VerticalPanel(); if (access.contains("Multi-layer Analysis")) { b3 = true; Anchor riskanalysis = new Anchor("manage your risk analysis sessions"); riskanalysis.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { loadPanel("riskanalysis.jsp"); } }); HTMLPanel l5 = new HTMLPanel("You are ready to <span id='riskanalysis'></span>"); l5.add(riskanalysis, "riskanalysis"); vvv.add(l5); } if (access.contains("Risk Analysis Sessions")) { b3 = true; Anchor ras = new Anchor("generate some comparisons"); ras.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { loadPanel("ras.jsp"); } }); HTMLPanel l6 = new HTMLPanel("You can also <span id='ras'></span>."); l6.add(ras, "ras"); vvv.add(l6); } s3.setWidget(vvv); if (b1) shortcuts.add(s1); if (b2) shortcuts.add(s2); if (b3) shortcuts.add(s3); } static class DomainSelectionDialog { DialogBox dialog = new DialogBox( true, false ); VerticalPanel panel = new VerticalPanel(); DomainSelectionDialog() { } private void addDomainOption( String name ) { Anchor a = new Anchor( name ); a.addClickHandler( new ClickWrapper<String>( name ) { @Override public void onClick( ClickEvent event ) { selectDomain( getValue() ); }} ); panel.add( a ); } protected void selectDomain( String value ) { dialog.hide(); RiscossJsonClient.selectDomain(value, new JsonCallback() { @Override public void onSuccess( Method method, JSONValue response ) { if( response == null ) return; if( response.isString() == null ) return; Log.println( "Domain set to " + response.isString().stringValue() ); Cookies.setCookie( CookieNames.DOMAIN_KEY, response.isString().stringValue() ); Window.Location.reload(); } @Override public void onFailure( Method method, Throwable exception ) { Window.alert( exception.getMessage() ); } } ); } public void show() { HorizontalPanel h = new HorizontalPanel(); h.add( new Button( "Cancel", new ClickHandler() { @Override public void onClick( ClickEvent event ) { dialog.hide(); }} ) ); panel.add( h ); dialog.setWidget( panel ); dialog.setText( "Select Domain" ); dialog.setPopupPositionAndShow( new PositionCallback() { @Override public void setPosition( int offsetWidth, int offsetHeight ) { dialog.setPopupPosition( offsetWidth /2, offsetHeight /2 ); } } ); } } protected void showDomainSelectionDialog() { RiscossCall.fromCookies().withDomain(null).admin().fx("domains").fx( "public" ).arg( "username", username ).get( new JsonCallback() { @Override public void onSuccess( Method method, JSONValue response ) { DomainSelectionDialog dsDialog = null; if( dsDialog == null ) { dsDialog = new DomainSelectionDialog(); } for( int i = 0; i < response.isArray().size(); i++ ) { dsDialog.addDomainOption( response.isArray().get( i ).isString().stringValue() ); } dsDialog.show(); } @Override public void onFailure( Method method, Throwable exception ) { Window.alert( exception.getMessage() ); } } ); } class OutlineLabel extends Anchor { String panelUrl; public OutlineLabel( String label, String panelName, ClickHandler h ) { super( label ); this.panelUrl = panelName; if( h != null ) { addClickHandler( h ); } else { addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { loadPanel( OutlineLabel.this.panelUrl ); } }); } } public OutlineLabel( String label, String panelName ) { this( label, panelName, null ); } public OutlineLabel(String label, ClickHandler clickHandler) { this( label, null, clickHandler ); } } protected void loadPanel( String url ) { if( currentPanel != null ) { RootPanel.get().remove( currentPanel.getWidget() ); currentPanel = null; } currentPanel = new FramePanel( url ); currentPanel.getWidget().setStyleName("main"); if( currentPanel != null ) { RootPanel.get().add( currentPanel.getWidget()); currentPanel.activate(); } } }
30.8117
146
0.683339
81f9c1d5888c3a6231c8ae1931bc88ed506421f3
1,352
package keisuke.count.step.format; import static keisuke.util.StringUtil.LINE_SEP; import java.io.UnsupportedEncodingException; import keisuke.StepCountResult; import keisuke.count.FormatEnum; import keisuke.count.util.EncodeUtil; /** * ステップ計測結果をCSV形式にフォーマットします。 */ public class CSVFormatter extends AbstractFormatter { CSVFormatter() { super(FormatEnum.CSV); } /** {@inheritDoc} */ public byte[] format(final StepCountResult[] results) { if (results == null) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < results.length; i++) { StepCountResult result = results[i]; sb.append(result.filePath()).append(","); sb.append(this.getSourceType(result.sourceType())).append(","); sb.append(EncodeUtil.csvEscape(result.sourceCategory())).append(","); // 未対応の形式をフォーマット if (result.isUnsupported()) { sb.append(",,,"); // 正常にカウントされたものをフォーマット } else { sb.append(Long.toString(result.execSteps())).append(","); sb.append(Long.toString(result.blancSteps())).append(","); sb.append(Long.toString(result.commentSteps())).append(","); sb.append(Long.toString(result.sumSteps())); } sb.append(LINE_SEP); } try { return sb.toString().getBytes(this.textEncoding()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }
25.509434
72
0.68713
aa5b261da884ce6dea060e32091034fe509325e8
1,658
/* * This file is part of Baritone. * * Baritone is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Baritone 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 Baritone. If not, see <https://www.gnu.org/licenses/>. */ package baritone.api.command.datatypes; import baritone.api.command.exception.CommandException; import java.util.function.Function; /** * An {@link IDatatype} which acts as a {@link Function}, in essence. The only difference * is that it requires an {@link IDatatypeContext} to be provided due to the expectation that * implementations of {@link IDatatype} are singletons. */ public interface IDatatypePost<T, O> extends IDatatype { /** * Takes the expected input and transforms it based on the value held by {@code original}. If {@code original} * is null, it is expected that the implementation of this method has a case to handle it, such that a * {@link NullPointerException} will never be thrown as a result. * * @param ctx The datatype context * @param original The transformable value * @return The transformed value */ T apply(IDatatypeContext ctx, O original) throws CommandException; }
39.47619
114
0.731001
a72f0251bc3e6e5f8e0660755c36cc5a5c4897dd
823
package com.yin.zk.config; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ZkConfiguration { @Autowired ZkConfig wrapperZk; @Bean(initMethod = "start") public CuratorFramework curatorFramework() { return CuratorFrameworkFactory.newClient( wrapperZk.getServer(), wrapperZk.getSessionTimeoutMs(), wrapperZk.getConnectionTimeoutMs(), new RetryNTimes(wrapperZk.getMaxRetries(), wrapperZk.getBaseSleepTimeMs())); } }
34.291667
92
0.746051
431bb91d141c579c23534b7dfc7b343a623253bb
3,005
package com.luck.basemodule.base; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.fragment.app.Fragment; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.ViewModelProvider; import com.luck.basemodule.view.LoadingDialog; import org.jetbrains.annotations.NotNull; import java.lang.reflect.ParameterizedType; import java.util.Objects; /** * Description: * created by shuai * 2020-08-14 * @author ProcyonLotor */ public abstract class BaseFragment<VM extends AndroidViewModel, VDB extends ViewDataBinding> extends Fragment { protected VM mViewModel; protected VDB mViewDataBind; protected LoadingDialog loadingDialog; protected Context mContext; @Override public void onAttach(@NonNull @NotNull Context context) { super.onAttach(context); mContext = context; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { loadingDialog = new LoadingDialog(requireActivity(), "加载中"); mViewDataBind = DataBindingUtil.inflate(inflater, getLayoutId(), container, false); mViewDataBind.setLifecycleOwner(this); //获得泛型参数的实际类型 Class<VM> vmClass = (Class<VM>) ((ParameterizedType) Objects.requireNonNull(this.getClass().getGenericSuperclass())) .getActualTypeArguments()[0]; mViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication())).get(vmClass); return mViewDataBind.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); afterCreate(savedInstanceState); } @Override public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onViewCreated(@NonNull @NotNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } /** * 布局文件 * * @return */ protected abstract @LayoutRes int getLayoutId(); /** * 具体代码 * * @param savedInstanceState */ protected abstract void afterCreate(Bundle savedInstanceState); public void showLoading(CharSequence message) { loadingDialog.setMessage(message); if (!loadingDialog.isShowing()) { loadingDialog.show(); } } public void dismissLoading() { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); } } }
29.174757
145
0.71614
107b14559654d98ab0e0226c9bcc93ef3f7c69cb
4,485
package de.axelspringer.ideas.team.mood.controller; import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Template; import de.axelspringer.ideas.team.mood.TeamMoodApplication; import de.axelspringer.ideas.team.mood.TeamMoodProperties; import de.axelspringer.ideas.team.mood.TeamMoodWeek; import de.axelspringer.ideas.team.mood.mail.MailContent; import de.axelspringer.ideas.team.mood.mail.MailSender; import de.axelspringer.ideas.team.mood.moods.TeamMood; import de.axelspringer.ideas.team.mood.moods.entity.Team; import de.axelspringer.ideas.team.mood.util.SymetricEncryption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.ModelAndView; import spark.template.handlebars.HandlebarsTemplateEngine; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentSkipListSet; import static spark.Spark.get; public class TeamMoodController { private final static Logger LOG = LoggerFactory.getLogger(TeamMoodApplication.class); private TeamMoodProperties teamMoodProperties = TeamMoodProperties.INSTANCE; private TeamMood teamMood = new TeamMood(); private MailSender mailSender = new MailSender(); public void initController() { LOG.info("Initializing controller."); HandlebarsTemplateEngine engine = new HandlebarsTemplateEngine(); get("/", (request, response) -> { return new ModelAndView(new HashMap(), "index.hbs"); }, engine); get("/week/:week", (request, response) -> { String currentWeek = request.params(":week"); LOG.info("Loading data for week '{}'.", currentWeek); validateCurrentWeek(currentWeek); TeamMoodWeek week = new TeamMoodWeek(currentWeek); MailContent emailContent = createMailContent(week); return new ModelAndView(emailContent, "email.hbs"); }, engine); get("/week/:week/send", (request, response) -> { String currentWeek = request.params(":week"); sendMailForWeek(teamMoodProperties.getEmailAddresses(), currentWeek); return "{}"; }); get("/week/:week/secret", (request, response) -> { String currentWeek = request.params(":week"); String url = request.scheme() + "://" + request.host() + "/week-by-secret-key/" + SymetricEncryption.encryptAndBase58(currentWeek); return "{ \"url\": \"" + url + "\" }"; }); get("/week-by-secret-key/:secret", (request, response) -> { String secret = request.params(":secret"); String currentWeek = SymetricEncryption.decryptAndBase58(secret); LOG.info("Loading data for week '{}'.", currentWeek); validateCurrentWeek(currentWeek); TeamMoodWeek week = new TeamMoodWeek(currentWeek); MailContent emailContent = createMailContent(week); return new ModelAndView(emailContent, "email.hbs"); }, engine); } private void sendMailForWeek(List<String> addresses, String currentWeek) throws IOException { LOG.info("Loading data for week '{}'.", currentWeek); validateCurrentWeek(currentWeek); TeamMoodWeek week = new TeamMoodWeek(currentWeek); MailContent emailContent = createMailContent(week); Template emailTemplate = new Handlebars().compile("templates/email"); String subject = "TeamMood for Ideas: KW" + week.weekNumber(); String htmlBody = emailTemplate.apply(emailContent); for (String mailAddress : addresses) { mailSender.send(mailAddress, subject, htmlBody); } } private MailContent createMailContent(TeamMoodWeek week) { MailContent emailContent = new MailContent(); emailContent.title = "TeamMood for Ideas: KW" + week.weekNumber(); emailContent.teams = new ConcurrentSkipListSet<>(); emailContent.start = week.start(); emailContent.end = week.end(); emailContent.weekNumber = "" + week.weekNumber(); teamMoodProperties.getTeamApiKeys().parallelStream().forEach((apiKey) -> { Team team = teamMood.loadTeamMoodForWeek(apiKey, week); emailContent.teams.add(team); }); return emailContent; } private void validateCurrentWeek(String currentWeek) { // TODO check if is number // TODO check if is at least this week } }
37.689076
143
0.673802
797b3d254bdfefc1ca83ecb0964779b5471d9842
15,410
/* * Copyright (c) 2022 Redlink GmbH. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.redlink.nlp.opennlp.pos.it; import io.redlink.nlp.model.pos.LexicalCategory; import io.redlink.nlp.model.pos.Pos; import io.redlink.nlp.model.pos.PosTag; import io.redlink.nlp.model.tag.TagSet; import io.redlink.nlp.opennlp.pos.OpenNlpLanguageModel; import org.springframework.stereotype.Service; import static java.util.Locale.ITALIAN; /** * Implementation of Italian-specific tools for natural language processing. * * @author [email protected] */ @Service public class LanguageItalian extends OpenNlpLanguageModel { //TODO: add Italien PosTag set /** * Mappings for the the <a href="http://medialab.di.unipi.it/wiki/Tanl_POS_Tagset">Tanl Tagset</a> for Italian */ public static final TagSet<PosTag> ITALIAN_TANL = new TagSet<PosTag>("Tanl Italian", "it"); static { ITALIAN_TANL.addTag(new PosTag("A", LexicalCategory.Adjective)); //adjective ITALIAN_TANL.addTag(new PosTag("An", LexicalCategory.Adjective)); //underspecified adjective ITALIAN_TANL.addTag(new PosTag("Ap", LexicalCategory.Adjective, Pos.PluralQuantifier)); //plural adjective ITALIAN_TANL.addTag(new PosTag("As", LexicalCategory.Adjective, Pos.SingularQuantifier)); //singular adjective ITALIAN_TANL.addTag(new PosTag("AP", Pos.PossessiveAdjective)); //possessive adjective ITALIAN_TANL.addTag(new PosTag("APn", Pos.PossessiveAdjective)); //underspecified possessive adjective ITALIAN_TANL.addTag(new PosTag("APs", Pos.PossessiveAdjective, Pos.SingularQuantifier)); //singular possessive adjective ITALIAN_TANL.addTag(new PosTag("APp", Pos.PossessiveAdjective, Pos.PluralQuantifier)); //plural possessive adjective ITALIAN_TANL.addTag(new PosTag("B", LexicalCategory.Adverb)); //adverb ITALIAN_TANL.addTag(new PosTag("BN", Pos.NegativeAdverb)); //negation adverb ITALIAN_TANL.addTag(new PosTag("C", LexicalCategory.Conjuction)); //conjunction ITALIAN_TANL.addTag(new PosTag("CC", Pos.CoordinatingConjunction)); //coordinate conjunction ITALIAN_TANL.addTag(new PosTag("CS", Pos.SubordinatingConjunction)); //subordinate conjunction ITALIAN_TANL.addTag(new PosTag("D", Pos.Determiner)); //determiner ITALIAN_TANL.addTag(new PosTag("DD", Pos.DemonstrativeDeterminer)); //demonstrative determiner ITALIAN_TANL.addTag(new PosTag("DE", Pos.ExclamatoryDeterminer)); //exclamative determiner ITALIAN_TANL.addTag(new PosTag("DI", Pos.IndefiniteDeterminer)); //indefinite determiner ITALIAN_TANL.addTag(new PosTag("DQ", Pos.InterrogativeDeterminer)); //interrogative determiner ITALIAN_TANL.addTag(new PosTag("DR", Pos.RelativeDeterminer)); //relative determiner ITALIAN_TANL.addTag(new PosTag("E", Pos.Preposition)); //preposition ITALIAN_TANL.addTag(new PosTag("EA", Pos.FusedPrepArt)); //articulated preposition ITALIAN_TANL.addTag(new PosTag("F", LexicalCategory.Punctuation)); //punctuation ITALIAN_TANL.addTag(new PosTag("FB", Pos.ParentheticalPunctuation)); //balanced punctuation ITALIAN_TANL.addTag(new PosTag("FC", Pos.MainPunctuation)); //clause boundary punctuation ITALIAN_TANL.addTag(new PosTag("FF", Pos.Comma)); //comma ITALIAN_TANL.addTag(new PosTag("FS", Pos.SentenceFinalPunctuation)); //sentence boundary punctuation ITALIAN_TANL.addTag(new PosTag("I", Pos.Interjection)); //interjection ITALIAN_TANL.addTag(new PosTag("N", Pos.CardinalNumber)); //cardinal number ITALIAN_TANL.addTag(new PosTag("NO", Pos.OrdinalNumber)); //ordinal number ITALIAN_TANL.addTag(new PosTag("NOn", Pos.OrdinalNumber)); //underspecified ordinal number ITALIAN_TANL.addTag(new PosTag("NOs", Pos.OrdinalNumber, Pos.SingularQuantifier)); //ordinal number ITALIAN_TANL.addTag(new PosTag("NOp", Pos.OrdinalNumber, Pos.PluralQuantifier)); //ordinal number ITALIAN_TANL.addTag(new PosTag("P", Pos.Pronoun)); //pronoun ITALIAN_TANL.addTag(new PosTag("PC", Pos.Pronoun)); //clitic pronoun TODO: clitic is missing ITALIAN_TANL.addTag(new PosTag("PD", Pos.DemonstrativePronoun)); //demonstrative pronoun ITALIAN_TANL.addTag(new PosTag("PE", Pos.PersonalPronoun)); //personal pronoun ITALIAN_TANL.addTag(new PosTag("PI", Pos.IndefinitePronoun)); //indefinite pronoun ITALIAN_TANL.addTag(new PosTag("PP", Pos.PossessivePronoun)); //possessive pronoun ITALIAN_TANL.addTag(new PosTag("PQ", Pos.InterrogativePronoun)); //interrogative pronoun ITALIAN_TANL.addTag(new PosTag("PR", Pos.RelativePronoun)); //relative pronoun ITALIAN_TANL.addTag(new PosTag("R", Pos.Article)); //article ITALIAN_TANL.addTag(new PosTag("RD", Pos.DefiniteArticle)); //determinative article TODO: determinative ~ definite?? ITALIAN_TANL.addTag(new PosTag("RI", Pos.IndefiniteArticle)); //indeterminative article ITALIAN_TANL.addTag(new PosTag("S", Pos.CommonNoun)); //common noun ITALIAN_TANL.addTag(new PosTag("Sn", LexicalCategory.Noun)); //underspecified noun ITALIAN_TANL.addTag(new PosTag("Ss", LexicalCategory.Noun, Pos.SingularQuantifier)); //singular noun ITALIAN_TANL.addTag(new PosTag("Sp", LexicalCategory.Noun, Pos.PluralQuantifier)); //plural noun ITALIAN_TANL.addTag(new PosTag("SA", Pos.Abbreviation)); //abbreviation ITALIAN_TANL.addTag(new PosTag("SP", Pos.ProperNoun)); //proper noun ITALIAN_TANL.addTag(new PosTag("SW", Pos.ProperNoun, Pos.Foreign)); //foreign name ITALIAN_TANL.addTag(new PosTag("SWn", Pos.ProperNoun, Pos.Foreign)); //underspecified foreign name ITALIAN_TANL.addTag(new PosTag("SWs", Pos.ProperNoun, Pos.Foreign, Pos.SingularQuantifier)); //underspecified foreign name singular ITALIAN_TANL.addTag(new PosTag("SWp", Pos.ProperNoun, Pos.Foreign, Pos.PluralQuantifier)); //underspecified foreign name plural ITALIAN_TANL.addTag(new PosTag("T", Pos.Determiner)); //predeterminer ITALIAN_TANL.addTag(new PosTag("V", LexicalCategory.Verb)); //verb ITALIAN_TANL.addTag(new PosTag("Vip", Pos.MainVerb, Pos.IndicativeVerb, Pos.PresentParticiple)); //main verb indicative present ITALIAN_TANL.addTag(new PosTag("Vip3", Pos.MainVerb, Pos.IndicativeVerb, Pos.PresentParticiple)); //main verb indicative present 3rd person ITALIAN_TANL.addTag(new PosTag("Vii", Pos.MainVerb, Pos.IndicativeVerb)); //main verb indicative imperfect ITALIAN_TANL.addTag(new PosTag("Vii3", Pos.MainVerb, Pos.IndicativeVerb)); //main verb indicative imperfect 3rd person ITALIAN_TANL.addTag(new PosTag("Vis", Pos.MainVerb, Pos.IndicativeVerb, Pos.PastParticiple)); //main verb indicative past ITALIAN_TANL.addTag(new PosTag("Vis3", Pos.MainVerb, Pos.IndicativeVerb, Pos.PastParticiple)); //main verb indicative past 3rd person ITALIAN_TANL.addTag(new PosTag("Vif", Pos.MainVerb, Pos.IndicativeVerb, Pos.FutureParticle)); //main verb indicative future ITALIAN_TANL.addTag(new PosTag("Vif3", Pos.MainVerb, Pos.IndicativeVerb, Pos.FutureParticle)); //main verb indicative future 3rd person ITALIAN_TANL.addTag(new PosTag("Vm", Pos.MainVerb, Pos.ImperativeVerb)); //main verb imperative ITALIAN_TANL.addTag(new PosTag("Vm3", Pos.MainVerb, Pos.ImperativeVerb)); //main verb imperative 3rd person ITALIAN_TANL.addTag(new PosTag("Vcp", LexicalCategory.Conjuction, Pos.MainVerb, Pos.PresentParticiple)); //main verb conjunctive present ITALIAN_TANL.addTag(new PosTag("Vcp3", LexicalCategory.Conjuction, Pos.MainVerb, Pos.PresentParticiple)); //main verb conjunctive present 3rd person ITALIAN_TANL.addTag(new PosTag("Vci", LexicalCategory.Conjuction, Pos.MainVerb)); //main verb conjunctive imperfect ITALIAN_TANL.addTag(new PosTag("Vci3", LexicalCategory.Conjuction, Pos.MainVerb)); //main verb conjunctive imperfect, 3rd person ITALIAN_TANL.addTag(new PosTag("Vd", Pos.MainVerb, Pos.ConditionalVerb)); //main verb conditional ITALIAN_TANL.addTag(new PosTag("Vdp", Pos.MainVerb, Pos.ConditionalVerb, Pos.PresentParticiple)); //main verb conditional present, other than 3rd person ITALIAN_TANL.addTag(new PosTag("Vdp3", Pos.MainVerb, Pos.ConditionalVerb, Pos.PresentParticiple)); //main verb conditional present 3rd person ITALIAN_TANL.addTag(new PosTag("Vf", Pos.MainVerb, Pos.InfinitiveParticle)); //main verb infinite ITALIAN_TANL.addTag(new PosTag("Vg", Pos.MainVerb, Pos.Gerund)); //main verb gerundive ITALIAN_TANL.addTag(new PosTag("Vp", Pos.MainVerb, Pos.Participle)); //main verb participle ITALIAN_TANL.addTag(new PosTag("Vpp", Pos.MainVerb, Pos.PresentParticiple)); //main verb participle present ITALIAN_TANL.addTag(new PosTag("Vps", Pos.MainVerb, Pos.PastParticiple)); //main verb participle past ITALIAN_TANL.addTag(new PosTag("VAip", Pos.AuxiliaryVerb, Pos.IndicativeVerb, Pos.PresentParticiple)); //auxiliary verb indicative present ITALIAN_TANL.addTag(new PosTag("VAip3", Pos.AuxiliaryVerb, Pos.IndicativeVerb, Pos.PresentParticiple)); //auxiliary verb indicative present 3rd perso ITALIAN_TANL.addTag(new PosTag("VAii", Pos.AuxiliaryVerb, Pos.IndicativeVerb)); //auxiliary verb indicative imperfect ITALIAN_TANL.addTag(new PosTag("VAii3", Pos.AuxiliaryVerb, Pos.IndicativeVerb)); //auxiliary verb indicative imperfect 3rd person ITALIAN_TANL.addTag(new PosTag("VAis", Pos.AuxiliaryVerb, Pos.IndicativeVerb, Pos.PastParticiple)); //auxiliary verb indicative past ITALIAN_TANL.addTag(new PosTag("VAis3", Pos.AuxiliaryVerb, Pos.IndicativeVerb, Pos.PastParticiple)); //auxiliary verb indicative past 3rd person ITALIAN_TANL.addTag(new PosTag("VAif", Pos.AuxiliaryVerb, Pos.IndicativeVerb, Pos.FutureParticle)); //auxiliary verb indicative future ITALIAN_TANL.addTag(new PosTag("VAif3", Pos.AuxiliaryVerb, Pos.IndicativeVerb, Pos.FutureParticle)); //auxiliary verb indicative future 3rd person ITALIAN_TANL.addTag(new PosTag("VAm", Pos.AuxiliaryVerb, Pos.ImperativeVerb)); //auxiliary verb imperative ITALIAN_TANL.addTag(new PosTag("VAcp", LexicalCategory.Conjuction, Pos.AuxiliaryVerb, Pos.PresentParticiple)); //auxiliary verb conjunctive present ITALIAN_TANL.addTag(new PosTag("VAcp3", LexicalCategory.Conjuction, Pos.AuxiliaryVerb, Pos.PresentParticiple)); //auxiliary verb conjunctive present 3rd person ITALIAN_TANL.addTag(new PosTag("VAci", LexicalCategory.Conjuction, Pos.AuxiliaryVerb)); //auxiliary verb conjunctive imperfect ITALIAN_TANL.addTag(new PosTag("VAci3", LexicalCategory.Conjuction, Pos.AuxiliaryVerb)); //auxiliary verb conjunctive imperfect 3rd person ITALIAN_TANL.addTag(new PosTag("VAd", Pos.AuxiliaryVerb, Pos.PresentParticiple)); //auxiliary verb conditional ITALIAN_TANL.addTag(new PosTag("VAdp", Pos.AuxiliaryVerb, Pos.PresentParticiple, Pos.ConditionalParticiple)); //auxiliary verb conditional present, other than 3rd person ITALIAN_TANL.addTag(new PosTag("VAdp3", Pos.AuxiliaryVerb, Pos.PresentParticiple, Pos.ConditionalParticiple)); //auxiliary verb conditional present 3rd person ITALIAN_TANL.addTag(new PosTag("VAf", Pos.AuxiliaryVerb, Pos.InfinitiveParticle)); //auxiliary verb infinite ITALIAN_TANL.addTag(new PosTag("VAg", Pos.AuxiliaryVerb, Pos.Gerund)); //main verb gerundive ITALIAN_TANL.addTag(new PosTag("VAp", Pos.AuxiliaryVerb, Pos.Participle)); //main verb gerundive ITALIAN_TANL.addTag(new PosTag("VApp", Pos.AuxiliaryVerb, Pos.PresentParticiple)); //auxiliary verb participle present ITALIAN_TANL.addTag(new PosTag("VAps", Pos.AuxiliaryVerb, Pos.PastParticiple)); //auxiliary verb participle past ITALIAN_TANL.addTag(new PosTag("VMip", Pos.ModalVerb, Pos.IndicativeVerb, Pos.PresentParticiple)); //modal verb indicative present ITALIAN_TANL.addTag(new PosTag("VMip3", Pos.ModalVerb, Pos.IndicativeVerb, Pos.PresentParticiple)); //modal verb indicative present 3rd person ITALIAN_TANL.addTag(new PosTag("VMii", Pos.ModalVerb, Pos.IndicativeVerb)); //modal verb indicative imperfect ITALIAN_TANL.addTag(new PosTag("VMii3", Pos.ModalVerb, Pos.IndicativeVerb)); //modal verb indicative imperfect 3rd person ITALIAN_TANL.addTag(new PosTag("VMis", Pos.ModalVerb, Pos.IndicativeVerb, Pos.PastParticiple)); //modal verb indicative past ITALIAN_TANL.addTag(new PosTag("VMis3", Pos.ModalVerb, Pos.IndicativeVerb, Pos.PastParticiple)); //modal verb indicative past 3rd person ITALIAN_TANL.addTag(new PosTag("VMif", Pos.ModalVerb, Pos.IndicativeVerb, Pos.FutureParticle)); //modal verb indicative future ITALIAN_TANL.addTag(new PosTag("VMif3", Pos.ModalVerb, Pos.IndicativeVerb, Pos.FutureParticle)); //modal verb indicative future 3rd person ITALIAN_TANL.addTag(new PosTag("VMm", Pos.ModalVerb)); //modal verb imperative ITALIAN_TANL.addTag(new PosTag("VMcp", LexicalCategory.Conjuction, Pos.ModalVerb, Pos.PresentParticiple)); //modal verb conjunctive present ITALIAN_TANL.addTag(new PosTag("VMcp3", LexicalCategory.Conjuction, Pos.ModalVerb, Pos.PresentParticiple)); //modal verb conjunctive present 3rd person ITALIAN_TANL.addTag(new PosTag("VMci", LexicalCategory.Conjuction, Pos.ModalVerb)); //modal verb conjunctive imperfect ITALIAN_TANL.addTag(new PosTag("VMci3", LexicalCategory.Conjuction, Pos.ModalVerb)); //modal verb conjunctive imperfect 3rd person ITALIAN_TANL.addTag(new PosTag("VMd", Pos.ModalVerb, Pos.ConditionalVerb)); //modal verb conditional ITALIAN_TANL.addTag(new PosTag("VMdp", Pos.ModalVerb, Pos.ConditionalVerb, Pos.PresentParticiple)); //modal verb conditional present, other than 3rd person ITALIAN_TANL.addTag(new PosTag("VMdp3", Pos.ModalVerb, Pos.ConditionalVerb, Pos.PresentParticiple)); //modal verb conditional present, 3rd person ITALIAN_TANL.addTag(new PosTag("VMf", Pos.ModalVerb, Pos.InfinitiveParticle)); //modal verb infinite ITALIAN_TANL.addTag(new PosTag("VMg", Pos.ModalVerb, Pos.Gerund)); //modal verb gerundive ITALIAN_TANL.addTag(new PosTag("VMp", Pos.ModalVerb, Pos.Participle)); //modal verb participle ITALIAN_TANL.addTag(new PosTag("VMpp", Pos.ModalVerb, Pos.Participle, Pos.PresentParticiple)); //modal verb participle present ITALIAN_TANL.addTag(new PosTag("VMps", Pos.ModalVerb, Pos.Participle, Pos.PastParticiple)); //modal verb participle past ITALIAN_TANL.addTag(new PosTag("X", LexicalCategory.Residual)); //residual class } } public LanguageItalian() { super(ITALIAN, ITALIAN_TANL, "it-sent.bin", "it-token.bin", "it-pos-maxent.bin"); } }
90.647059
177
0.744322
7a5953a4bc2e1327395e21d90c13b82035a4ed8a
349
package io.github.techdweebgaming.modularjda.api.commands.converters; public class BooleanConverter implements IConverter<Boolean> { @Override public Boolean fromString(String string) { return string.equalsIgnoreCase("true") || string.equalsIgnoreCase("t") || string.equalsIgnoreCase("yes") || string.equalsIgnoreCase("y"); } }
38.777778
145
0.747851
72b707ae28048b296bd8db310a0a380d69f5c2a5
317
package com.damienfremont.blog; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; public class MyApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> s = new HashSet<Class<?>>(); s.add(StatusService.class); return s; } }
21.133333
48
0.700315
0c83aa912845fb12288ad9b9a249fef456920696
7,182
public class BinarySearchTree implements TreeTAD<Integer> { private Node<Integer> root; public BinarySearchTree() { this.root = null; } @Override public Node<Integer> find(Integer obj) { if (root == null) { return null; } else { Node<Integer> aux = root; while (aux != null && aux.getValue() != obj) { if (obj < aux.getValue()) { aux = aux.getLeftSon(); } else { aux = aux.getRightSon(); } } return aux; } } @Override public Node<Integer> recursiveFind(Integer obj) { return this.recursiveFind(root, obj); } private Node<Integer> recursiveFind(Node<Integer> tree, Integer obj) { if (tree == null) return null; if (obj == tree.getValue()) return tree; if (obj > tree.getValue()) { return recursiveFind(tree.getRightSon(), obj); } else { return recursiveFind(tree.getLeftSon(), obj); } } @Override public Node<Integer> min() { Node<Integer> minNode = root; Node<Integer> aux = root; while (aux != null) { minNode = aux; aux = aux.getLeftSon(); } return minNode; } @Override public Node<Integer> min(Node<Integer> obj) { obj = find(obj.getValue()); if (obj == null) return null; while (obj.getLeftSon() != null) obj = obj.getLeftSon(); return obj; } @Override public Node<Integer> recursiveMin(Node<Integer> obj) { Node<Integer> aux = find(obj.getValue()); return recursiveMinimum(aux); } private Node<Integer> recursiveMinimum(Node<Integer> node) { if (node.getLeftSon() != null) node = recursiveMinimum(node.getLeftSon()); return node; } @Override public Node<Integer> next(Node<Integer> obj) { obj = find(obj.getValue()); if (obj == null) { return null; } else if (obj.getRightSon() != null) { return min(obj.getRightSon()); } else { Node<Integer> p = obj.getFather(); while (p != null && obj == p.getRightSon()) { obj = p; p = p.getFather(); } return p; } } @Override public void add(Integer obj) { Node<Integer> node = new Node<>(obj); if (root == null) { root = node; } else { Node<Integer> aux = root; Node<Integer> father = null; while (aux != null && aux.getValue() != node.getValue()) { father = aux; if (aux.getValue() > node.getValue()) { aux = aux.getLeftSon(); } else { aux = aux.getRightSon(); } } node.setFather(father); if (father.getValue() > node.getValue()) { father.setLeftSon(node); } else if (father.getValue() < node.getValue()) { father.setRightSon(node); } else { father.setValue(node.getValue()); // se os valores forem igual ele não add } } } @Override public void recursiveAdd(Integer obj) { Node<Integer> node = new Node<>(obj); if (root == null) { root = node; } else { this.recursiveAdd(root, node); } } private void recursiveAdd(Node<Integer> subTree, Node<Integer> node) { if (subTree.getValue() < node.getValue()) { if (subTree.getRightSon() == null) { subTree.setRightSon(node); node.setFather(subTree); } else { this.recursiveAdd(subTree.getRightSon(), node); } } else if (subTree.getValue() > node.getValue()) { if (subTree.getLeftSon() == null) { subTree.setLeftSon(node); node.setFather(subTree); } else { this.recursiveAdd(subTree.getLeftSon(), node); } } else { subTree.setValue(node.getValue()); } } @Override public void remove(Integer obj) { this.remove(root, obj); } private Node<Integer> remove(Node<Integer> node, Integer obj) { if (node == null) return null; else if (obj < node.getValue()) node.setLeftSon(remove(node.getLeftSon(), obj)); else if (obj > node.getValue()) node.setRightSon(remove(node.getRightSon(), obj)); else{ if (node.getLeftSon() == null && node.getRightSon() == null) { node.setValue(null); node = null; } else if (node.getLeftSon() == null) { Node<Integer> aux = node; node = node.getRightSon(); node.setFather(aux.getFather()); aux = null; } else if (node.getRightSon() == null) { Node<Integer> aux = node; node = node.getLeftSon(); node.setFather(aux.getFather()); aux = null; } else { Node<Integer> sucessor = node.getRightSon(); while (sucessor.getLeftSon() != null) { sucessor = sucessor.getLeftSon(); } node.setValue(sucessor.getValue()); sucessor.setValue(obj); if (sucessor.getFather().getLeftSon() == sucessor) sucessor.getFather().setLeftSon(sucessor.getRightSon()); else sucessor.getFather().setRightSon(sucessor.getRightSon()); if (sucessor.getRightSon() != null) sucessor.getRightSon().setFather(sucessor.getFather()); sucessor = null; } } return node; } @Override public String preOrderPrint() { preOrderPrint(root); return ""; } private void preOrderPrint(Node<Integer> root) { if (root == null) return; System.out.printf("%d ", root.getValue()); preOrderPrint(root.getLeftSon()); preOrderPrint(root.getRightSon()); } @Override public String posOrderPrint() { posOrderPrint(root); return ""; } private void posOrderPrint(Node<Integer> root) { if (root == null) return; posOrderPrint(root.getLeftSon()); posOrderPrint(root.getRightSon()); System.out.printf("%d ", root.getValue()); } @Override public String inOrderPrint() { inOrderPrint(root); return ""; } private void inOrderPrint(Node<Integer> root) { if (root == null) return; this.inOrderPrint(root.getLeftSon()); System.out.printf("%d ", root.getValue()); this.inOrderPrint(root.getRightSon()); } }
26.116364
90
0.491785
a6a9f41381565e7a28d87948f8cbe2a41039fb9d
1,031
package vangiaurecca.example.model; public class SinhVien { private int ma; private String ten; private double diemTB; private XepLoai loai; public int getMa() { return ma; } public void setMa(int ma) { this.ma = ma; } public String getTen() { return ten; } public void setTen(String ten) { this.ten = ten; } public double getDiemTB() { return diemTB; } public void setDiemTB(double diemTB) { this.diemTB = diemTB; } public XepLoai getLoai() { if(this.diemTB >= 8){ loai=XepLoai.Gioi; } else if(this.diemTB >= 6.5){ loai=XepLoai.Kha; } else if(this.diemTB >= 5){ loai=XepLoai.TrungBinh; } else{ loai=XepLoai.Yeu; } return loai; } public SinhVien(int ma, String ten, double diemTB) { super(); this.ma = ma; this.ten = ten; this.diemTB = diemTB; this.loai = getLoai(); } @Override public String toString() { // TODO Auto-generated method stub return this.ma + "\t" + this.ten + "\t" + this.diemTB + "\t" + this.loai.deScription(); } }
17.775862
53
0.632396
33a69b8a91dd778c7035c1853c16fd8ce28cffd1
1,538
package mage.cards.s; import java.util.UUID; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.effects.Effect; import mage.abilities.effects.common.ReturnToHandTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import static mage.filter.StaticFilters.FILTER_CONTROLLED_CREATURE_SHORT_TEXT; import mage.filter.common.FilterControlledCreaturePermanent; import mage.target.common.TargetControlledCreaturePermanent; /** * * @author emerald000 */ public final class Scapegoat extends CardImpl { public Scapegoat(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{W}"); // As an additional cost to cast Scapegoat, sacrifice a creature. this.getSpellAbility().addCost(new SacrificeTargetCost(new TargetControlledCreaturePermanent(FILTER_CONTROLLED_CREATURE_SHORT_TEXT))); // Return any number of target creatures you control to their owner's hand. Effect effect = new ReturnToHandTargetEffect(); effect.setText("Return any number of target creatures you control to their owner's hand"); this.getSpellAbility().addEffect(effect); this.getSpellAbility().addTarget(new TargetControlledCreaturePermanent(0, Integer.MAX_VALUE, new FilterControlledCreaturePermanent(), false)); } public Scapegoat(final Scapegoat card) { super(card); } @Override public Scapegoat copy() { return new Scapegoat(this); } }
35.767442
150
0.757477
6d7695008e90ebc2199da7d18e4b9e117707125d
1,438
/* * Copyright(c) 2016-2017 IBM, Red Hat, 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. */ package io.microprofile.showcase.bootstrap; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; /** * @author Heiko Braun * @since 15/09/16 */ @ApplicationScoped public class BootstrapDataProducer { @Produces public BootstrapData load() { final URL resource = Thread.currentThread().getContextClassLoader().getResource("schedule.json"); assert resource !=null : "Failed to load 'schedule.json'"; final Parser parser = new Parser(); final BootstrapData data = parser.parse(resource); Logger.getLogger(BootstrapData.class.getName()).log(Level.INFO, "Schedule contains "+data.getSessions().size() + " sessions"); return data; } }
31.26087
134
0.722531
cb56410c2e8d4c44b295af68575763ff56f372cf
30,399
class A { public static void uqc_q1 (String[] uznayLkM) { ; return; boolean D = !-new RgxKOS6_LBRg[ new void[ V8O2h_6RTyO()[ false.Wh()]].VJGPHzQm0t9Zw()].Kmy5jidzipG() = !369557521.gi3KlRt; boolean[][][] LaH; boolean[][] HLWUNxkYxyg1 = !new boolean[ -new boolean[ this.S][ Aw().eeHkk()]][ !!null[ Hk.J4EAqZbNg8Wb]] = -new int[ -new wO_fPv5bS[ n().j3HMH][ !-( false.Ab2sN3kcyn())[ sFrBoS.K()]]].OipFkFTRW8g(); void[] Lxm6JluYK3SXsR = -new f().k81bBPnVamk0_N; boolean tUzakj = new lQbc_vnuvv().tKJZHd5() = -yPCJJ().CbupupuD9; boolean[][] UAHB_RB; ; rlnyNrfQtsaaG[][] m1Ymb7407 = new TNIrb()[ 7.wy_Uto37cU] = --new int[ !403577.D].uyi5F1i; { if ( -!false.sBA) false.yx8Wl5WHL(); return; int Tyz1LNqm7RfS; _Z0 rAWr; { boolean[][][] r7kHYDD; } Fzx4[][][][] mN; { void QUktzXS8rlu_; } int dsVwv0CESHr; ; new NA6eixGbRc()[ -694.Y4S0P2P9Sy()]; { int[][][][] VoWnr2NqYna; } -this[ !TgG7Tix_QlVK.Du]; while ( -!r.Vl2qAF5UDIX()) while ( true[ -this.DjLKpzt6()]) ; } void AXl7fgZ5inMC = --new ZWsRKob().equ = ( this[ -!!true.XRcgPsMjhg()])[ true.px]; } public static void iMmTZSX0 (String[] AIN3FsCfXVUC) { cQIWe2WBgG1EVn uQA52ax97Y; return new void[ null.cJUkap_93].O; int xr9Km; if ( 34.jAJpMkZtCLZJ9()) while ( -( -null.rBVTQSIa5t_()).q6iRm8()) { int[] RGugBy; } zu0FJ0zOLUSuh AuP6va = _r.D3(); int[] WP; ; return !!false[ null.IyVObiH9sdsbHF()]; while ( new oh8jANmshaT().B4oFQqx3T7p) { int[][] Q5SzRFtEAfLgo; } boolean Ey4qtLN = r.WZ() = TGSDP0BV7pCix.YG1WK; jlht3QGPz cDq; boolean[] PhdSbksxG4BZ; if ( false.OSfg9Eo24C()) ;else return; void h1pk2; boolean W5mKGeLup6eyk; return ( !!new M7sMzW[ !!649130472.Fde].D8XqrFuJru3()).EDssb; void rMJ = !ekS1mQ().g4KJJf7flOTq(); } public int[][][][] AJ9z (ynimnB[][] igk3phKP, void MiZ81K9GneWVEY, void I, void[] kmgqzUyq_Nfo, boolean[] dK_zmOEZy) { { void jNx; BtQvkUvZsxQbQP HbKvffU; D[] _; boolean ToQqCS2htc2zth; if ( --!null[ KtpLruURMh.tOGzEUU()]) return; EetrROq()[ new boolean[ -627000241.Zj7cIGWoI6].Ahc7_rNkzPK()]; boolean[][] XkN; ; ---new oThaM4cF1x8().nxLER_C; { void[][][][][][][] VwAkN1pORJn7; } int[] Ox3RxjLIIv; new f2jCa8NuEY1y().qgU5i(); int NdbaiqeTi; if ( fb0().gU) ; boolean[] Uxzld5Sw0T; void[] U; QY5w2k5Gg BNSwRU; !-!s().z7RtARu7OsHM(); } boolean[][][][][] JEXjS3fM2D; -new int[ new arby7vdH2iq().fDkN0QVQXn()][ true[ 25257.KjZp()]]; void _; ; return this.jNF; v4UhyLs6wGL46B[][][] VSLYUNp_ARRTd = true[ rvUR5wwviGkv9D.wCbgX4A()] = nZpNZGqK5Vqq().PpC_P; { NPPLEQZerjWLt[][][][] e; -inB9p68f8ITG0c[ ( !fCezqQ3qZt5g5().iQGJvGHkzjfY())[ ( null.wm).PZoeZhjF]]; } gc()[ !!!true[ this.VSY20uylSL]]; false[ !!-!!new Cxzu07d9p()[ this[ this.TAiQlrBApoSCQ]]]; while ( KAVyLQY[ -!!this[ !!( -!false.JFvvEMFln).G_AhJjNPMca()]]) { ARNHAXh HAwyKmy; } void TbQm8HqbB; void[] niY0P; int COPVY = null[ -null.tNNB5mf()] = -null.MC; boolean[] Hj9ZkBCHblycw1; int[] w = 557164278[ false.SC_gowy()]; boolean ZooPBzm = !-!true.HIBVLyFfTJnh() = !!this.NXArrYVa_ituCU; if ( --!( --null.hFO9KoAZIPLMpo()).b) ( new boolean[ false.Aa0drIMHUeX4()][ sg3.Ju1WIfu3sO1JyG])[ this.V1B3xN]; void[] K6kRx8oBL = new OWCfNC().yhzZlzG3XSK5 = !-!70397.Y(); } public boolean LJ3f5CJVosRL () { !new void[ !-!vKyAHRKXSjwn.HUB7EvULoULc].e6txe; VhY0mBaa9PI2Gg[][] dzGyPS = ZmJz_lulJAFJdb[ -sD9Jc[ -( !---null[ !!new boolean[ this.UZ2mfmOqo][ --this.JqtIZbXJt()]]).iDdF()]]; int[] r5TKYHe1BjiEik; void qJssytonGu9WK = !null[ new UY()[ ( -!true.BI).lHnvLU()]] = -30796829.PzO; jo9iZ9v4lDOkME[][] yNgun_; !saeY5MIH4N.YF1LnI(); boolean[][][] NTJdC7Z = null.mbx4E1E = new EmdUi0NRKeWB0[ false[ -null.bnv]][ null[ ESi5u.oe()]]; int[][][] HLP; int zXGLqNMqZ = null.R8BwhLKckW8(); ; ; while ( -new void[ -false[ null.iVwD]].o7K32S30C) ; int XhEz; cHx LrNvIBsyJ = 2424.Y3DVc = -true.gsJJXd; int bqvD = new boolean[ fi4KOdsdskMH.kuZ6ppMzU6ZB()].oiXt3NfE(); { int INtPaps; { this[ this.rNEDnF]; } if ( !--A2ELX()[ !new void[ !this.R_6()].iEeAr()]) return; C113Qm9T nC6bHZGFeBGI; new zUUVvxb[ null[ true.i9JJKXMFS()]].PUl(); boolean yhsvpNLK9iiAqM; while ( !-true[ !rEk.mM()]) false.mMVv(); { ; } ; void da8HVr4BcZ; while ( !!false[ -true[ vk7_Ol6B[ !true[ new MOyEvJISV()[ 7[ new boolean[ new CAM().Hk0qz].iSAf()]]]]]]) ; boolean n88wNgCK4k; void yR; !true.IvPSioGTTRy(); int xg_NDCTqc8eWGx; void a8ZZbB_e; } return; { { int[] S; } { boolean v6iJ; } while ( -!this[ --null[ true.JWr7J5bmRsWjLx()]]) true.N3UT(); int YM_Tl; { int YtL0lfmb; } if ( !-( zLp()[ new c1().givQS()])[ this.aaH_xYVAvg_e]) if ( this.dp4NeSwZGZ()) { ; } while ( !!-!new boolean[ -vPFzluX()[ !-16233270[ this.i_bYisyfuz]]][ this[ !new NoKK4jCY5AX().rVusqZ]]) if ( !-!no6t.yqh()) while ( !!this[ -Rb.ObMmiD2UX]) if ( -!null[ new peu1Gbyv9v4vom[ new wKr3qS7C().jg_7y].Zu4EI()]) { boolean[][][] Vz93; } !OH[ ( true.GHF92)._c]; void agQT; ; Z3hP1zG().yOe1ljXB; return; ; while ( !-false[ !true.dcet()]) { { U[][] uz; } } ; } if ( -null.u3TnKx2_9Ji()) if ( ZOqvafCc[ -!!-!!---!this.oI9bZE1r2fN5es()]) while ( this[ new int[ this.cjAelIg()].Z4FqxJ()]) ; } public void secASigDP6L (int JnwTQo5AvZc, int OFzS6n12, boolean[] i6OPGLebSVa, void[] GJq) { WMj97siC_[] AhW = true.Y_Hstzhl = !CdlbwVJ8DY1()[ this.KT3X]; ExixNO30Xr3j daDn = !-( ae0jLNu6j().D39fv).GDXhC(); int b0HKFklnsRcxxJ = !!--( null.IplMq_wgxfm())[ this.TLLWOSNB()]; -!-!-!!!new mj[ -!vwn_kB8PDsPh[ new _z8_ppztmD().JUM]].lHDmWVQlrf09OR(); hRxzXI4vE ikE63T6txTNqN; while ( !( L_rD_V().KWfdMxB3uw()).XsA7b) return; void[] i0vQJVPHr0i; int wdc8; !275.y45G1fi5q; int[][][][] kPCeKf1nYDR; HlAuj0frc1.W0mb2_KySC(); -new qmMK9voG().Zsswk5(); int rCKh; int[][][][] FkZMc0KV5GmuAB = eUbEtXjDk.FlID2Fc = true.LNoy_HBHL18nV(); while ( aycqE[ !-!!new void[ -new void[ ( !false[ new void[ !!!!!!!( !!!!hG7DTs6Vn7O8H.xKG5W5j5)[ --250.OTbkdcKw7dqJ4a]].CPY])._VQbzYTB].wowclPpjf_5].rl]) { return; } if ( MclSwYZbepym.zCnOOCWcvK()) this.lYXs4YpOb1VSo();else new M().BEMO(); oW7hXw[][] tE; while ( !-false._ZuZ()) 99092553[ 802.pWcrObmDgPMz_]; ( -this.y6ZwIOmV).pHM3xN8; int ZAM8rx5ImE = -true.wcxtAOv6WK = new lv().Jx1Lr(); } public static void EtfBdM (String[] fwUu) { boolean[] dBUevzH_1LQ4bs = new vOz2otaBAtjE()[ true[ -!true.li()]]; boolean[][][][] n8mIp5150oh; boolean QyMkFphL; void[] z8; int YIkMSx51HzlSJ; !null[ new HFKsDE6A3uozE()[ pte1lhnNc2nKIZ().suA()]]; qFpilf fv1lHqb = new y698tBN2FmEkI().js80aLlLWs(); int qk = !ycjAku3dSIb.gwNby1vzYd6C = -!( -true.ZzMQ29B).nbu(); void[] l; } public static void YsJAVdR9T (String[] R6SlNqW4) throws Z8OQ2B6oDoSH { XRW7auvKRJ83L[][] VPwbvhX9Bj; int DcIbFI; { if ( ---true[ !null[ ( !new void[ !!!this[ new void[ -null.LWKoKJ3Yv3()].CFtyLvR()]].Jo)[ !null.lD]]]) if ( !OAZ.JSVEY()) if ( gjNQHCGrJazoDa().V_) return; while ( -( -( sOtfVR0().r()).uFf8_VI40()).riqyNhu5DG6c) ; void s; boolean[] sz; boolean kCOh1HQTh; return; boolean b; while ( !!new o_[ -true[ !!false.mhchnSNYZRsbWr]][ -( qp9B()[ -!true[ !-NNE()[ ( -!new c0_XiT6().ozv())[ new T2BHV7mB8S[ -!new xGTLj().aia5nuaMVXqtj()].YoU9QTNidrrEp()]]]])[ -false.kcLRHcfwwwALKF]]) if ( --null.oD()) while ( !Ut()[ new boolean[ !bl4OXlnEv().xsrTqift()].fSTX4_DyzBp]) while ( this.qTEu3j9dzv) return; while ( --this.xIPU6JhoE) { int Te; } return; if ( ( !new Hovl()[ !true[ ( false.kbXjPjDp6wE()).syoGGT3cyjM_()]]).K) if ( !EHa9.WeKq()) return; ; pTfn XJ7rEo; } boolean[][][] Pz5xj = !-D7P11s[ !-new OQ1SgJBc0tfJ().YKr8Ehx]; int d4NjMBqLwtis7O; return; boolean iS2MeOABR30zy = null[ -false[ -a9xLI0().qLxj()]] = !LPI().a9EGwwBIHrtj(); ; !!-new OhfBLvdkgqVdg3().W; void b; { O5VbVnsrvB z8aIW8Ig; { ciUNZrzcc VXTVJeqK; } while ( -new int[ !new boolean[ new NOI[ qpyb1P2BT()[ 638797561[ false[ !!new RCHPjc4[ this.zH0][ true.Pu6VBo8RY()]]]]].zs7iMe()][ !8206532.W8jQ4nO92u]].zXGlDSX7()) if ( gMhaII9IahU()[ null[ !new void[ true.B3()].RAs8CBLeKl]]) { { !false.JXXF(); } } boolean Ty1; M966_Jg[] Vmfe8; if ( this.vf_3oRKwc()) ; -!---!-!false[ -( !-( !vk2()[ !new int[ !--!--435836152[ ---null[ -!!!Vf6fiUftB[ XCOS2Mod6WP().tsKSsf72wm]]]][ !!--!9759502.JVThnQc()]]).WYZ()).xKRZDAqt]; void yhNgg; } return; return onSQ3a1().KkNaNAL9t; int hdg; int[][][][] kByJ = !this.at(); rrN CW2vnl; ; } public static void n2 (String[] OhwAyQYPR7Ur) { ; int[][][] pmHXW; void[][][][] E2rg3F = 7987[ ( -!( !VvL6.Xili4o()).frHAy9VltZ4C())[ ( !--ece.x4rRrYFfY5sa()).s_]]; int[] h; } public void[][] l () throws t08M { ; } public static void nxGtb (String[] e) throws cNW9VZoXf { { boolean KrqjNllf; while ( -!-dDqu3ymj().iX32_Vk1W7k889()) if ( this.jAIa3_Aj()) true[ !( this[ -!53[ -null.tlzi4BbcfUfn6()]]).Zx3ydCvMlZ()]; GdwdOmT5QXVy43 dhRI; } return this[ !!38316094[ !true.mk5lUgg]]; ; { !( true[ -!-URb().IAVx()]).RpP(); { SJ[] L64DCc; } boolean[][] tyB5qOBj8; if ( false[ this[ new boolean[ !!!this[ this[ 8.npN()]]]._shcaL7m()]]) { int RT322GpA4v; } int[][][] eVeZNABzXQtDx; void[][][] I31gdd; void[][][][] OHd3RX; zQ8TesqEl1Ig[][][] HY; return; r2N pDSJl; int aKYU; while ( !new L[ 30480[ -!-true.V_VMNhkz]][ true.lIo2tL]) if ( true.z1T8x8()) { void bwlrXuHqNml5; } { GNBx65()[ -( ( -new wv6plQNgn().GF04cV).yQIZmk()).U0dQFfgllGNC()]; } void ICkahkSBHmj; ; if ( this.Y8y2oac3()) ; bIhpsR4ua i3ilfF; int dZg; { int D9G; } if ( BRYrCii7lgv().JSpe3wPf) return; } void I6ciasN; void[] l4yiJx = -( 137[ !new void[ -----!249063221.whLNNcI].lWXr()]).HVvK3OrCliSMQ = !42419177.Maj6w(); { return; { ENfnUMKyOg7 lpAx; } !805084946.gXARa(); !g()[ false.GXfnGl0YdjA()]; } --this.umImAUgfed(); boolean i = 2658[ !!!!07.Lz67D] = -Z().D(); m9d9 bc7mBiOBC66ng = null.NYwtXX() = !false.C; int[] SD2; while ( this.FzRl1XFWboMX()) { while ( new int[ !TENvhsECQPvjnn.NjZQETalA9L].cuuYHdqBvoHY()) -!-new Ft8bIPTKw().cXZ; } int rFVL; { boolean[] QVeRhfhf; { void AGHp6uewiQbs; } while ( new VjWEgbESD95V()[ new void[ ( true.tVaw())[ RqPGQPWHiq7t().VoZ()]].tV()]) ; ( !!!-!-CrJ.IwOCh()).F7BOMPVBHhk; boolean[][] pI; boolean M3E; int[][] HSMAo; int[][] pRdK2_22Ar7f; ; void jBAAUhyva; ; -22647.ULFFo6Eupw5T(); return; if ( ( !!7095973[ !false.GDlVlfH96cnCh()]).RdUDe()) while ( ( UXbNtTIsZWc1e2[ true[ new int[ false[ -lHERHzq86h().qAD]][ IsfIH().jAN]]])[ -false.wCCyBEP]) while ( hpO_x().DwQoYiJ81mYVt) ; !!dPFw5[ !false[ new ph1X[ null[ t1oJnQSW().NEwQz()]].A6dZHNaGwt2]]; } void[] qQ5; ; int[][][] Ha9P5HjNbUn33g = -new boolean[ -Ao().ojXJ6_G][ false.DNNuXPuFB()] = !false[ D67yf[ ( !!null.UkRVf())[ new yX1aZJvSB6Jak().oH1gw]]]; } public static void sJakjPpWpj (String[] O) { !( !this.s8Ps())[ new SbdTYEL().a5WndUyQESCq()]; ; if ( RV9EZtIC.WDHSxtJaM8()) return;else --this[ false.zdkF3hzpxln()]; return !!( new r()[ this.OO0P])[ !!new fjP().z1o6o]; if ( -!!!-( -!92849[ null.xwrqAvuzCl]).RUC4Q2nRx()) while ( 586[ --710697[ !!false[ this.C]]]) while ( new NESxvYJr[ -!!!-( vaGFD().Cp()).gXxz2vxoCWsSV][ --!this.lL7_B3F0MyLE2()]) return; boolean HEhwvnmJAym = !true.PG_6; { AZSQr[] x06PapiBkhV; void[] ou_Jm; } int dBt = null[ iJgmF()[ --!49217[ --!-!w7bYEcC_9JUGRS.RE]]]; while ( -!!new pCoNo4_LTs6G().Do8()) if ( new void[ null.aNzs()].qANt0D4_zj()) return; } public bAagg0X9I[][][] N62RtLjT (rfG6pG MI9v6LRdCfvzN3, void[][] AtTy8) throws bBGhLfmcP4jf { int[] fKT = d().Lz4GC; if ( -!-!this.kB6GJJVRw) ;else { ; } boolean jqJvHsl = true.A4B() = !--sU()[ !-( -aOpbsZ.DuALrdbs4Qn).A95]; void zYkUxj = -!( -Wda2C4JAZ1vj.r7_JjfyJp7sXZG)[ false.qvhCVuUeIvMg()]; int[] V; boolean rdsY8WNcZK0s2u = ( !!( this[ !!0463.c()]).LPV16UScUb0ofo)._H76YGIQqIfZD_ = 7.qs2vSf52m(); void NJTWX6XU1c0M; boolean[] ARlI = true.ZgIrTu9V7O = !this[ -!-null[ --!!ZFnz9btnG[ -!--673.xuGSNvm]]]; { q1lBrfCGDNLzAc[] Z8v; int i5amm; int bCIUcihXTjrxHJ; while ( -43957429.GtffpI9qzIyZ()) -true.ppY2Mm5oHG8(); void[] dR; if ( !null.IJ4eUrNrr()) while ( null.d4B7b) if ( 2[ ( !new boolean[ -!-true[ -false.JO5GzIn5]].tprfKR_)[ !!new seMLT()[ !!-!null[ b1BJYZuh()[ !( false[ null.jQJ5()]).VhDjU()]]]]]) 2763010[ null.UIG7m()]; int lnaC; ZrgAcNj vd; { !!new void[ -( new W9()[ -!-true[ !( true[ false.opnNI2rNqsK]).F49bN]]).nNPbr].yWmt; } boolean[][] _2; INiDzY3UtmVmT3[][] n; boolean[][][] tPMXSh; if ( -fVx.lB()) if ( this.yRr2CPu3) if ( 72.o_aOzv) -!---true.zPhJNILE; while ( -!-!-new vw8BVnQxRa[ -DP4CC.O()].r) { boolean R9DUIgTiwz; } YBKzh_eatnzKN.Dl(); void Zv; int uQe; } 303823[ true.hakorCE8SnA()]; { boolean[] YjfuEmgaoi4; void EzvdCvlwdoGM2E; while ( new int[ !ABJP0czaRCn()[ null.lV()]].W7bQ5wH) { !!!!new k1().ZEJj; } ; { int a_ok2ckH; } while ( true.pW4sgR7EPhCh()) if ( !686081434[ !this.ufG()]) { void MXbn; } return; } } public static void cIkDrdQT (String[] ayOGV) throws j_ZhEp9A2 { ; void p1j5Ijw = -!( !WkeN.OY_fupsxH)[ !!-!!!new OzkU8H5RDQVPTm().mE] = ( W2cwYRidizHnQ()[ !!true.N()]).mJ3Rwk; ; { ; if ( 8989.jQGzTINFc7OptM()) -true.Xo(); boolean[] ygQ47; void[][][] GDtax5Stbru0KG; vFDjtgPRJH G79a0olC1; int H4NhUU; return; this.fRpPVYyI(); } boolean[][][][][] iYe9g4PHgBXSt6 = this[ false.zuWj()] = ( !new W4ied2urnrBmv().eEzlLa408FO()).kFc3Jy_KloV7; ffj[][][][][] c8EMijap = !M3u2LI2Yu().IWrilQif() = !true.Pxakc; boolean mA4 = true.rHi2LQCe(); while ( new eFe_GIcpV()[ 084945419[ !null[ -this.gvd3YmjUmUidSi()]]]) return; void MQVOKt; int[] w_lyb = new void[ new BymOaQWS4U0Ok().x7dO8hUlx][ 3880270.N_()] = --805106[ false[ !null[ this.pw8zbDHmlDenV()]]]; } } class on0S { } class ObFdpemYFNd2P0 { public static void wvYJlB2mjmNZ (String[] x) throws RQcvf3mQ { boolean[] kBAug6awIrzF; OVce6[] BygP = -g0QhMq1Sh2Bfb().v03wcsVpc = new dwO()[ !new BlfMeuwTG().jzqTQqI3WZP]; while ( null.iTAiPsV0) return; boolean MTo77jXiRe; return; return new hSuaNTr4lsIiJT().q(); } } class H1fOqPUZcI { public boolean XfAEfyq; public boolean dbPKVI2SCefHZD; public static void t0ISAwV9uk4 (String[] rcheGsosbgw) throws ISfVfCkIoe7WN { t AvP8Uwz6Spi; IFN UbFjZ73; } public boolean Kd0miXxmFGZqn (aM vXMJp06, DRRnW9FoUn[] lw6YIP, GmNx2l mdipnMMTUpiW, int mAhz76suQZBh) throws tK1ZC { int[][] K4tYf0QZG = null.q(); int pR82Ifpe706g = -null.B6UU551Vg4cs6f(); void P; void xqo4ey1J = kSSix1MPj6().sVVRt09hbPpF() = l9e5yuy()[ -!!-----!-new int[ new G2g4U3()[ false.PucfMALKyNPUe]].eoKBTAYSVn1w()]; boolean[][] cBXMRg1nT; !wS3wDpI0()[ !!nznTl8FUyD()[ null.__MtXX3VJ()]]; void k0JqEjfeL; Rqt[] oeFO5gP = ( -new PI8wbirnApm()[ this[ null.QgyWlS]]).WGj29Kk(); if ( ySyMId3b7uj().xNN) new void[ !!new boolean[ --this.Ea42KAgJu7G][ this.uLo4oskRA()]][ TY1bO78().UN]; } public static void x (String[] MtgdQ) throws Jh { pfOoYzMd[][] c_sf = 778.Xkjr4uzDlE(); int AB9a9Q4CQUorF6; void[][][] pUThpPlxLE; if ( -mWgX.l023) { return; }else while ( this.wpP96VJwqR7ZJ()) return; boolean xXO4YaQy85 = -!1281604.IX5Mo() = !true.D_0FUAciQwjsYo(); void[][] H2lI; int[] Q = Zg2zZljT_2J9x()[ --!40655236.Bg02L()]; int L5SVl = ( 6.aALqHpX())[ -!!( true[ -this.WJSuh()]).DKucf]; return; void[][][][][] oKdXqi = new rNxfrlhhvHXKTJ().fm7apnCc2; new int[ new fJPj6()[ --!null.o]].x; while ( --!null[ -new Z7O().on85U_O9tnb]) ; g.ExMkdzp; int[][] o5cX = !449498[ true.SGTq1K471c_m] = !this.dVTQ4BmPSAsmZp; xFMO3V_Hb6GLFJ[] HlFSqRiNw; int[] wKOUa8e2S5K5MZ; return p1HtvVeC1Ti()[ -!this[ ( !null[ false.CXeqUkaeLXIHi()]).gh0Jt7x]]; } public static void LT5 (String[] N) throws Zzu { while ( !!fSwY6vhIreeAw().jglNM7o()) ; h3t2oqG6Q[][][][][][][] i10b71r5; return; while ( !-!-false.t8bz()) if ( --new boolean[ !this[ !h_3SSqBlu0ja.GI04BRHa()]].hq) if ( -Zq0IHHkbnj.cDU()) return; -!false.cr9UF; kOAQ9bI QOAWeZl0; while ( !--this[ !-!!null[ !!024.WV_Dx3]]) return; } public n[][] UmmtWGOs48F () throws KTlg { { uuw8e4oSCNZ[] hMFr6dw_f; boolean AJl4EWnKVQsvEZ; void V; ns[][][][][] WHzLEXwL; return; return; return; } while ( !!null[ false.spvmN()]) return; return new EzmR7QzzN()[ !x[ !-!-!-( !!new int[ nCkL4vPDa_0()._MMrn0Ng4BK2][ -pI2.wAdfudtnGJGX])[ false[ !iU4gGn9FR().KUaWlDVPqhkEz()]]]]; while ( --!new BWHk().bx9ofgZ) { int[][] AzdZz; } while ( !DR.YUCGCe()) null[ null.fV3cvo95bl()]; } } class Kyqh7 { public int[][][] PSUX_9XpbEV; public static void jAz (String[] mUNvOf) { { boolean[][][][] O_ZJsZ; } LI[][][][] wDSlMH = ( this.OHjAhbx())[ JrLn[ new meIPn().iFdMTEh95lbx2p()]] = new GY5Db03Q69G3a[ bZ5v8Zx0WcWSW()[ !false.TWb1m5dN]][ -!!false.e5lBd]; void QJCM7 = ( -!new FRH().DOpYAGF3())[ -true.ryB4j5i7]; return; return; int MwRLb2n = new dhqU()[ EQqWSeDv().RfjiguU55CXw_5()] = -KVb8bmUrk3a()[ !this.vEVMiKNsvbJXi5]; if ( new z0K().qbUGxQYvhoniGk()) if ( yLSe2N()[ null.DpUL7LdR6Kj]) ; return null.sA1x4(); if ( -( new AiEP1yPrS().h0eQrE7GZAai())[ new kJevX2RtqRuR().ogB()]) { return; }else while ( G.Ii91lOF) { -8738499[ !!6[ null.sVZhh1fNHxfA()]]; } } public static void YERfTVMi6B (String[] JcpquRy2W) throws IR { boolean Wu; IAyqvc6xg51H[] uO5Wcn8Xxc; { boolean rLDF; if ( t8bpeRhWwIX.J_tgrjMS6C()) return; return; boolean YI41lCguSO; boolean[] d; void[] T8ldOG3nO_; { int GdFenc8W8X_M; } ibn2amG It; BjBnGw[][] J7zzmcHXq2l_U; boolean[][][][] suEB; } { boolean[] nBtn4Z7h; if ( !-( -true[ !!this.wF]).MOIOLPSH6YT()) QhzXkwjHUxAnhx()[ 311094105.kkPI_gZDy52]; ; DCsajY[][] Rocrib0_fx; ; } return null.S0K; void[] hk11R2qgce; ( -!( !!-new int[ Rs0VZYc0ixF[ !-!false[ null.ZB]]][ jEGpzbRYB87.h()]).d_tWlrVOSBCqW).QtqyB98sG; BFBO0C0yl[][] ZnDO; boolean[][] Bnc3aov = V4jgwIkW().sqUE7gGb9o5FjQ() = !-qc9s.vkG_3(); boolean M; int[] R; } public Hzx7ophZ9 F; public static void TzL4aj_ (String[] EX2oLDJBxPWM) { while ( !this.mzrF6Kffaz()) while ( GV.mbFdWOaeTzaZB) if ( ( --431646147[ ( new void[ -( ( AHJPtzul[ !!!!null.SZh74Sc96v()])._E21nZc4).CkVIYB6][ -this.zoGUjVMk0nxHS()]).cg1zjXNQ6CZ8V()]).vkOOpTipNEoZQ()) if ( null.PpoYS5AFi0Jq_()) return; { int[] qEbxT1cEEkUAs; void joTo7; --5063.TGPFx6USrW(); ; null.DbEhHB; if ( -null.qVlvb()) { if ( --new r().Yds03yUmX) return; } ; tc3IxnrUR[] P6sveaO; boolean Iy9j79s; int[] FqGfSfUtVnm; void rY3o5EZlvu8dn; { ; } LPw92PNgGelG Zqwah7QydM; int VLWC3zB; boolean[][] ehWVS5; while ( 83828891[ !02923287.KPERo()]) -null[ !!new int[ uP.X4OJ7T].PBIONsI]; } boolean uupgq = !( -!true.vccb7()).ufGiO3rVp591; while ( null[ -false[ ( -eURE7RGK()[ !this.CN()]).v1CX9wNamGN()]]) ; void[] inKiSB; if ( --!-RvO8_QCt_CcU().SwBnb4()) while ( new C()[ 34[ new IZlUutWt[ !new Buk5bRii().rS0oH].ppsihQa_Cx6W()]]) if ( new CvmS().Rk6D()) if ( AF.E0dFZ8rm) ;else { while ( !!-null.ZsktjRP8GQ()) -this[ ( !-A8RfmUDv5p[ a().VvReLTOceb()])[ null.bwnmcMZ()]]; } aWD8aj NmewRvh; boolean TnR8Q9; boolean[] m; int[] QMh; S5[][] EMw; if ( -!-0555102[ this[ -this[ this.PmfhHdt3eoLDG]]]) new boolean[ false.giNhPoQ7hTq3PI()].gLr5Pzr; } public static void mie1iDEvyo6 (String[] hjvfG) { boolean[] YJ4t85O; boolean ByjVuOTWQxHvLC = new X8iC().Wd6c9A = true.sS3L; ; ; { --null.kpixU(); return; rX6l2CrWxvkC QSFLOTghFKpAa; if ( -!!this[ !( null[ -true.X()]).sIQBz6wSCZmIm]) !!this.siP2JSi3; VhtMZdreFeMk f; void[][][] f2A0ggb; false.vdYPwxiox1tu4O(); } void K; { Zqq nsNYbBQIEi; oXfSHPzNsfb[][][][][][] EB7X0WOHMuJ; if ( --( -K5_aE4KP_lMjzW.dGOPGr()).EmT06KaUV2kXO) { if ( MJk7Ou2[ new ZhE().W1UJRTHuPG0o]) { int j6naFUh0wrkNY; } } void O0322NfA; } ; ZuSd0 PGQ = -this[ tqjGz2[ null[ null[ -pj54vvz._7eLATQUqFQ()]]]] = this[ false[ -na[ 9[ !!true[ --( --!-!DzaO()[ !true.rvD5U8yE2WYncY()]).hlZ]]]]]; !RrC4IytzkBVlTK.WlY6aK; iKZ8RZ9 QO0yS_j; } public static void ch4bGVgpLHCN5 (String[] eNXZ) throws r2_8aQ4 { while ( !null[ !06331.bJn]) return; int cWd7frul = _glSjD()._rDLaJ4nqNf0Cv(); dZd6k1t[] TmCuQ8o44; eUnWZSFR6 pMP5TUgLx; void[] qWgmS; V0Y6_.zBUB2ZR_wW2rD; hThEKUJ[][] O = !-!this[ null.N1dZMz]; !!!iO2jU4HJX3ws7.rWvWGy_vUuoGqf(); while ( -( -!( -null.HUYy).ZX1wnDxLgXE).F()) !-52608061.fDpvmFHYr; if ( q()[ this.TpYsnF()]) while ( this.ON7TjgLPR) return; { Dsz[][][][][] TrbyjA; boolean[][][] Ki014brMQ9Z_yg; return; while ( --this.z1lFVNVFvO8t) { return; } boolean[] N2Ufy3rYJn; false.FgIy7ybexL0N4; int B1t2; boolean[] KdO; void O4jWCUkfQmyVe; void FOiZ4Qoq4; ; if ( false[ false.qb1u4c12]) if ( new int[ !new i()[ null.w3B()]][ -new jN8CgztvC6Ir[ !new int[ false.nlI57G6gIt5Fkp].oDn_].XCSg2mx7b4]) ; if ( new int[ -!this.gkcd()].D9ejNSRGkXZfs()) while ( -null.Lx79fBTMBuh8()) ; int LzJ8qxsKoZotqB; return; return; boolean[][][][] w7rghxg; void[] Uij1q8u8y301th; return; while ( 358094955[ new boolean[ !this.pigOfNNm9Ej()][ this.nBZ0PNiat()]]) { dIGGgyhXWzTCjP Y; } } bmlkSzK[][][] cbN; ; Y2n1[] RlFPnCwi3 = -( false[ ( 8928385.td7mG())[ --this.pjnKRdxFtx()]]).S(); } public int snBAIFATuBbN6; public int tHqSOi () { int[][][] Te8S7C4wEsuY = new TLJnI2Q().Yoy() = !C9op3eI8OSek()[ !false.PQMqsTPexcDE()]; void[] f8TesNwVtUS = !new c8vW6f().HXdZte = new hSm().Dk0WwI4; if ( 28383.NrDV1nvXj()) if ( !!false._2aLYdApt6wOl) { ; } if ( !new vZ9G7wya043Mi().j()) while ( -new boolean[ -22.HPVwewYemipC()].FR3pPJ_ZUME) if ( !-!false.x2SeugQlEof4MO) return; { void b8jS; ; void[][][][][][] nf_gHkVI; boolean[] KwrJ; return; { n[][][] jy; } Faydp5[] L51AgbZ; int iu; boolean[] l; while ( -!776896419[ new void[ new boolean[ -new boolean[ this.kEET9DCrZPPRBn()][ null[ true.h()]]].OyfI3()][ !!!59[ !!--NpUZStqFF.EUYSouiC8y]]]) while ( ( !( 98209386.e_Feaq1N()).lfyKIyv32cE)[ !-null[ -!!null.nHecnwFXWJsd]]) while ( x1rHFp3_ZPL().uF6VRrzT) while ( UZugLNZ()[ null[ -!-new int[ -this.tL].NZ1cW()]]) ; if ( this[ --!!( -!this.FH43Uk0YZL)[ new uC_cea[ !roWI45d6Oj.lGQr].GV3Y]]) if ( QHCgDpGd08m()[ new boolean[ -!0.Wp0Upu][ Sib3juOt[ false.c8pVIp6PMvk]]]) ; } r8OJ[][][][] ECWhMkBwmC; int WTyrIUO6FciJ7; un3Y6LWqGJ j = V42oq7rNTKu5jO().u = false.m_k91ByeTg_P; void[] FKG92ygAmke = ( MIDyzg5zp.JTt)[ -187477[ !new ui().cHq8j8Kir()]] = null.SrwRhM1NCjn(); } public void NyH7K (ypJw8Ia QPak, x0tIr_mXE1CvJX[][] j73ije) throws V9dmaJ { !-!new boolean[ null.PATYK()][ this.PAf()]; M YMvv2crBEHv0W; while ( -!836.EApxwYJVP()) ; int _FwZm; BmImaSe[][][] ECnc21S; if ( new L6Ml5RhdIyw().egJJyfDFLkddc) if ( true.ja2Fn) if ( new z1[ true.SwTIN()].s6) return; void F5cQvV = !-0695767.C31v1YZpWKGh; CBBe CW3jpMv3z = dSyMSf.EuePSxF0MrB() = -false.SHdWD(); return !null.o2nF; E[] qicDN3BZ0E0 = !!A_sI()[ !-true.Vw]; return -new K5b9P().CS(); ; int[] jC; boolean dqquAUpzf2tfIY; } public boolean UrUD () throws oy { void kU; int gvpEkw = -!fKa().vwHVZ; } public void[][][][] YyxW0; public boolean[] cHZ8qJz8Tgd; public static void AglPo4F_ (String[] pHO8_qrw) { ; int[] F2w_V_ = !!593808711[ !-new boolean[ ( --JuX3okKUUZL().kGxF2GR1I6gZNA())[ !!18[ -HYw2CQyv8Znc56.if6mFuR]]].mLOKm] = -true[ !-!( !-BfDG()[ new krJVOfyRmup5r()[ ( null.eKNgjc5kn()).s8DQ7LCjz()]]).SLMAKF]; CAczXzI().NVEbVIRhN; boolean qciIj = -!-!!-null.a2L = !false[ new iYSauqISQ_().UUfjR6]; if ( new void[ ( -!-new yQj1nfXXzyEGSo()[ !( -!false.PQZW1OUgLgG)[ -new boolean[ ( C[ ---dKe.R]).vzXxWRSuc_9].FQep0wjTcO]])[ 980461[ !-16125938[ !!wS().Xl1043UvhQr()]]]].nbhYLMV6eljg) false.FSvrgrmnY;else ; boolean gZXeIYq7; int PBI_ = --new boolean[ 824.fa4m5Aj5n6q0P].xCRNbWO; int[][][][] EW_r = ( 337[ !( !true.W2()).z9XcA8]).j6jY(); !true.OG7tQqUTovG(); aXpI6eD4T AS9m; void[] HHQZ3EK = ( -76062.mtw7a()).mzMO; ; return; !!!false[ this.fwXASbyuO()]; void[] AAX3Vi2; EcMcEQ8lDgQm kL; return mupo9GSdJGaKK[ false.wMcDOuslIQ7]; int gUPLG = a6fqCfLpBSV[ ---true.hZAk7] = true.N7II4VO2kQ; void axf = !!--true.iKS(); } public boolean L10o0mLy0l; } class z { public boolean DPc4BQQWBs4Xs (iii99gEDJ9gYLW[] E, boolean[] PXnQ2WMDJwT, boolean[][] D01uRRuuYXj0d, void s) throws g3vecwpAX { oc0cMW xhT5m; } }
39.893701
329
0.499194
5ddbd312df9b7b58a862df27d4debab9a0f1bfdc
449
package com.gangz.food.order.domain.order; import com.gangz.food.order.applications.OrderItemDTO; import com.gangz.food.order.infrastructure.user.UserId; import java.util.List; public class OrderFactory { public Order create(UserId userId, List<OrderItemDTO> orderItems) { Order order = new Order(); orderItems.forEach(item->order.addItem(item.foodId(),item.quantity())); order.submit(); return order; } }
28.0625
79
0.712695
b4202c97d08fbafec1d17c5f2a7b894565cbe8c7
66
package com.zingson.jeasy.utils.encrypt; public class Sha256 { }
13.2
40
0.772727
39eadc5de4252656733505a2af76941ab10bdc55
2,944
package org.zmsoft.common.mail; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.mail.internet.MimeMessage; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.stereotype.Component; import org.zmsoft.config.mail.MailConfigService; /** * 实现多账号,轮询发送 */ @Component("MailSender") public class MailSender extends JavaMailSenderImpl implements JavaMailSender { private MailConfigService myMailConfig; // 保存多个用户名和密码的队列 private ArrayList<String> usernameList; private ArrayList<String> passwordList; // 轮询标识 private int currentMailId = 0; // public MailSender() { // if (EmptyHelper.isEmpty(myMailConfig)) // myMailConfig = MyBeanFactoryHelper.getBean(MyMailConfig.class.getSimpleName()); // String username = myMailConfig.getUsername(); // String password = myMailConfig.getPassword(); // // 初始化账号 // if (usernameList == null) // usernameList = new ArrayList<String>(); // String[] userNames = username.split(","); // if (userNames != null) { // for (String user : userNames) { // usernameList.add(user); // } // } // // // 初始化密码 // if (passwordList == null) // passwordList = new ArrayList<String>(); // String[] passwords = password.split(","); // if (passwords != null) { // for (String pw : passwords) { // passwordList.add(pw); // } // } } @Override protected void doSend(MimeMessage[] mimeMessage, Object[] object) throws MailException { super.setUsername(usernameList.get(currentMailId)); super.setPassword(passwordList.get(currentMailId)); String host = myMailConfig.getHost(); int port = Integer.valueOf(myMailConfig.getPort()); String defaultEncoding = myMailConfig.getDefaultEncoding(); // 设置编码和各种参数 super.setHost(host); super.setPort(port); super.setDefaultEncoding(defaultEncoding); super.setJavaMailProperties(asProperties(this.getProperties())); super.doSend(mimeMessage, object); // 轮询 currentMailId = (currentMailId + 1) % usernameList.size(); } private Properties asProperties(Map<String, String> source) { Properties properties = new Properties(); properties.putAll(source); return properties; } public Map<String, String> getProperties() { // String auth = myMailConfig.getAuth(); String timeout = myMailConfig.getTimeout(); int port = Integer.valueOf(myMailConfig.getPort()); Map<String, String> map = new HashMap<String, String>(); map.put("mail.smtp.timeout", timeout); map.put("mail.smtp.auth", auth); map.put("mail.smtp.socketFactory.fallback", "false"); map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); map.put("mail.smtp.socketFactory.port", port + ""); return map; } @Override public String getUsername() { return usernameList.get(currentMailId); } }
27.514019
84
0.723505
6f83b7069db0a109b430be14c447596c0f7c068e
2,079
package com.kickstarter.ui.views; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatDialog; import android.widget.Button; import com.kickstarter.KSApplication; import com.kickstarter.R; import com.kickstarter.libs.Koala; import com.kickstarter.libs.preferences.BooleanPreferenceType; import com.kickstarter.libs.qualifiers.AppRatingPreference; import com.kickstarter.libs.utils.ViewUtils; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class AppRatingDialog extends AppCompatDialog { protected @Inject @AppRatingPreference BooleanPreferenceType hasSeenAppRatingPreference; protected @Inject Koala koala; protected @Bind(R.id.no_thanks_button) Button noThanksButton; protected @Bind(R.id.remind_button) Button remindButton; protected @Bind(R.id.rate_button) Button rateButton; public AppRatingDialog(final @NonNull Context context) { super(context); } @Override protected void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); setContentView(R.layout.app_rating_prompt); ButterKnife.bind(this); ((KSApplication) getContext().getApplicationContext()).component().inject(this); } @OnClick(R.id.rate_button) protected void rateButtonClick() { this.koala.trackAppRatingNow(); this.hasSeenAppRatingPreference.set(true); dismiss(); ViewUtils.openStoreRating(getContext(), getContext().getPackageName()); } @OnClick(R.id.remind_button) protected void remindButtonClick() { this.koala.trackAppRatingRemindLater(); dismiss(); } @OnClick(R.id.no_thanks_button) protected void noThanksButtonClick() { this.koala.trackAppRatingNoThanks(); this.hasSeenAppRatingPreference.set(true); dismiss(); } }
31.029851
93
0.787398
8b46b8987f24336dfd6c532d75ca658ceadd71fd
1,137
/* * Owned by aizuddindeyn * Visit https://gitlab.com/group-bear/mouse-automation */ package com.aizuddindeyn.mouse; import java.text.MessageFormat; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author aizuddindeyn * @date 11/7/2020 */ class MouseRunnable implements Runnable { private final ScheduledExecutorService executor; MouseRunnable(ScheduledExecutorService executor) { this.executor = executor; } @Override public void run() { boolean started = MouseInstance.getInstance().isStarted(); String status = (started) ? "started" : "paused"; String action = (started) ? "pause" : "resume"; String message = MessageFormat.format("App {0}. Press ''p'' and ''Enter'' to {1} (''e'' to exit): ", status, action); boolean valid = MousePrompt.getInstance().prompt(message); if (valid) { MouseApplication.startStop(started); } executor.schedule(new MouseRunnable(executor), MouseUtils.EXECUTOR_DELAY, TimeUnit.MILLISECONDS); } }
29.153846
105
0.652595
68fc40819bf67537ea2ba16f9055d6d90645fd42
3,363
/* * Copyright www.jingtum.com Inc. * * 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 com.jingtum.net; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.jingtum.model.Wallet; import com.jingtum.model.BalanceCollection; import com.jingtum.model.EffectCollection; import com.jingtum.model.MemoCollection; import com.jingtum.model.Notification; import com.jingtum.model.PaymentCollection; import com.jingtum.model.RelationCollection; import com.jingtum.model.TransactionCollection; import com.jingtum.model.TrustLineCollection; import com.jingtum.model.OrderCollection; import com.jingtum.model.OrderBookCollection; import com.jingtum.model.PaymentChoiceCollection; import java.lang.reflect.Type; /** * @author jzhao * @version 1.0 * Updated by zpli * Added Memo, PaymentChoice */ public class WalletDeserializer implements JsonDeserializer<Wallet> { public Wallet deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(BalanceCollection.class, new BalanceCollectionDeserializer()) .registerTypeAdapter(PaymentCollection.class, new PaymentCollectionDeserializer()) .registerTypeAdapter(OrderCollection.class, new OrderCollectionDeserializer()) .registerTypeAdapter(OrderBookCollection.class, new OrderBookCollectionDeserializer()) .registerTypeAdapter(TrustLineCollection.class, new TrustLineCollectionDeserializer()) .registerTypeAdapter(TransactionCollection.class, new TransactionCollectionDeserializer()) .registerTypeAdapter(EffectCollection.class, new EffectCollectionDeserializer()) .registerTypeAdapter(MemoCollection.class, new MemoCollectionDeserializer()) .registerTypeAdapter(RelationCollection.class, new RelationCollectionDeserializer()) .registerTypeAdapter(Notification.class, new NotificationDeserializer()) .registerTypeAdapter(PaymentChoiceCollection.class, new PaymentChoiceCollectionDeserializer()) .create(); Wallet wallet = gson.fromJson(json, Wallet.class); return wallet; } }
46.708333
125
0.765388
60ef7c772a5c19897db31fa2d66790c51168654d
1,355
/*************************************************************************** * Copyright 2017 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.examples.livedemo.analysis.util; /** * * @author Bjoern Weissenfels * * @since 1.10 * * @param <V> * The first type. * @param <W> * The second type. */ public class Pair<V, W> { private V first; private W last; public Pair(final V first, final W last) { this.first = first; this.last = last; } public V getFirst() { return this.first; } public void setFirst(final V first) { this.first = first; } public W getLast() { return this.last; } public void setLast(final W last) { this.last = last; } }
24.196429
77
0.6
8cdc1b6db04bee43537f6da9ce2ee0037fe7f9b2
4,182
package nl.haroid.webclient; import nl.haroid.common.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URISyntaxException; import java.net.URL; /** * @author Ruud de Jong */ public abstract class AbstractHaring implements Haring { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHaring.class); private String username; private String password; @Override public final String start(String username, String password) { this.username = username; this.password = password; HttpsSession session = null; try { session = new HttpsSession(new URL(HttpsSession.PROTOCOL + getHost())); InputStream inputStream = session.connect(new URL(HttpsSession.PROTOCOL + getHost() + getRelativeStartUrl())); if (inputStream != null) { if (!login(session, inputStream)) { // Login gefaald. return null; } String tegoed = haalVerbruikGegevensOp(session); LOGGER.debug("Tegoed: " + tegoed); return tegoed; } } catch (MalformedURLException e) { LOGGER.error("URL invalid: ", e); } catch (ClassCastException e) { LOGGER.error("Class cast: ", e); } catch (SocketTimeoutException e) { LOGGER.warn("Timeout: ", e); } catch (IOException e) { LOGGER.error("IO error: ", e); } catch (URISyntaxException e) { LOGGER.error("URL invalid: ", e); } finally { if (session != null) { session.disconnect(); } } return "niet gevonden"; } protected abstract String getHost(); protected abstract String getRelativeStartUrl(); protected abstract String getRelativeVerbruikUrl(); protected abstract String vindTegoed(String body); private boolean login(HttpsSession session, InputStream inputStream) throws IOException, URISyntaxException { LOGGER.info("***************************************"); LOGGER.info("** INLOGGEN **"); LOGGER.info("***************************************"); String body = Utils.toString(inputStream); LOGGER.debug("Response body size: " + body.length() + " bytes."); LOGGER.trace("Body: " + body); inputStream.close(); FormParserUtil.Form form = FormParserUtil.parseForm(body); if (form == null) { LOGGER.info("Kan het inlogscherm niet vinden"); LOGGER.info(body); return false; } LOGGER.info("Form:"); LOGGER.info("Form action: " + form.action); LOGGER.info("Form inputs: " + form.inputList.size()); FormParserUtil.Input loginInput = FormParserUtil.getLoginInput(form); FormParserUtil.Input passwordInput = FormParserUtil.getPasswordInput(form); if (loginInput != null && passwordInput != null) { loginInput.value = username; passwordInput.value = password; return FormParserUtil.postForm(session, form); } else { LOGGER.info("Kan login en password velden NIET vinden op het login scherm."); return false; } } private String haalVerbruikGegevensOp(HttpsSession session) throws IOException { LOGGER.info("***************************************"); LOGGER.info("** VERBRUIK OPHALEN **"); LOGGER.info("***************************************"); InputStream inputStream = session.get(new URL(HttpsSession.PROTOCOL + getHost() + getRelativeVerbruikUrl())); String body = Utils.toString(inputStream); LOGGER.info("Response body size: " + body.length() + " bytes."); LOGGER.trace("Body: " + body); inputStream.close(); String tegoed = vindTegoed(body); LOGGER.info("Gevonden tegoed: " + tegoed); return tegoed; } }
37.00885
122
0.580823
e6b20ba420705d7475558cdfecd396b4c58e2cec
987
package simple.example.kocheng.model; public class Beruang { private String jenis; private String asal; private String deskripsi; private int drawableRes; public Beruang(String jenis, String asal, String deskripsi, int drawableRes) { this.jenis = jenis; this.asal = asal; this.deskripsi = deskripsi; this.drawableRes = drawableRes; } public String getJenis() { return jenis; } public void setJenis(String jenis) { this.jenis = jenis; } public String getAsal() { return asal; } public void setAsal(String asal) { this.asal = asal; } public String getDeskripsi() { return deskripsi; } public void setDeskripsi(String deskripsi) { this.deskripsi = deskripsi; } public int getDrawableRes() { return drawableRes; } public void setDrawableRes(int drawableRes) { this.drawableRes = drawableRes; } }
20.142857
82
0.617021
a578436926a18d7519c0de4fdafc62f39fbee852
10,067
/* * Copyright (c) Numerical Method Inc. * http://www.numericalmethod.com/ * * THIS SOFTWARE IS LICENSED, NOT SOLD. * * YOU MAY USE THIS SOFTWARE ONLY AS DESCRIBED IN THE LICENSE. * IF YOU ARE NOT AWARE OF AND/OR DO NOT AGREE TO THE TERMS OF THE LICENSE, * DO NOT USE THIS SOFTWARE. * * THE SOFTWARE IS PROVIDED "AS IS", WITH NO WARRANTY WHATSOEVER, * EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, * ANY WARRANTIES OF ACCURACY, ACCESSIBILITY, COMPLETENESS, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, NON-INFRINGEMENT, * TITLE AND USEFULNESS. * * IN NO EVENT AND UNDER NO LEGAL THEORY, * WHETHER IN ACTION, CONTRACT, NEGLIGENCE, TORT, OR OTHERWISE, * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIMS, DAMAGES OR OTHER LIABILITIES, * ARISING AS A RESULT OF USING OR OTHER DEALINGS IN THE SOFTWARE. */ package com.numericalmethod.suanshu.matrix.doubles.factorization.qr; import com.numericalmethod.suanshu.matrix.doubles.IsMatrix; import com.numericalmethod.suanshu.matrix.doubles.Matrix; import com.numericalmethod.suanshu.matrix.doubles.matrixtype.PermutationMatrix; import com.numericalmethod.suanshu.matrix.doubles.matrixtype.dense.DenseMatrix; import com.numericalmethod.suanshu.matrix.doubles.matrixtype.dense.triangle.UpperTriangularMatrix; import com.numericalmethod.suanshu.matrix.doubles.operation.CreateMatrix; import com.numericalmethod.suanshu.misc.SuanShuUtils; import com.numericalmethod.suanshu.vector.doubles.Vector; import com.numericalmethod.suanshu.vector.doubles.dense.DenseVector; import com.numericalmethod.suanshu.vector.doubles.dense.operation.Basis; import com.numericalmethod.suanshu.vector.doubles.operation.Projection; import java.util.ArrayList; import java.util.List; /** * The Gram–Schmidt process is a method for orthogonalizing a set of vectors in an inner product space. * It does so by iteratively computing the vector orthogonal to the subspace spanned by the previously found orthogonal vectors. * An orthogonal vector is the difference between a column vector and its projection on the subspace. * <p/> * There is the problem of "loss of orthogonality" during the process. * In general, the bigger the matrix is, e.g., dimension = 3500x3500, the less precise the result is. * The vectors in <i>Q</i> may not be as orthogonal. * This implementation uses a numerically stable Gram–Schmidt process with twice re-orthogonalization * to alleviate the problem of rounding errors. * <p/> * Numerical determination of rank requires a criterion to decide how small a value should be treated as zero. * This is a practical choice which depends on both the matrix and the application. * For instance, for a matrix with a big first eigenvector, * we should accordingly decrease the precision to compute the rank. * <p/> * While the result for the orthogonal basis may match those of the Householder Reflection {@link HouseholderReflection}, * the result for the orthogonal complement may differ because the kernel basis is not unique. * * @author Haksun Li * @see * <ul> * <li>"Luc Giraud, Julien Langou, Miroslav Rozloznik, "On the loss of orthogonality in the Gram-Schmidt orthogonalization process," Computers & Mathematics with Applications, Volume 50, Issue 7, October 2005, p. 1069-1075. Numerical Methods and Computational Mechanics." * <li>"Gene H. Golub, Charles F. Van Loan, Matrix Computations (Johns Hopkins Studies in Mathematical Sciences)(3rd Edition)(Paperback)." * <li><a href="http://en.wikipedia.org/wiki/Gram-Schmidt">Wikipedia: Gram–Schmidt process</a> * </ul> */ //TODO: column pivoting, rank, det, output the diagonal // public class GramSchmidt implements QRDecomposition { private Matrix Q; private UpperTriangularMatrix R; private PermutationMatrix P; private int rank; private final DenseVector zero; private final int nRows;//the number of rows private final int nCols;//the number of columns private final double epsilon; /** * Run the Gram-Schmidt process to orthogonalize a matrix. * * @param A a matrix * @param pad0Cols when a column is linearly dependent on the previous columns, there is no orthogonal vector. We pad the basis with a 0-vector. * @param epsilon a precision parameter: when a number |x| ≤ ε, it is considered 0 */ public GramSchmidt(Matrix A, boolean pad0Cols, double epsilon) { this.nRows = A.nRows(); this.nCols = A.nCols(); this.epsilon = epsilon; R = new UpperTriangularMatrix(nCols); R.set(1, 1, 0);//allocate space P = new PermutationMatrix(nCols);//For a fat matrix A, the permutation matrix P is not square. The rightmost columns are 0. rank = 0; zero = new DenseVector(nRows); Vector[] basis = new Vector[nCols]; basis[0] = new DenseVector(nRows);//in case the one and only column has norm 0, we need to have the lenght for CreateMatrix.cbind for (int i = 1; i <= nCols; ++i) {//This loop implements the stabilized version of the modified Gram-Schmidt process. Vector orthogonalVector = A.getColumn(i); for (int j = 1; j <= 2; ++j) {//reorthogonalization; twice is enough for (int k = 1; k <= i - 1; ++k) { if (basis[k - 1] != null) {//basis[i] is not zero vector Projection projection = new Projection(orthogonalVector, basis[k - 1]); orthogonalVector = projection.getOrthogonalVector(); R.set(k, i, projection.getProjectionLength(0) + R.get(k, i)); } } } if (!IsMatrix.zero(orthogonalVector, epsilon)) { double norm = orthogonalVector.norm(); R.set(i, i, norm); basis[i - 1] = orthogonalVector.scaled(1. / norm); rank++;//increase rank each linearly independent vector is found } else {//orthogonalVector is not a basis b/c of linear dependence if (pad0Cols) { basis[i - 1] = zero; } R.set(i, i, 0); P.moveColumn2End(i);//record column pivoting if this vector is linearly dependent on the previous vectors } } Q = CreateMatrix.cbind(basis); } /** * Run the Gram-Schmidt process to orthogonalize a matrix. * * @param A a matrix */ public GramSchmidt(Matrix A) { this(A, true, SuanShuUtils.autoEpsilon(A)); } @Override public Matrix Q() { return Q.deepCopy(); } @Override public UpperTriangularMatrix R() { return new UpperTriangularMatrix(R); } @Override public PermutationMatrix P() { return new PermutationMatrix(P); } @Override public int rank() { return rank; } /** * {@inheritDoc} * * This implementation extends <i>Q</i> by appending <i>A</i>'s orthogonal complement. * Suppose <i>Q</i> has the orthogonal basis for a subspace <i>A</i>. * To compute the orthogonal complement of <i>A</i>, we apply the Gram-Schmidt procedure to either * <ol> * <li>the columns of <i>I - P = I - Q * Q'</i>, or * <li>the spanning set \(\left \{ u_1, u_2, ..., u_k, e_1, e_2, ..., e_n \right \}\) * and keeping only the first <i>n</i> elements of the resulting basis of <i>R<sub>n</sub></i>. * The last <i>n-k</i> elements are the basis for the orthogonal complement. <i>k</i> is the rank. * </ol> * We implemented the second option. * * @return the spanning set of both the orthogonal basis of <i>A</i> and the orthogonal complement */ @Override public Matrix squareQ() { if (Q.nRows() == rank) {//<i>A</i> is full rank if (Q.nCols() <= Q.nRows()) {//square or tall <i>A</i> return Q();//<i>Q</i> is already complete because <i>A</i> is full rank } Matrix squareQ = CreateMatrix.subMatrix(Q, 1, nRows, 1, nRows);//keep only the first <i>nRows</i> columns return squareQ; } /* * When <i>A</i> is full rank and there are more columns than rows, * we need to do a reduction to make <i>Q</i> <i>nRows x nRows</i>. */ if (Q.nCols() > Q.nRows()) { Matrix Qcomplete = CreateMatrix.subMatrix(Q, 1, nRows, 1, nRows);//keep only the first <i>nRows</i> columns return Qcomplete; } /* * When A is not full rank, we need to complete the square <i>Q</i> * by adding the basis of the null space or range space of <i>A</i>. */ List<Vector> basis = new ArrayList<Vector>(); for (int i = 1; i <= rank; ++i) {//compute the span for the range space basis.add(Q.getColumn(i)); } List<Vector> Rn = Basis.getBasis(nRows, nRows);//basis for Euclidean space Rn basis.addAll(Rn); Matrix M = CreateMatrix.cbind(basis); GramSchmidt gs = new GramSchmidt(M, false, epsilon); Matrix squareQ = gs.Q(); squareQ = CreateMatrix.subMatrix(squareQ, 1, nRows, 1, nRows);//keep only the first <i>nRows</i> columns return squareQ; } @Override public Matrix tallR() { UpperTriangularMatrix myR = R(); if (nRows < nCols) {//for fat matrices return CreateMatrix.subMatrix(myR, 1, nRows, 1, nCols); } //for tall matrices Matrix tallR = new DenseMatrix(nRows, nCols).ZERO(); CreateMatrix.replace(tallR, 1, Math.min(nCols, nRows), 1, nCols, myR); return tallR; } }
44.153509
272
0.628688
f6a1431e4fbc35f959ff122765a265c9128089c9
5,833
package uk.nhs.cdss.transform.out.two; import static java.util.Collections.singletonList; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import java.time.Clock; import java.time.Duration; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.hl7.fhir.dstu3.model.Identifier; import org.hl7.fhir.dstu3.model.Narrative; import org.hl7.fhir.dstu3.model.Period; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.dstu3.model.ReferralRequest; import org.hl7.fhir.dstu3.model.ReferralRequest.ReferralCategory; import org.hl7.fhir.dstu3.model.ReferralRequest.ReferralPriority; import org.hl7.fhir.dstu3.model.ReferralRequest.ReferralRequestStatus; import org.hl7.fhir.dstu3.model.Type; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import uk.nhs.cdss.constants.ApiProfiles; import uk.nhs.cdss.domain.ActivityDefinition; import uk.nhs.cdss.domain.Concern; import uk.nhs.cdss.engine.CodeDirectory; import uk.nhs.cdss.services.NarrativeService; import uk.nhs.cdss.services.ReferenceStorageService; import uk.nhs.cdss.transform.bundle.ConcernBundle; import uk.nhs.cdss.transform.bundle.ReferralRequestBundle; import uk.nhs.cdss.transform.out.ConceptTransformer; import uk.nhs.cdss.transform.out.ConditionTransformer; import uk.nhs.cdss.transform.out.ReferralRequestTransformer; import uk.nhs.cdss.transform.out.two.ProcedureRequestTransformer.ProcedureRequestBundle; @Component @Profile(ApiProfiles.TWO) @AllArgsConstructor public class ReferralRequestTwoTransformer implements ReferralRequestTransformer { private static final Duration ROUTINE_APPOINTMENT_OCCURRENCE = Duration.parse("P7D"); private final ConceptTransformer conceptTransformer; private final ConditionTransformer conditionTransformer; private final ProcedureRequestTransformer procedureRequestTransformer; private final CodeDirectory codeDirectory; private final ReferenceStorageService referenceStorageService; private final NarrativeService narrativeService; private final Clock clock; @Override public ReferralRequest transform(ReferralRequestBundle bundle) { ReferralRequest result = new ReferralRequest(); var from = bundle.getReferralRequest(); Reference subject = bundle.getSubject(); Reference context = bundle.getContext(); Reference reasonRef = referenceStorageService.create( conditionTransformer.transform(createConcernBundle(bundle, from.getReason()))); result.setDefinition(transformDefinition(from.getDefinition())); result.setGroupIdentifier(new Identifier() .setValue(bundle.getRequestGroupId())); ReferralRequestStatus status = bundle.isDraft() ? ReferralRequestStatus.DRAFT : ReferralRequestStatus.ACTIVE; result.setStatus(status); ReferralCategory intent = ReferralCategory.PLAN; result.setIntent(intent); result.setPriority(ReferralPriority.ROUTINE); result.setSubject(subject); result.setContext(context); result.setText(transformNarrative(bundle.getReferralRequest())); Type occurrence = transformOccurrence(from.getOccurrence()); result.setOccurrence(occurrence); result.setAuthoredOn(defaultIfNull(from.getAuthoredOn(), Date.from(clock.instant()))); result.setReasonReference(singletonList(reasonRef)); result.setDescription(from.getDescription()); List<Reference> relevantHistory = transformRelevantHistory(from.getRelevantHistory()); result.setRelevantHistory(relevantHistory); List<Reference> supportingInfo = from.getSecondaryReasons() .stream() .map(concern -> createConcernBundle(bundle, concern)) .map(conditionTransformer::transform) .map(referenceStorageService::create) .collect(Collectors.toList()); ProcedureRequestBundle procedureRequestBundle = ProcedureRequestBundle.builder() .nextActivity(from.getReasonCode()) .referralRequest(result.copy()) //For testability we don't want to modify the instance sent. .build(); Reference procedureRequest = procedureRequestTransformer.transform(procedureRequestBundle); supportingInfo.add(procedureRequest); result.setSupportingInfo(supportingInfo); return result; } private Narrative transformNarrative(uk.nhs.cdss.domain.ReferralRequest referralRequest) { String primaryConcern = conceptTransformer .transform(codeDirectory.get(referralRequest.getReasonCode())) .getCodingFirstRep().getDisplay(); var baseText = "Plan to refer patient to '"+ referralRequest.getDescription() + "'"; var text = baseText + " based on the concern '" + primaryConcern + "'"; return narrativeService.buildNarrative(text); } private ConcernBundle createConcernBundle(ReferralRequestBundle bundle, Concern concern) { return ConcernBundle.builder() .subject(bundle.getSubject()) .context(bundle.getContext()) .questionnaireEvidenceDetail(bundle.getConditionEvidenceResponseDetail()) .observationEvidenceDetail(bundle.getConditionEvidenceObservationDetail()) .concern(concern) .build(); } private Type transformOccurrence(String occurrence) { var duration = "routine".equalsIgnoreCase(occurrence) ? ROUTINE_APPOINTMENT_OCCURRENCE : Duration.parse(occurrence); var now = clock.instant(); return new Period() .setStart(Date.from(now)) .setEnd(Date.from(now.plus(duration))); } private List<Reference> transformDefinition(ActivityDefinition definition) { // TODO return Collections.emptyList(); } private List<Reference> transformRelevantHistory(List<Object> relevantHistory) { // TODO return Collections.emptyList(); } }
39.412162
100
0.776616
6c771cf610a0ecdf8c5c1930c0028844c04e4f9a
72,489
/* * This file is part of Mixin, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.asm.mixin.transformer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.FrameNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.ClassSignature; import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.Locals; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** * Information about a class, used as a way of keeping track of class hierarchy * information needed to support more complex mixin behaviour such as detached * superclass and mixin inheritance. */ public final class ClassInfo { /** * Include <tt>private</tt> members when running a member search */ public static final int INCLUDE_PRIVATE = Opcodes.ACC_PRIVATE; /** * Include <tt>static</tt> members when running a member search */ public static final int INCLUDE_STATIC = Opcodes.ACC_STATIC; /** * Include <tt>private</tt> <b>and</b> <tt>static</tt> members when running * a member search */ public static final int INCLUDE_ALL = ClassInfo.INCLUDE_PRIVATE | ClassInfo.INCLUDE_STATIC; /** * Include instance and class initialisers when running a method search */ public static final int INCLUDE_INITIALISERS = 0x40000; /** * Search type for the findInHierarchy methods, replaces a boolean flag * which made calling code difficult to read */ public static enum SearchType { /** * Include this class when searching in the hierarchy */ ALL_CLASSES, /** * Only walk the superclasses when searching the hierarchy */ SUPER_CLASSES_ONLY } /** * When using {@link ClassInfo#forType ClassInfo.forType}, determines * whether an array type should be returned as declared (eg. as <tt>Object * </tt>) or whether the element type should be returned instead. */ public static enum TypeLookup { /** * Return the type as declared in the descriptor. This means that array * types will be treated <tt>Object</tt> for the purposes of type * hierarchy lookups returning the correct member methods. */ DECLARED_TYPE, /** * Legacy behaviour. A lookup by type will return the element type. */ ELEMENT_TYPE } /** * <p>To all intents and purposes, the "real" class hierarchy and the mixin * class hierarchy exist in parallel, this means that for some hierarchy * validation operations we need to walk <em>across</em> to the other * hierarchy in order to allow meaningful validation to occur.</p> * * <p>This enum defines the type of traversal operations which are allowed * for a particular lookup.</p> * * <p>Each traversal type has a <code>next</code> property which defines * the traversal type to use on the <em>next</em> step of the hierarchy * validation. For example, the type {@link #IMMEDIATE} which requires an * immediate match falls through to {@link #NONE} on the next step, which * prevents further traversals from occurring in the lookup.</p> */ public static enum Traversal { /** * No traversals are allowed. */ NONE(null, false, SearchType.SUPER_CLASSES_ONLY), /** * Traversal is allowed at all stages. */ ALL(null, true, SearchType.ALL_CLASSES), /** * Traversal is allowed at the bottom of the hierarchy but no further. */ IMMEDIATE(Traversal.NONE, true, SearchType.SUPER_CLASSES_ONLY), /** * Traversal is allowed only on superclasses and not at the bottom of * the hierarchy. */ SUPER(Traversal.ALL, false, SearchType.SUPER_CLASSES_ONLY); private final Traversal next; private final boolean traverse; private final SearchType searchType; private Traversal(Traversal next, boolean traverse, SearchType searchType) { this.next = next != null ? next : this; this.traverse = traverse; this.searchType = searchType; } /** * Return the next traversal type for this traversal type */ public Traversal next() { return this.next; } /** * Return whether this traversal type allows traversal */ public boolean canTraverse() { return this.traverse; } public SearchType getSearchType() { return this.searchType; } } /** * Information about frames in a method */ public static class FrameData { private static final String[] FRAMETYPES = { "NEW", "FULL", "APPEND", "CHOP", "SAME", "SAME1" }; /** * Frame index */ public final int index; /** * Frame type */ public final int type; /** * Frame local count */ public final int locals; /** * Frame local size */ public final int size; FrameData(int index, int type, int locals, int size) { this.index = index; this.type = type; this.locals = locals; this.size = size; } FrameData(int index, FrameNode frameNode) { this.index = index; this.type = frameNode.type; this.locals = frameNode.local != null ? frameNode.local.size() : 0; this.size = Locals.computeFrameSize(frameNode); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("FrameData[index=%d, type=%s, locals=%d size=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals, this.size); } } /** * Information about a member in this class */ abstract static class Member { /** * Member type */ static enum Type { METHOD, FIELD } /** * Member type */ private final Type type; /** * The original name of the member */ private final String memberName; /** * The member's signature */ private final String memberDesc; /** * True if this member was injected by a mixin, false if it was * originally part of the class */ private final boolean isInjected; /** * Access modifiers */ private final int modifiers; /** * Current name of the member, may be different from {@link #memberName} * if the member has been renamed */ private String currentName; /** * Current descriptor of the member, may be different from * {@link #memberDesc} if the member has been remapped */ private String currentDesc; /** * True if this member is decorated with {@link Final} */ private boolean decoratedFinal; /** * True if this member is decorated with {@link Mutable} */ private boolean decoratedMutable; /** * True if this member is decorated with {@link Unique} */ private boolean unique; protected Member(Member member) { this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected); this.currentName = member.currentName; this.currentDesc = member.currentDesc; this.unique = member.unique; } protected Member(Type type, String name, String desc, int access) { this(type, name, desc, access, false); } protected Member(Type type, String name, String desc, int access, boolean injected) { this.type = type; this.memberName = name; this.memberDesc = desc; this.isInjected = injected; this.currentName = name; this.currentDesc = desc; this.modifiers = access; } public String getOriginalName() { return this.memberName; } public String getName() { return this.currentName; } public String getOriginalDesc() { return this.memberDesc; } public String getDesc() { return this.currentDesc; } public boolean isInjected() { return this.isInjected; } public boolean isRenamed() { return !this.currentName.equals(this.memberName); } public boolean isRemapped() { return !this.currentDesc.equals(this.memberDesc); } public boolean isPrivate() { return (this.modifiers & Opcodes.ACC_PRIVATE) != 0; } public boolean isStatic() { return (this.modifiers & Opcodes.ACC_STATIC) != 0; } public boolean isAbstract() { return (this.modifiers & Opcodes.ACC_ABSTRACT) != 0; } public boolean isFinal() { return (this.modifiers & Opcodes.ACC_FINAL) != 0; } public boolean isSynthetic() { return (this.modifiers & Opcodes.ACC_SYNTHETIC) != 0; } public boolean isUnique() { return this.unique; } public void setUnique(boolean unique) { this.unique = unique; } public boolean isDecoratedFinal() { return this.decoratedFinal; } public boolean isDecoratedMutable() { return this.decoratedMutable; } protected void setDecoratedFinal(boolean decoratedFinal, boolean decoratedMutable) { this.decoratedFinal = decoratedFinal; this.decoratedMutable = decoratedMutable; } public boolean matchesFlags(int flags) { return (((~this.modifiers | (flags & ClassInfo.INCLUDE_PRIVATE)) & ClassInfo.INCLUDE_PRIVATE) != 0 && ((~this.modifiers | (flags & ClassInfo.INCLUDE_STATIC)) & ClassInfo.INCLUDE_STATIC) != 0); } // Abstract because this has to be static in order to contain the enum public abstract ClassInfo getOwner(); public ClassInfo getImplementor() { return this.getOwner(); } public int getAccess() { return this.modifiers; } /** * @param name new name * @return the passed-in argument, for fluency */ public String renameTo(String name) { this.currentName = name; return name; } public String remapTo(String desc) { this.currentDesc = desc; return desc; } public boolean equals(String name, String desc) { return (this.memberName.equals(name) || this.currentName.equals(name)) && (this.memberDesc.equals(desc) || this.currentDesc.equals(desc)); } @Override public boolean equals(Object obj) { if (!(obj instanceof Member)) { return false; } Member other = (Member)obj; return (other.memberName.equals(this.memberName) || other.currentName.equals(this.currentName)) && (other.memberDesc.equals(this.memberDesc) || other.currentDesc.equals(this.currentDesc)); } @Override public int hashCode() { return this.toString().hashCode(); } @Override public String toString() { return String.format(this.getDisplayFormat(), this.memberName, this.memberDesc); } protected String getDisplayFormat() { return "%s%s"; } } /** * A method */ public class Method extends Member { private final List<FrameData> frames; private boolean isAccessor; private boolean conformed; public Method(Member member) { super(member); this.frames = member instanceof Method ? ((Method)member).frames : null; } public Method(MethodNode method) { this(method, false); } @SuppressWarnings("unchecked") public Method(MethodNode method, boolean injected) { super(Type.METHOD, method.name, method.desc, method.access, injected); this.frames = this.gatherFrames(method); this.setUnique(Annotations.getVisible(method, Unique.class) != null); this.isAccessor = Annotations.getSingleVisible(method, Accessor.class, Invoker.class) != null; boolean decoratedFinal = Annotations.getVisible(method, Final.class) != null; boolean decoratedMutable = Annotations.getVisible(method, Mutable.class) != null; this.setDecoratedFinal(decoratedFinal, decoratedMutable); } public Method(String name, String desc) { super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false); this.frames = null; } public Method(String name, String desc, int access) { super(Type.METHOD, name, desc, access, false); this.frames = null; } public Method(String name, String desc, int access, boolean injected) { super(Type.METHOD, name, desc, access, injected); this.frames = null; } private List<FrameData> gatherFrames(MethodNode method) { List<FrameData> frames = new ArrayList<FrameData>(); for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn instanceof FrameNode) { frames.add(new FrameData(method.instructions.indexOf(insn), (FrameNode)insn)); } } return frames; } public List<FrameData> getFrames() { return this.frames; } @Override public ClassInfo getOwner() { return ClassInfo.this; } public boolean isAccessor() { return this.isAccessor; } public boolean isConformed() { return this.conformed; } @Override public String renameTo(String name) { this.conformed = false; return super.renameTo(name); } /** * @param name new name * @return the passed-in argument, for fluency */ public String conform(String name) { boolean nameChanged = !name.equals(this.getName()); if (this.conformed && nameChanged) { throw new IllegalStateException("Method " + this + " was already conformed. Original= " + this.getOriginalName() + " Current=" + this.getName() + " New=" + name); } if (nameChanged) { this.renameTo(name); this.conformed = true; } return name; } @Override public boolean equals(Object obj) { if (!(obj instanceof Method)) { return false; } return super.equals(obj); } } /** * A method resolved in an interface <em>via</em> a class, return the member * wrapped so that the implementing class can be retrieved. */ public class InterfaceMethod extends Method { private final ClassInfo owner; public InterfaceMethod(Member member) { super(member); this.owner = member.getOwner(); } @Override public ClassInfo getOwner() { return this.owner; } @Override public ClassInfo getImplementor() { return ClassInfo.this; } } /** * A field */ public class Field extends Member { public Field(Member member) { super(member); } public Field(FieldNode field) { this(field, false); } public Field(FieldNode field, boolean injected) { super(Type.FIELD, field.name, field.desc, field.access, injected); this.setUnique(Annotations.getVisible(field, Unique.class) != null); if (Annotations.getVisible(field, Shadow.class) != null) { boolean decoratedFinal = Annotations.getVisible(field, Final.class) != null; boolean decoratedMutable = Annotations.getVisible(field, Mutable.class) != null; this.setDecoratedFinal(decoratedFinal, decoratedMutable); } } public Field(String name, String desc, int access) { super(Type.FIELD, name, desc, access, false); } public Field(String name, String desc, int access, boolean injected) { super(Type.FIELD, name, desc, access, injected); } @Override public ClassInfo getOwner() { return ClassInfo.this; } @Override public boolean equals(Object obj) { if (!(obj instanceof Field)) { return false; } return super.equals(obj); } @Override protected String getDisplayFormat() { return "%s:%s"; } } private static final Logger logger = LogManager.getLogger("mixin"); private static final Profiler profiler = MixinEnvironment.getProfiler(); private static final String JAVA_LANG_OBJECT = "java/lang/Object"; /** * Loading and parsing classes is expensive, so keep a cache of all the * information we generate */ private static final Map<String, ClassInfo> cache = new HashMap<String, ClassInfo>(); private static final ClassInfo OBJECT = new ClassInfo(); static { ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT); } /** * Class name (binary name) */ private final String name; /** * Class superclass name (binary name) */ private final String superName; /** * Outer class name */ private final String outerName; /** * True either if this is not an inner class or if it is an inner class but * does not contain a reference to its outer class. */ private final boolean isProbablyStatic; /** * Interfaces */ private final Set<String> interfaces; /** * Constructors and initialisers in this class */ private final Set<Method> initialisers; /** * Methods in this class */ private final Set<Method> methods; /** * Public and protected fields in this class */ private final Set<Field> fields; /** * Mixins which target this class */ private final Set<MixinInfo> mixins; /** * Map of mixin types to corresponding supertypes, to avoid repeated * lookups */ private final Map<ClassInfo, ClassInfo> correspondingTypes = new HashMap<ClassInfo, ClassInfo>(); /** * Mixin info if this class is a mixin itself */ private final MixinInfo mixin; private final MethodMapper methodMapper; /** * True if this is a mixin rather than a class */ private final boolean isMixin; /** * True if this is an interface */ private final boolean isInterface; /** * Access flags */ private final int access; /** * Superclass reference, not initialised until required */ private ClassInfo superClass; /** * Outer class reference, not initialised until required */ private ClassInfo outerClass; /** * Class signature, lazy-loaded where possible */ private ClassSignature signature; /** * Mixins which have been applied this class */ private Set<MixinInfo> appliedMixins; /** * Private constructor used to initialise the ClassInfo for {@link Object} */ private ClassInfo() { this.name = ClassInfo.JAVA_LANG_OBJECT; this.superName = null; this.outerName = null; this.isProbablyStatic = true; this.initialisers = ImmutableSet.<Method>of( new Method("<init>", "()V") ); this.methods = ImmutableSet.<Method>of( new Method("getClass", "()Ljava/lang/Class;"), new Method("hashCode", "()I"), new Method("equals", "(Ljava/lang/Object;)Z"), new Method("clone", "()Ljava/lang/Object;"), new Method("toString", "()Ljava/lang/String;"), new Method("notify", "()V"), new Method("notifyAll", "()V"), new Method("wait", "(J)V"), new Method("wait", "(JI)V"), new Method("wait", "()V"), new Method("finalize", "()V") ); this.fields = Collections.<Field>emptySet(); this.isInterface = false; this.interfaces = Collections.<String>emptySet(); this.access = Opcodes.ACC_PUBLIC; this.isMixin = false; this.mixin = null; this.mixins = Collections.<MixinInfo>emptySet(); this.methodMapper = null; } /** * Initialise a ClassInfo from the supplied {@link ClassNode} * * @param classNode Class node to inspect */ private ClassInfo(ClassNode classNode) { Section timer = ClassInfo.profiler.begin(Profiler.ROOT, "class.meta"); try { this.name = classNode.name; this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT; this.initialisers = new HashSet<Method>(); this.methods = new HashSet<Method>(); this.fields = new HashSet<Field>(); this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0); this.interfaces = new HashSet<String>(); this.access = classNode.access; this.isMixin = classNode instanceof MixinClassNode; this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; this.mixins = this.isMixin ? Collections.<MixinInfo>emptySet() : new HashSet<MixinInfo>(); this.interfaces.addAll(classNode.interfaces); for (MethodNode method : classNode.methods) { this.addMethod(method, this.isMixin); } boolean isProbablyStatic = true; String outerName = classNode.outerClass; for (FieldNode field : classNode.fields) { if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) { if (field.name.startsWith("this$")) { isProbablyStatic = false; if (outerName == null) { outerName = field.desc; if (outerName != null && outerName.startsWith("L")) { outerName = outerName.substring(1, outerName.length() - 1); } } } } this.fields.add(new Field(field, this.isMixin)); } this.isProbablyStatic = isProbablyStatic; this.outerName = outerName; this.methodMapper = new MethodMapper(MixinEnvironment.getCurrentEnvironment(), this); this.signature = ClassSignature.ofLazy(classNode); } finally { timer.end(); } } void addInterface(String iface) { this.interfaces.add(iface); this.getSignature().addInterface(iface); } void addMethod(MethodNode method) { this.addMethod(method, true); } private void addMethod(MethodNode method, boolean injected) { if (method.name.startsWith("<")) { this.initialisers.add(new Method(method, injected)); } else { this.methods.add(new Method(method, injected)); } } /** * Add a mixin which targets this class */ void addMixin(MixinInfo mixin) { if (this.isMixin) { throw new IllegalArgumentException("Cannot add target " + this.name + " for " + mixin.getClassName() + " because the target is a mixin"); } this.mixins.add(mixin); } /** * Add a mixin which has been applied to this class */ void addAppliedMixin(MixinInfo mixin) { if (this.appliedMixins == null) { this.appliedMixins = new HashSet<MixinInfo>(); } this.appliedMixins.add(mixin); } /** * Get all mixins which target this class */ Set<MixinInfo> getMixins() { return this.isMixin ? Collections.<MixinInfo>emptySet() : Collections.<MixinInfo>unmodifiableSet(this.mixins); } /** * Get all mixins which have been successfully applied to this class */ public Set<IMixinInfo> getAppliedMixins() { return this.appliedMixins != null ? Collections.<IMixinInfo>unmodifiableSet(this.appliedMixins) : Collections.<IMixinInfo>emptySet(); } /** * Get whether this class is a mixin */ public boolean isMixin() { return this.isMixin; } /** * Get whether this class is loadable mixin */ public boolean isLoadable() { return this.mixin != null && this.mixin.isLoadable(); } /** * Get whether this class has ACC_PUBLIC */ public boolean isPublic() { return (this.access & Opcodes.ACC_PUBLIC) != 0; } /** * Get whether this class has ACC_ABSTRACT */ public boolean isAbstract() { return (this.access & Opcodes.ACC_ABSTRACT) != 0; } /** * Get whether this class has ACC_SYNTHETIC */ public boolean isSynthetic() { return (this.access & Opcodes.ACC_SYNTHETIC) != 0; } /** * Get whether this class is probably static (or is not an inner class) */ public boolean isProbablyStatic() { return this.isProbablyStatic; } /** * Get whether this class is an inner class */ public boolean isInner() { return this.outerName != null; } /** * Get whether this is an interface or not */ public boolean isInterface() { return this.isInterface; } /** * Returns the answer to life, the universe and everything */ public Set<String> getInterfaces() { return Collections.<String>unmodifiableSet(this.interfaces); } @Override public String toString() { return this.name; } MethodMapper getMethodMapper() { return this.methodMapper; } public int getAccess() { return this.access; } /** * Get the class name (binary name) */ public String getName() { return this.name; } /** * Get the class name (java format) */ public String getClassName() { return this.name.replace('/', '.'); } /** * Get the class name (simple name, java format) */ public String getSimpleName() { int pos = this.name.lastIndexOf('/'); return pos < 0 ? this.name : this.name.substring(pos + 1); } /** * Get the object type (ASM type) */ public org.objectweb.asm.Type getType() { return org.objectweb.asm.Type.getObjectType(this.name); } /** * Get the superclass name (binary name) */ public String getSuperName() { return this.superName; } /** * Get the superclass info, can return null if the superclass cannot be * resolved */ public ClassInfo getSuperClass() { if (this.superClass == null && this.superName != null) { this.superClass = ClassInfo.forName(this.superName); } return this.superClass; } /** * Get the name of the outer class, or null if this is not an inner class */ public String getOuterName() { return this.outerName; } /** * Get the outer class info, can return null if the outer class cannot be * resolved or if this is not an inner class */ public ClassInfo getOuterClass() { if (this.outerClass == null && this.outerName != null) { this.outerClass = ClassInfo.forName(this.outerName); } return this.outerClass; } /** * Return the class signature * * @return signature as a {@link ClassSignature} instance */ public ClassSignature getSignature() { return this.signature.wake(); } /** * Class targets */ List<ClassInfo> getTargets() { if (this.mixin != null) { List<ClassInfo> targets = new ArrayList<ClassInfo>(); targets.add(this); targets.addAll(this.mixin.getTargets()); return targets; } return ImmutableList.<ClassInfo>of(this); } /** * Get class/interface methods * * @return read-only view of class methods */ public Set<Method> getMethods() { return Collections.<Method>unmodifiableSet(this.methods); } /** * If this is an interface, returns a set containing all methods in this * interface and all super interfaces. If this is a class, returns a set * containing all methods for all interfaces implemented by this class and * all super interfaces of those interfaces. * * @param includeMixins Whether to include methods from mixins targeting * this class info * @return read-only view of class methods */ public Set<Method> getInterfaceMethods(boolean includeMixins) { Set<Method> methods = new HashSet<Method>(); ClassInfo supClass = this.addMethodsRecursive(methods, includeMixins); if (!this.isInterface) { while (supClass != null && supClass != ClassInfo.OBJECT) { supClass = supClass.addMethodsRecursive(methods, includeMixins); } } // Remove default methods. for (Iterator<Method> it = methods.iterator(); it.hasNext();) { if (!it.next().isAbstract()) { it.remove(); } } return Collections.<Method>unmodifiableSet(methods); } /** * Recursive function used by {@link #getInterfaceMethods} to add all * interface methods to the supplied set * * @param methods Method set to add to * @param includeMixins Whether to include methods from mixins targeting * this class info * @return superclass reference, used to make the code above more fluent */ private ClassInfo addMethodsRecursive(Set<Method> methods, boolean includeMixins) { if (this.isInterface) { for (Method method : this.methods) { // Default methods take priority. They are removed later. if (!method.isAbstract()) { // Remove the old method so the new one is added. methods.remove(method); } methods.add(method); } } else if (!this.isMixin && includeMixins) { for (MixinInfo mixin : this.mixins) { mixin.getClassInfo().addMethodsRecursive(methods, includeMixins); } } for (String iface : this.interfaces) { ClassInfo.forName(iface).addMethodsRecursive(methods, includeMixins); } return this.getSuperClass(); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(Class<?> superClass) { return this.hasSuperClass(superClass, Traversal.NONE, superClass.isInterface()); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(Class<?> superClass, Traversal traversal) { return this.hasSuperClass(superClass, traversal, superClass.isInterface()); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @param includeInterfaces True to include interfaces in the lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(Class<?> superClass, Traversal traversal, boolean includeInterfaces) { String internalName = org.objectweb.asm.Type.getInternalName(superClass); if (ClassInfo.JAVA_LANG_OBJECT.equals(internalName)) { return true; } return this.findSuperClass(internalName, traversal) != null; } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass) { return this.hasSuperClass(superClass, Traversal.NONE, false); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass, Traversal traversal) { return this.hasSuperClass(superClass, traversal, false); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Name of the superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @param includeInterfaces True to include interfaces in the lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(String superClass, Traversal traversal, boolean includeInterfaces) { if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) { return true; } return this.findSuperClass(superClass, traversal) != null; } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass) { return this.hasSuperClass(superClass, Traversal.NONE, false); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) { return this.hasSuperClass(superClass, traversal, false); } /** * Test whether this class has the specified superclass in its hierarchy * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @param includeInterfaces True to include interfaces in the lookup * @return true if the specified class appears in the class's hierarchy * anywhere */ public boolean hasSuperClass(ClassInfo superClass, Traversal traversal, boolean includeInterfaces) { if (ClassInfo.OBJECT == superClass) { return true; } return this.findSuperClass(superClass.name, traversal, includeInterfaces) != null; } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass) { return this.findSuperClass(superClass, Traversal.NONE); } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @param traversal Traversal type to allow during this lookup * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass, Traversal traversal) { return this.findSuperClass(superClass, traversal, false, new HashSet<String>()); } /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null * * @param superClass Superclass name to search for * @param traversal Traversal type to allow during this lookup * @param includeInterfaces True to include interfaces in the lookup * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass, Traversal traversal, boolean includeInterfaces) { if (ClassInfo.OBJECT.name.equals(superClass)) { return null; } return this.findSuperClass(superClass, traversal, includeInterfaces, new HashSet<String>()); } private ClassInfo findSuperClass(String superClass, Traversal traversal, boolean includeInterfaces, Set<String> traversed) { ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { for (ClassInfo superTarget : superClassInfo.getTargets()) { if (superClass.equals(superTarget.getName())) { return superClassInfo; } ClassInfo found = superTarget.findSuperClass(superClass, traversal.next(), includeInterfaces, traversed); if (found != null) { return found; } } } if (includeInterfaces) { ClassInfo iface = this.findInterface(superClass); if (iface != null) { return iface; } } if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { String mixinClassName = mixin.getClassName(); if (traversed.contains(mixinClassName)) { continue; } traversed.add(mixinClassName); ClassInfo mixinClass = mixin.getClassInfo(); if (superClass.equals(mixinClass.getName())) { return mixinClass; } ClassInfo targetSuper = mixinClass.findSuperClass(superClass, Traversal.ALL, includeInterfaces, traversed); if (targetSuper != null) { return targetSuper; } } } return null; } private ClassInfo findInterface(String superClass) { for (String ifaceName : this.getInterfaces()) { ClassInfo iface = ClassInfo.forName(ifaceName); if (superClass.equals(ifaceName)) { return iface; } ClassInfo superIface = iface.findInterface(superClass); if (superIface != null) { return superIface; } } return null; } /** * Walks up this class's hierarchy to find the first class targetted by the * specified mixin. This is used during mixin application to translate a * mixin reference to a "real class" reference <em>in the context of <b>this * </b> class</em>. * * @param mixin Mixin class to search for * @return corresponding (target) class for the specified mixin or null if * no corresponding mixin was found */ ClassInfo findCorrespondingType(ClassInfo mixin) { if (mixin == null || !mixin.isMixin || this.isMixin) { return null; } ClassInfo correspondingType = this.correspondingTypes.get(mixin); if (correspondingType == null) { correspondingType = this.findSuperTypeForMixin(mixin); this.correspondingTypes.put(mixin, correspondingType); } return correspondingType; } /* (non-Javadoc) * Only used by findCorrespondingType(), used as a convenience so that * sanity checks and caching can be handled more elegantly */ private ClassInfo findSuperTypeForMixin(ClassInfo mixin) { ClassInfo superClass = this; while (superClass != null && superClass != ClassInfo.OBJECT) { for (MixinInfo minion : superClass.mixins) { if (minion.getClassInfo().equals(mixin)) { return superClass; } } superClass = superClass.getSuperClass(); } return null; } /** * Find out whether this (mixin) class has another mixin in its superclass * hierarchy. This method always returns false for non-mixin classes. * * @return true if and only if one or more mixins are found in the hierarchy * of this mixin */ public boolean hasMixinInHierarchy() { if (!this.isMixin) { return false; } ClassInfo supClass = this.getSuperClass(); while (supClass != null && supClass != ClassInfo.OBJECT) { if (supClass.isMixin) { return true; } supClass = supClass.getSuperClass(); } return false; } /** * Find out whether this (non-mixin) class has a mixin targetting * <em>any</em> of its superclasses. This method always returns false for * mixin classes. * * @return true if and only if one or more classes in this class's hierarchy * are targetted by a mixin */ public boolean hasMixinTargetInHierarchy() { if (this.isMixin) { return false; } ClassInfo supClass = this.getSuperClass(); while (supClass != null && supClass != ClassInfo.OBJECT) { if (supClass.mixins.size() > 0) { return true; } supClass = supClass.getSuperClass(); } return false; } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param searchType Search strategy to use * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, SearchType searchType) { return this.findMethodInHierarchy(method.name, method.desc, searchType, Traversal.NONE); } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, SearchType searchType, Traversal traversal) { return this.findMethodInHierarchy(method.name, method.desc, searchType, traversal, 0); } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param searchType Search strategy to use * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, SearchType searchType, int flags) { return this.findMethodInHierarchy(method.name, method.desc, searchType, Traversal.NONE, flags); } /** * Finds the specified private or protected method in this class's hierarchy * * @param method Method to search for * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodNode method, SearchType searchType, Traversal traversal, int flags) { return this.findMethodInHierarchy(method.name, method.desc, searchType, traversal, flags); } /** * Finds the specified public or protected method in this class's hierarchy * * @param method Method to search for * @param searchType Search strategy to use * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodInsnNode method, SearchType searchType) { return this.findMethodInHierarchy(method.name, method.desc, searchType, Traversal.NONE); } /** * Finds the specified public or protected method in this class's hierarchy * * @param method Method to search for * @param searchType Search strategy to use * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(MethodInsnNode method, SearchType searchType, int flags) { return this.findMethodInHierarchy(method.name, method.desc, searchType, Traversal.NONE, flags); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param searchType Search strategy to use * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, SearchType searchType, int flags) { return this.findMethodInHierarchy(name, desc, searchType, Traversal.NONE, flags); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, SearchType searchType, Traversal traversal) { return this.findMethodInHierarchy(name, desc, searchType, traversal, 0); } /** * Finds the specified public or protected method in this class's hierarchy * * @param name Method name to search for * @param desc Method descriptor * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethodInHierarchy(String name, String desc, SearchType searchType, Traversal traversal, int flags) { return this.findInHierarchy(name, desc, searchType, traversal, flags, Type.METHOD); } /** * Finds the specified private or protected field in this class's hierarchy * * @param field Field to search for * @param searchType Search strategy to use * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldNode field, SearchType searchType) { return this.findFieldInHierarchy(field.name, field.desc, searchType, Traversal.NONE); } /** * Finds the specified private or protected field in this class's hierarchy * * @param field Field to search for * @param searchType Search strategy to use * @param flags search flags * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldNode field, SearchType searchType, int flags) { return this.findFieldInHierarchy(field.name, field.desc, searchType, Traversal.NONE, flags); } /** * Finds the specified public or protected field in this class's hierarchy * * @param field Field to search for * @param searchType Search strategy to use * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldInsnNode field, SearchType searchType) { return this.findFieldInHierarchy(field.name, field.desc, searchType, Traversal.NONE); } /** * Finds the specified public or protected field in this class's hierarchy * * @param field Field to search for * @param searchType Search strategy to use * @param flags search flags * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(FieldInsnNode field, SearchType searchType, int flags) { return this.findFieldInHierarchy(field.name, field.desc, searchType, Traversal.NONE, flags); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param searchType Search strategy to use * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, SearchType searchType) { return this.findFieldInHierarchy(name, desc, searchType, Traversal.NONE); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param searchType Search strategy to use * @param flags search flags * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, SearchType searchType, int flags) { return this.findFieldInHierarchy(name, desc, searchType, Traversal.NONE, flags); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, SearchType searchType, Traversal traversal) { return this.findFieldInHierarchy(name, desc, searchType, traversal, 0); } /** * Finds the specified public or protected field in this class's hierarchy * * @param name Field name to search for * @param desc Field descriptor * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @param flags search flags * @return the field object or null if the field could not be resolved */ public Field findFieldInHierarchy(String name, String desc, SearchType searchType, Traversal traversal, int flags) { return this.findInHierarchy(name, desc, searchType, traversal, flags, Type.FIELD); } /** * Finds a public or protected member in the hierarchy of this class which * matches the supplied details * * @param name Member name to search * @param desc Member descriptor * @param searchType Search strategy to use * @param traversal Traversal type to allow during this lookup * @param flags Inclusion flags * @param type Type of member to search for (field or method) * @return the discovered member or null if the member could not be resolved */ @SuppressWarnings("unchecked") private <M extends Member> M findInHierarchy(String name, String desc, SearchType searchType, Traversal traversal, int flags, Type type) { if (searchType == SearchType.ALL_CLASSES) { M member = this.findMember(name, desc, flags, type); if (member != null) { return member; } if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { M mixinMember = mixin.getClassInfo().findMember(name, desc, flags, type); if (mixinMember != null) { return this.cloneMember(mixinMember); } } } } ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { for (ClassInfo superTarget : superClassInfo.getTargets()) { M member = superTarget.findInHierarchy(name, desc, SearchType.ALL_CLASSES, traversal.next(), flags & ~ClassInfo.INCLUDE_PRIVATE, type); if (member != null) { return member; } } } if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES))) { for (String implemented : this.interfaces) { ClassInfo iface = ClassInfo.forName(implemented); if (iface == null) { ClassInfo.logger.debug("Failed to resolve declared interface {} on {}", implemented, this.name); continue; // throw new RuntimeException(new ClassNotFoundException(implemented)); } M member = iface.findInHierarchy(name, desc, SearchType.ALL_CLASSES, traversal.next(), flags & ~ClassInfo.INCLUDE_PRIVATE, type); if (member != null) { return this.isInterface ? member : (M)new InterfaceMethod(member); } } } return null; } /** * Effectively a clone method for member, placed here so that the enclosing * instance for the inner class is this class and not the enclosing instance * of the existing class. Basically creates a cloned member with this * ClassInfo as its parent. * * @param member member to clone * @return wrapper member */ @SuppressWarnings("unchecked") private <M extends Member> M cloneMember(M member) { if (member instanceof Method) { return (M)new Method(member); } return (M)new Field(member); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method) { return this.findMethod(method.name, method.desc, method.access); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method, int flags) { return this.findMethod(method.name, method.desc, flags); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method) { return this.findMethod(method.name, method.desc, 0); } /** * Finds the specified public or protected method in this class * * @param method Method to search for * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method, int flags) { return this.findMethod(method.name, method.desc, flags); } /** * Finds the specified public or protected method in this class * * @param name Method name to search for * @param desc Method signature to search for * @param flags search flags * @return the method object or null if the method could not be resolved */ public Method findMethod(String name, String desc, int flags) { return this.findMember(name, desc, flags, Type.METHOD); } /** * Finds the specified field in this class * * @param field Field to search for * @return the field object or null if the field could not be resolved */ public Field findField(FieldNode field) { return this.findField(field.name, field.desc, field.access); } /** * Finds the specified public or protected method in this class * * @param field Field to search for * @param flags search flags * @return the field object or null if the field could not be resolved */ public Field findField(FieldInsnNode field, int flags) { return this.findField(field.name, field.desc, flags); } /** * Finds the specified field in this class * * @param name Field name to search for * @param desc Field signature to search for * @param flags search flags * @return the field object or null if the field could not be resolved */ public Field findField(String name, String desc, int flags) { return this.findMember(name, desc, flags, Type.FIELD); } /** * Finds the specified member in this class * * @param name Field name to search for * @param desc Field signature to search for * @param flags search flags * @param memberType Type of member list to search * @return the field object or null if the field could not be resolved */ @SuppressWarnings("unchecked") private <M extends Member> M findMember(String name, String desc, int flags, Type memberType) { Set<M> members = (Set<M>)(memberType == Type.METHOD ? this.methods : this.fields); for (M member : members) { if (member.equals(name, desc) && member.matchesFlags(flags)) { return member; } } if (memberType == Type.METHOD && (flags & ClassInfo.INCLUDE_INITIALISERS) != 0) { for (Method ctor : this.initialisers) { if (ctor.equals(name, desc) && ctor.matchesFlags(flags)) { return (M)ctor; } } } return null; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { if (!(other instanceof ClassInfo)) { return false; } return ((ClassInfo)other).name.equals(this.name); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.name.hashCode(); } /** * Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for * the class was already defined, then the original ClassInfo is returned * from the internal cache. Otherwise a new ClassInfo is created and * returned. * * @param classNode classNode to get info for * @return ClassInfo instance for the supplied classNode */ static ClassInfo fromClassNode(ClassNode classNode) { ClassInfo info = ClassInfo.cache.get(classNode.name); if (info == null) { info = new ClassInfo(classNode); ClassInfo.cache.put(classNode.name, info); } return info; } /** * Return a ClassInfo for the specified class name, fetches the ClassInfo * from the cache where possible. * * @param className Binary name of the class to look up * @return ClassInfo for the specified class name or null if the specified * name cannot be resolved for some reason */ public static ClassInfo forName(String className) { className = className.replace('.', '/'); ClassInfo info = ClassInfo.cache.get(className); if (info == null) { try { ClassNode classNode = MixinService.getService().getBytecodeProvider().getClassNode(className); info = new ClassInfo(classNode); } catch (Exception ex) { ClassInfo.logger.catching(Level.TRACE, ex); ClassInfo.logger.warn("Error loading class: {} ({}: {})", className, ex.getClass().getName(), ex.getMessage()); // ex.printStackTrace(); } // Put null in the cache if load failed ClassInfo.cache.put(className, info); ClassInfo.logger.trace("Added class metadata for {} to metadata cache", className); } return info; } /** * Return a ClassInfo for the specified type descriptor, fetches the * ClassInfo from the cache where possible. * * @param descriptor Internal descriptor of the type to inspect * @param lookup Lookup type to use (literal/element) * @return ClassInfo for the specified class name or null if the specified * name cannot be resolved for some reason */ public static ClassInfo forDescriptor(String descriptor, TypeLookup lookup) { org.objectweb.asm.Type type; try { type = org.objectweb.asm.Type.getObjectType(descriptor); } catch (IllegalArgumentException ex) { ClassInfo.logger.warn("Error resolving type from descriptor: {}", descriptor); return null; } return ClassInfo.forType(type, lookup); } /** * Return a ClassInfo for the specified class type, fetches the ClassInfo * from the cache where possible and generates the class meta if not. * * @param type Type to look up * @param lookup Lookup type to use (literal/element) * @return ClassInfo for the supplied type or null if the supplied type * cannot be found or is a primitive type */ public static ClassInfo forType(org.objectweb.asm.Type type, TypeLookup lookup) { if (type.getSort() == org.objectweb.asm.Type.ARRAY) { if (lookup == TypeLookup.ELEMENT_TYPE) { return ClassInfo.forType(type.getElementType(), TypeLookup.ELEMENT_TYPE); } return ClassInfo.OBJECT; } else if (type.getSort() < org.objectweb.asm.Type.ARRAY) { return null; } return ClassInfo.forName(type.getClassName().replace('.', '/')); } /** * Return a ClassInfo for the specified class name, but only if the class * information already exists in the cache. This prevents class loads in the * instance that a ClassInfo is only being retrieved for a class which * should definitely have already been processed but will be missing in case * of an error condition. * * @param className Binary name of the class to look up * @return ClassInfo for the specified class name or null if the specified * class does not have an entry in the cache */ public static ClassInfo fromCache(String className) { return ClassInfo.cache.get(className.replace('.', '/')); } /** * Return a ClassInfo for the specified class type, but only if the class * information already exists in the cache. This prevents class loads in the * instance that a ClassInfo is only being retrieved for a class which * should definitely have already been processed but will be missing in case * of an error condition. * * @param type Type to look up * @param lookup Lookup type to use (literal/element) * @return ClassInfo for the supplied type or null if the supplied type * does not have an entry in the cache */ public static ClassInfo fromCache(org.objectweb.asm.Type type, TypeLookup lookup) { if (type.getSort() == org.objectweb.asm.Type.ARRAY) { if (lookup == TypeLookup.ELEMENT_TYPE) { return ClassInfo.fromCache(type.getElementType(), TypeLookup.ELEMENT_TYPE); } return ClassInfo.OBJECT; } else if (type.getSort() < org.objectweb.asm.Type.ARRAY) { return null; } return ClassInfo.fromCache(type.getClassName()); } /** * ASM logic applied via ClassInfo, returns first common superclass of * classes specified by <tt>type1</tt> and <tt>type2</tt>. * * @param type1 First type * @param type2 Second type * @return common superclass info */ public static ClassInfo getCommonSuperClass(String type1, String type2) { if (type1 == null || type2 == null) { return ClassInfo.OBJECT; } return ClassInfo.getCommonSuperClass(ClassInfo.forName(type1), ClassInfo.forName(type2)); } /** * ASM logic applied via ClassInfo, returns first common superclass of * classes specified by <tt>type1</tt> and <tt>type2</tt>. * * @param type1 First type * @param type2 Second type * @return common superclass info */ public static ClassInfo getCommonSuperClass(org.objectweb.asm.Type type1, org.objectweb.asm.Type type2) { if (type1 == null || type2 == null || type1.getSort() != org.objectweb.asm.Type.OBJECT || type2.getSort() != org.objectweb.asm.Type.OBJECT) { return ClassInfo.OBJECT; } return ClassInfo.getCommonSuperClass(ClassInfo.forType(type1, TypeLookup.DECLARED_TYPE), ClassInfo.forType(type2, TypeLookup.DECLARED_TYPE)); } /** * ASM logic applied via ClassInfo, returns first common superclass of * classes specified by <tt>type1</tt> and <tt>type2</tt>. * * @param type1 First type * @param type2 Second type * @return common superclass info */ private static ClassInfo getCommonSuperClass(ClassInfo type1, ClassInfo type2) { return ClassInfo.getCommonSuperClass(type1, type2, false); } /** * ASM logic applied via ClassInfo, returns first common superclass of * classes specified by <tt>type1</tt> and <tt>type2</tt>. * * @param type1 First type * @param type2 Second type * @return common superclass info */ public static ClassInfo getCommonSuperClassOrInterface(String type1, String type2) { if (type1 == null || type2 == null) { return ClassInfo.OBJECT; } return ClassInfo.getCommonSuperClassOrInterface(ClassInfo.forName(type1), ClassInfo.forName(type2)); } /** * ASM logic applied via ClassInfo, returns first common superclass of * classes specified by <tt>type1</tt> and <tt>type2</tt>. * * @param type1 First type * @param type2 Second type * @return common superclass info */ public static ClassInfo getCommonSuperClassOrInterface(org.objectweb.asm.Type type1, org.objectweb.asm.Type type2) { if (type1 == null || type2 == null || type1.getSort() != org.objectweb.asm.Type.OBJECT || type2.getSort() != org.objectweb.asm.Type.OBJECT) { return ClassInfo.OBJECT; } return ClassInfo.getCommonSuperClassOrInterface(ClassInfo.forType(type1, TypeLookup.DECLARED_TYPE), ClassInfo.forType(type2, TypeLookup.DECLARED_TYPE)); } /** * ASM logic applied via ClassInfo, returns first common superclass or * interface of classes specified by <tt>type1</tt> and <tt>type2</tt>. * * @param type1 First type * @param type2 Second type * @return common superclass info */ public static ClassInfo getCommonSuperClassOrInterface(ClassInfo type1, ClassInfo type2) { return ClassInfo.getCommonSuperClass(type1, type2, true); } private static ClassInfo getCommonSuperClass(ClassInfo type1, ClassInfo type2, boolean includeInterfaces) { if (type1.hasSuperClass(type2, Traversal.NONE, includeInterfaces)) { return type2; } else if (type2.hasSuperClass(type1, Traversal.NONE, includeInterfaces)) { return type1; } else if (type1.isInterface() || type2.isInterface()) { return ClassInfo.OBJECT; } do { type1 = type1.getSuperClass(); if (type1 == null) { return ClassInfo.OBJECT; } } while (!type2.hasSuperClass(type1, Traversal.NONE, includeInterfaces)); return type1; } }
34.273759
149
0.6147
1e4ef7f7bb4239eca3dce495c41f04553b11d263
11,113
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.test; import com.google.common.collect.ImmutableList; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.model.ConfigModelRegistry; import com.yahoo.config.model.NullConfigModelRegistry; import com.yahoo.config.model.api.HostProvisioner; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.provision.Host; import com.yahoo.config.model.provision.Hosts; import com.yahoo.config.model.provision.InMemoryProvisioner; import com.yahoo.config.model.provision.SingleNodeProvisioner; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Capacity; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Flavor; import com.yahoo.config.provision.HostSpec; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.ProvisionLogger; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.yahoo.vespa.model.test.utils.ApplicationPackageUtils.generateSchemas; /** * Helper class which sets up a system with multiple hosts. * Usage: * <code> * VespaModelTester tester = new VespaModelTester(); * tester.addHosts(count, flavor); * ... add more nodes * VespaModel model = tester.createModel(servicesString); * ... assert on model * </code> * * @author bratseth */ public class VespaModelTester { private final ConfigModelRegistry configModelRegistry; private boolean hosted = true; private final Map<NodeResources, Collection<Host>> hostsByResources = new HashMap<>(); private ApplicationId applicationId = ApplicationId.defaultId(); private boolean useDedicatedNodeForLogserver = false; private HostProvisioner provisioner; public VespaModelTester() { this(new NullConfigModelRegistry()); } public VespaModelTester(ConfigModelRegistry configModelRegistry) { this.configModelRegistry = configModelRegistry; } public HostProvisioner provisioner() { if (provisioner instanceof ProvisionerAdapter) return ((ProvisionerAdapter)provisioner).provisioner(); return provisioner; } /** Adds some nodes with resources 1, 3, 10 */ public Hosts addHosts(int count) { return addHosts(InMemoryProvisioner.defaultResources, count); } public Hosts addHosts(NodeResources resources, int count) { return addHosts(Optional.of(new Flavor(resources)), resources, count); } private Hosts addHosts(Optional<Flavor> flavor, NodeResources resources, int count) { List<Host> hosts = new ArrayList<>(); for (int i = 0; i < count; ++i) { // Let host names sort in the opposite order of the order the hosts are added // This allows us to test index vs. name order selection when subsets of hosts are selected from a cluster // (for e.g cluster controllers and slobrok nodes) String hostname = String.format("%s-%02d", "node" + "-" + Math.round(resources.vcpu()) + "-" + Math.round(resources.memoryGb()) + "-" + Math.round(resources.diskGb()), count - i); hosts.add(new Host(hostname, ImmutableList.of(), flavor)); } this.hostsByResources.put(resources, hosts); if (hosts.size() > 100) throw new IllegalStateException("The host naming scheme is nameNN. To test more than 100 hosts, change to nameNNN"); return new Hosts(hosts); } /** Sets whether this sets up a model for a hosted system. Default: true */ public void setHosted(boolean hosted) { this.hosted = hosted; } /** Sets the tenant, application name, and instance name of the model being built. */ public void setApplicationId(String tenant, String applicationName, String instanceName) { applicationId = ApplicationId.from(tenant, applicationName, instanceName); } public void useDedicatedNodeForLogserver(boolean useDedicatedNodeForLogserver) { this.useDedicatedNodeForLogserver = useDedicatedNodeForLogserver; } /** Creates a model which uses 0 as start index and fails on out of capacity */ public VespaModel createModel(String services, String ... retiredHostNames) { return createModel(Zone.defaultZone(), services, true, retiredHostNames); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(String services, boolean failOnOutOfCapacity, String ... retiredHostNames) { return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, 0, Optional.empty(), new DeployState.Builder(), retiredHostNames); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(String services, boolean failOnOutOfCapacity, DeployState.Builder builder) { return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, 0, Optional.empty(), builder); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(String services, boolean failOnOutOfCapacity, boolean useMaxResources, String ... retiredHostNames) { return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, useMaxResources, false, 0, Optional.empty(), new DeployState.Builder(), retiredHostNames); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(String services, boolean failOnOutOfCapacity, boolean useMaxResources, boolean alwaysReturnOneNode, String ... retiredHostNames) { return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, useMaxResources, alwaysReturnOneNode, 0, Optional.empty(), new DeployState.Builder(), retiredHostNames); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(String services, boolean failOnOutOfCapacity, int startIndexForClusters, String ... retiredHostNames) { return createModel(Zone.defaultZone(), services, failOnOutOfCapacity, false, false, startIndexForClusters, Optional.empty(), new DeployState.Builder(), retiredHostNames); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, String ... retiredHostNames) { return createModel(zone, services, failOnOutOfCapacity, false, false, 0, Optional.empty(), new DeployState.Builder(), retiredHostNames); } /** Creates a model which uses 0 as start index */ public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, DeployState.Builder deployStateBuilder, String ... retiredHostNames) { return createModel(zone, services, failOnOutOfCapacity, false, false, 0, Optional.empty(), deployStateBuilder, retiredHostNames); } /** * Creates a model using the hosts already added to this * * @param services the services xml string * @param useMaxResources false to use the minmal resources (when given a range), true to use max * @param failOnOutOfCapacity whether we should get an exception when not enough hosts of the requested flavor * is available or if we should just silently receive a smaller allocation * @return the resulting model */ public VespaModel createModel(Zone zone, String services, boolean failOnOutOfCapacity, boolean useMaxResources, boolean alwaysReturnOneNode, int startIndexForClusters, Optional<VespaModel> previousModel, DeployState.Builder deployStatebuilder, String ... retiredHostNames) { VespaModelCreatorWithMockPkg modelCreatorWithMockPkg = new VespaModelCreatorWithMockPkg(null, services, generateSchemas("type1")); ApplicationPackage appPkg = modelCreatorWithMockPkg.appPkg; provisioner = hosted ? new ProvisionerAdapter(new InMemoryProvisioner(hostsByResources, failOnOutOfCapacity, useMaxResources, alwaysReturnOneNode, false, startIndexForClusters, retiredHostNames)) : new SingleNodeProvisioner(); TestProperties properties = new TestProperties() .setMultitenant(hosted) // Note: system tests are multitenant but not hosted .setHostedVespa(hosted) .setApplicationId(applicationId) .setUseDedicatedNodeForLogserver(useDedicatedNodeForLogserver); DeployState.Builder deployState = deployStatebuilder .applicationPackage(appPkg) .modelHostProvisioner(provisioner) .properties(properties) .zone(zone); previousModel.ifPresent(deployState::previousModel); return modelCreatorWithMockPkg.create(false, deployState.build(), configModelRegistry); } /** To verify that we don't call allocateHost(alias) in hosted environments */ private static class ProvisionerAdapter implements HostProvisioner { private final InMemoryProvisioner provisioner; public ProvisionerAdapter(InMemoryProvisioner provisioner) { this.provisioner = provisioner; } public InMemoryProvisioner provisioner() { return provisioner; } @Override public HostSpec allocateHost(String alias) { throw new UnsupportedOperationException("Allocating hosts using <node> tags is not supported in hosted environments, " + "use <nodes count='N'> instead, see https://cloud.vespa.ai/en/reference/services"); } @Override public List<HostSpec> prepare(ClusterSpec cluster, Capacity capacity, ProvisionLogger logger) { return provisioner.prepare(cluster, capacity, logger); } } }
49.834081
164
0.660488
065d82fda65bdf4d8bc15618b7a6967be23f7dea
392
package samples.powermockito.junit4.bugs.github352; import org.junit.Test; /** * */ public class MyTest extends MyAbstractTest { //some setup code here @Override public void test1() { //some test code here } @Override public void test2() { //some test code here } @Test public void test3() { // some test code here } }
14
51
0.589286
9115a01c8f9d9bced4993c19cc7f04ccd6b6a0b1
708
package com.ctrip.framework.apollo.demo.spring; import com.ctrip.framework.apollo.demo.spring.bean.AnnotatedBean; import com.ctrip.framework.apollo.demo.spring.config.AppConfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.Scanner; /** * @author Jason Song([email protected]) */ public class AnnotationApplication { public static void main(String[] args) { new AnnotationConfigApplicationContext( AppConfig.class.getPackage().getName(), AnnotatedBean.class.getPackage().getName()); onKeyExit(); } private static void onKeyExit() { System.out.println("Press Enter to exit..."); new Scanner(System.in).nextLine(); } }
28.32
92
0.752825
b07a0c9027b722acc5ada75548a4a9b2e283bf81
9,484
/** * */ package istc.bigdawg.migration; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.net.ntp.TimeStamp; import org.apache.log4j.Logger; import istc.bigdawg.LoggerSetup; import istc.bigdawg.exceptions.MigrationException; import istc.bigdawg.postgresql.PostgreSQLConnectionInfo; import istc.bigdawg.postgresql.PostgreSQLHandler; import istc.bigdawg.postgresql.PostgreSQLSchemaTableName; import istc.bigdawg.query.ConnectionInfo; import istc.bigdawg.utils.StackTrace; import istc.bigdawg.utils.TaskExecutor; /** * Data migration between instances of PostgreSQL. * * * log table query: copy (select time,message from logs where message like * 'Migration result,%' order by time desc) to '/tmp/migration_log.csv' with * (format csv); * * * @author Adam Dziedzic * */ public class FromPostgresToPostgres extends FromDatabaseToDatabase { /* * log */ private static Logger logger = Logger .getLogger(FromPostgresToPostgres.class); /** * The objects of the class are serializable. */ private static final long serialVersionUID = 1L; /** * Always put extractor as the first task to be executed (while migrating * data from PostgreSQL to PostgreSQL). */ private static final int EXPORT_INDEX = 0; /** * Always put loader as the second task to be executed (while migrating data * from PostgreSQL to PostgreSQL) */ private static final int LOAD_INDEX = 1; public FromPostgresToPostgres(PostgreSQLConnectionInfo connectionFrom, String fromTable, PostgreSQLConnectionInfo connectionTo, String toTable) { this.migrationInfo = new MigrationInfo(connectionFrom, fromTable, connectionTo, toTable, null); } /** * Create default instance of the class. */ public FromPostgresToPostgres() { super(); } /** * Migrate data between instances of PostgreSQL. */ public MigrationResult migrate(MigrationInfo migrationInfo) throws MigrationException { logger.debug("General data migration: " + this.getClass().getName()); if (migrationInfo.getConnectionFrom() instanceof PostgreSQLConnectionInfo && migrationInfo.getConnectionTo() instanceof PostgreSQLConnectionInfo) { try { this.migrationInfo = migrationInfo; return this.dispatch(); } catch (Exception e) { logger.error(StackTrace.getFullStackTrace(e)); throw new MigrationException(e.getMessage(), e); } } return null; } /** * Create a new schema and table in the connectionTo if they do not exist. * * Get the table definition from the connectionFrom. * * @param connectionFrom * from which database we fetch the data * @param fromTable * from which table we fetch the data * @param connectionTo * to which database we connect to * @param toTable * to which table we want to load the data * @throws SQLException */ private PostgreSQLSchemaTableName createTargetTableSchema( Connection connectionFrom, Connection connectionTo) throws SQLException { /* separate schema name from the table name */ PostgreSQLSchemaTableName schemaTable = new PostgreSQLSchemaTableName( migrationInfo.getObjectTo()); /* create the target schema if it is not already there */ PostgreSQLHandler.executeStatement(connectionTo, "create schema if not exists " + schemaTable.getSchemaName()); String createTableStatement = MigrationUtils .getUserCreateStatement(migrationInfo); /* * get the create table statement for the source table from the source * database */ if (createTableStatement == null) { logger.debug( "Get the create statement for target table from the source database."); createTableStatement = PostgreSQLHandler.getCreateTable( connectionFrom, migrationInfo.getObjectFrom(), migrationInfo.getObjectTo()); } PostgreSQLHandler.executeStatement(connectionTo, createTableStatement); return schemaTable; } @Override /** * Migrate data from a local instance of the database to a remote one. */ public MigrationResult executeMigrationLocalRemote() throws MigrationException { return this.executeMigration(); } @Override /** * Migrate data between local instances of PostgreSQL. */ public MigrationResult executeMigrationLocally() throws MigrationException { return this.executeMigration(); } public MigrationResult executeMigration() throws MigrationException { TimeStamp startTimeStamp = TimeStamp.getCurrentTime(); logger.debug("start migration: " + startTimeStamp.toDateString()); long startTimeMigration = System.currentTimeMillis(); String copyFromCommand = PostgreSQLHandler .getExportBinCommand(getObjectFrom()); String copyToCommand = PostgreSQLHandler .getLoadBinCommand(getObjectTo()); Connection conFrom = null; Connection conTo = null; ExecutorService executor = null; try { conFrom = PostgreSQLHandler.getConnection(getConnectionFrom()); conTo = PostgreSQLHandler.getConnection(getConnectionTo()); conFrom.setReadOnly(true); conFrom.setAutoCommit(false); conTo.setAutoCommit(false); createTargetTableSchema(conFrom, conTo); final PipedOutputStream output = new PipedOutputStream(); final PipedInputStream input = new PipedInputStream(output); List<Callable<Object>> tasks = new ArrayList<>(); tasks.add(new ExportPostgres(conFrom, copyFromCommand, output, new PostgreSQLHandler(getConnectionTo()))); tasks.add(new LoadPostgres(conTo, migrationInfo, copyToCommand, input)); executor = Executors.newFixedThreadPool(tasks.size()); List<Future<Object>> results = TaskExecutor.execute(executor, tasks); Long countExtractedElements = (Long) results.get(EXPORT_INDEX) .get(); Long countLoadedElements = (Long) results.get(LOAD_INDEX).get(); long endTimeMigration = System.currentTimeMillis(); long durationMsec = endTimeMigration - startTimeMigration; logger.debug("migration duration time msec: " + durationMsec); MigrationResult migrationResult = new MigrationResult( countExtractedElements, countLoadedElements, durationMsec, startTimeMigration, endTimeMigration); String message = "Migration was executed correctly."; return summary(migrationResult, migrationInfo, message); } catch (Exception e) { String message = e.getMessage() + " Migration failed. Task did not finish correctly. "; logger.error(message + " Stack Trace: " + StackTrace.getFullStackTrace(e), e); if (conTo != null) { ExecutorService executorTerminator = null; try { conTo.abort(executorTerminator); } catch (SQLException ex) { String messageRollbackConTo = " Could not roll back " + "transactions in the destination database after " + "failure in data migration: " + ex.getMessage(); logger.error(messageRollbackConTo); message += messageRollbackConTo; } finally { if (executorTerminator != null) { executorTerminator.shutdownNow(); } } } if (conFrom != null) { ExecutorService executorTerminator = null; try { executorTerminator = Executors.newCachedThreadPool(); conFrom.abort(executorTerminator); } catch (SQLException ex) { String messageRollbackConFrom = " Could not roll back " + "transactions in the source database " + "after failure in data migration: " + ex.getMessage(); logger.error(messageRollbackConFrom); message += messageRollbackConFrom; } finally { if (executorTerminator != null) { executorTerminator.shutdownNow(); } } } throw new MigrationException(message, e); } finally { if (conFrom != null) { /* * calling closed on an already closed connection has no effect */ try { conFrom.close(); } catch (SQLException e) { String msg = "Could not close the source database connection."; logger.error(msg + StackTrace.getFullStackTrace(e), e); } conFrom = null; } if (conTo != null) { try { conTo.close(); } catch (SQLException e) { String msg = "Could not close the destination database connection."; logger.error(msg + StackTrace.getFullStackTrace(e), e); } conTo = null; } if (executor != null && !executor.isShutdown()) { executor.shutdownNow(); } } } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { LoggerSetup.setLogging(); System.out.println("Migrating data from PostgreSQL to PostgreSQL"); FromDatabaseToDatabase migrator = new FromPostgresToPostgres(); ConnectionInfo conInfoFrom = new PostgreSQLConnectionInfo("localhost", "5431", "mimic2", "pguser", "test"); ConnectionInfo conInfoTo = new PostgreSQLConnectionInfo("localhost", "5430", "mimic2", "pguser", "test"); MigrationResult result; try { result = migrator.migrate(conInfoFrom, "mimic2v26.d_patients", conInfoTo, "patients2"); } catch (MigrationException e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } logger.debug("Number of extracted rows: " + result.getCountExtractedElements() + " Number of loaded rows: " + result.getCountLoadedElements()); } }
32.040541
88
0.720793
9c4896e3d6c2994eeb499dbdc491cb3f56cc4568
625
package com.geekhalo.ddd.lite.codegen.support.meta; import com.squareup.javapoet.TypeName; import lombok.AccessLevel; import lombok.Setter; import org.apache.commons.lang3.StringUtils; @Setter(AccessLevel.PUBLIC) public abstract class ModelSetterMeta extends ModelMethodMeta { private TypeName type; public final TypeName type() { return this.type; } protected void merge(ModelSetterMeta n) { super.merge(n); if (n.ignore()){ setIgnore(true); } if (StringUtils.isNotEmpty(n.description())){ setDescription(n.description()); } } }
25
63
0.6688
ff2bcf42b63c83d111b675ff9ecfe7c5366b4792
3,207
/* * 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.openide.windows; import junit.framework.*; import org.openide.util.Lookup; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.openide.util.lookup.Lookups; import org.openide.util.lookup.ProxyLookup; /** Tests that a window system implementation conforms to the expected * behaviour. * * @author Jaroslav Tulach */ public final class WindowSystemCompatibilityTest extends Object { /** initialize the lookup for the test */ public static void init() { System.setProperty("org.openide.util.Lookup", WindowSystemCompatibilityTest.class.getName() + "$Lkp"); Object o = Lookup.getDefault(); if (!(o instanceof Lkp)) { Assert.fail("Wrong lookup object: " + o); } } private WindowSystemCompatibilityTest(String testName) { } /** Checks the default implementation. */ public static Test suite() { return suite(null); } /** Executes the test for provided window manager. */ public static Test suite(WindowManager wm) { init(); Object o = Lookup.getDefault(); Lkp l = (Lkp)o; l.assignWM(wm); if (wm != null) { Assert.assertEquals("Same engine found", wm, WindowManager.getDefault()); } else { o = WindowManager.getDefault(); Assert.assertNotNull("Engine found", o); Assert.assertEquals(DummyWindowManager.class, o.getClass()); } TestSuite ts = new TestSuite(); ts.addTestSuite(WindowManagerHid.class); return ts; } /** Default lookup used in the suite. */ public static final class Lkp extends ProxyLookup { private InstanceContent ic; public Lkp() { super(new Lookup[0]); ic = new InstanceContent(); AbstractLookup al = new AbstractLookup(ic); setLookups(new Lookup[] { al, Lookups.metaInfServices(Lkp.class.getClassLoader()) }); } final void assignWM(WindowManager executionEngine) { // ic.setPairs(java.util.Collections.EMPTY_LIST); if (executionEngine != null) { ic.add(executionEngine); } } } }
30.836538
110
0.626754
7a94ce02cfce8fe600003b4199e7a767a6b7c6a9
7,374
package jmss.formula.wl; import jmss.formula.ClauseAbs; import jmss.specificationCore.Solver; import java.util.List; import static java.lang.Math.abs; /** * 2016/02/15. */ public class ClauseWL extends ClauseAbs { //Watches private Integer moving = null; private int movingIndex = -1; private Integer fixed = null; private int fixedIndex = -1; public ClauseWL(Solver solver) { super(solver); } public void removeWatchesFromVariables() { if (size() == 1) { // Remove only watch ((VariableW) state.F().getVariable(moving)).removeWatch(this,moving); } else { ((VariableW) state.F().getVariable(moving)).removeWatch(this,moving); ((VariableW) state.F().getVariable(fixed)).removeWatch(this,fixed); } } public void connectInitialWachtes() { List<Integer> lits = getLiterals(); //TODO random selection, heuristic if(size() == 1){ moving = fixed = lits.get(0); movingIndex = fixedIndex = 0; } else{ moving = lits.get(0); movingIndex = 0; fixed = lits.get(1); fixedIndex = 1; } //connect variables ((VariableW) state.F().getVariable(abs(moving))).connectToClause(this,moving); if(size()>1){ ((VariableW) state.F().getVariable(abs(fixed))).connectToClause(this,fixed); } } public boolean searchNewWatch(Integer watch) { if(size() == 1){ state.F().foundConflictClause(this); return false; } if(size() == 2){ if(isConflicting()) state.F().foundConflictClause(this); if(isUnit()) state.F().foundUnitClause(this); return false; } if(watch.equals(fixed)) flipSearch(); //search for new watch for (int i = 0; i < getLiterals().size(); i++) { Integer lit = getLiterals().get(i); //ignore watches if(lit.equals(fixed)) continue; if(lit.equals(moving)) continue; //case 1:literal is free if(state.F().isVariableUndefined(abs(lit)) || (state.M().inTrail(lit)) ){ int prevVar = abs(moving); moving = lit; movingIndex = i; // Add moving to a queue to avoid concurrent modification ((VariableW) state.F().getVariable(abs(moving))).connectToClauseL(this,moving); if(prevVar != abs(moving)) ((VariableW) state.F().getVariable(abs(moving))).update(); // if(isConflicting()) throw new IllegalStateException("2WL conflicting"); // if(isUnit()) throw new IllegalStateException("2WL unit"); //signal watch change return true; } } if(isConflicting()) { state.F().foundConflictClause(this); } if(isUnit()) { state.F().foundUnitClause(this); } return false; } private void flipSearch() { Integer t = moving; Integer ind = movingIndex; moving = fixed; movingIndex = fixedIndex; fixed = t; fixedIndex = ind; } // @Override // public boolean isConflicting() { // //not conflicting as long as moving is not false in trail // return state.M().inTrail(-moving); // } // // @Override // public boolean isUnit() { // //last unassigned literal is always moving // return state.F().isVariableUndefined(abs(moving)); // } @Override public boolean isUnit() { // If one watch is conflicting and the other free, clause is unit if ((state.M().inTrail(-moving)) && (state.F().isVariableUndefined(abs(fixed)))) { return true; } if ((state.M().inTrail(-fixed)) && (state.F().isVariableUndefined(abs(moving)))) { return true; } // If moving == fixed (clause size 1) and undefined, clause is unit return (size() == 1) && (state.F().isVariableUndefined(abs(moving))); } @Override public boolean isConflicting() { // If both watches are conflicting in M, clause is conflicting if ((state.M().inTrail(-moving)) && (state.M().inTrail(-fixed))) { return true; } // Otherwise, clause is not conflicting return false; } @Override public Integer getUnitLiteral() { if(state.F().isVariableUndefined(moving)) return moving; if(state.F().isVariableUndefined(fixed)) return fixed; throw new IllegalStateException("Not unit"); // return fixed; } @Override public void addLiteral(Integer lit) { } @Override public void assertConflictingState() { List<Integer> lits = getLiterals(); if(size() == 1){ moving = fixed = lits.get(0); movingIndex = fixedIndex = 0; ((VariableW) state.F().getVariable(abs(moving))).connectToClause(this,moving); return; } if(size() == 2){ moving = lits.get(0); fixed = lits.get(1); movingIndex = 0; fixedIndex = 1; ((VariableW) state.F().getVariable(abs(moving))).connectToClause(this,moving); ((VariableW) state.F().getVariable(abs(fixed))).connectToClause(this,fixed); return; } // Size > 2: status may be affected // Find the 2 literals which are last assigned in trail int l1 = 0; int l2 = 1; // ensure bigger status if (state.M().isAssertedBefore(-lits.get(l2), -lits.get(l1))) { l2 = 0; l1 = 1; } for (int i = 2; i < lits.size(); i++) { // if new literal later than l2: set new literal as l2, l1 as l2 if (state.M().isAssertedBefore(-lits.get(l2), -lits.get(i) )) { l1 = l2; l2 = i; } else { // new literal later than l1, but not l2: set new l1 if (state.M().isAssertedBefore(-lits.get(l1), -lits.get(i))) { l1 = i; } // New literal before l1, l2: do nothing } } // set watches and indexes moving = lits.get(l1); movingIndex = l1; fixed = lits.get(l2); fixedIndex = l2; ((VariableW) state.F().getVariable(abs(moving))).connectToClause(this,moving); ((VariableW) state.F().getVariable(abs(fixed))).connectToClause(this,fixed); } public void updateStatus() { throw new NullPointerException("NYI"); } public String toString() { String ret = ""; List<Integer> lits = getLiterals(); for (int i = 0; i < lits.size(); i++) { if (i == movingIndex) { ret += " [" + lits.get(i) + "]"; } else { if (i == fixedIndex) { ret += " {" + lits.get(i) + "}"; } else { ret += " " + lits.get(i); } } } return ret; } }
26.814545
101
0.514782
7e416afa78bc383b842c35e307acbbc9e7c1f518
777
package com.guli.gulike.aoth.feign; import com.guli.common.utils.R; import com.guli.gulike.aoth.vo.SocialUserVo; import com.guli.gulike.aoth.vo.UserLoginVo; import com.guli.gulike.aoth.vo.UserRegistVo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; /** * @创建人: fry * @用于: * @创建时间 2020/9/3 */ @FeignClient("guli-member") public interface MenberFeignService { @PostMapping("/member/regist") R regist(@RequestBody UserRegistVo memberRegistVo); @PostMapping("/member/login") R login(@RequestBody UserLoginVo vo); /** * 社交登录 */ @PostMapping("/member/oauth2/login") R oauth(@RequestBody SocialUserVo vo); }
25.064516
59
0.734878
abc98bb935d6b1d0cc548ba69e72248686992d36
1,602
/* * Copyright 2020 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.core.rest; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.stereotype.Component; /** * * {@link ConverterFactory} for converting String to Enums (case-insensitive). * * @see ConverterFactory * @since 7.5 */ @Component @SuppressWarnings({ "rawtypes", "unchecked" }) public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> { private static class StringToEnumConverter<T extends Enum> implements Converter<String, T> { private Class<T> enumType; public StringToEnumConverter(Class<T> enumType) { this.enumType = enumType; } public T convert(String source) { return (T) Enum.valueOf(this.enumType, source.trim().toUpperCase()); } } @Override public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) { return new StringToEnumConverter(targetType); } }
31.411765
93
0.750936
9ecce004122870b8057c387624030c0946b005f5
11,226
package com.celeste.databases.core.util; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import lombok.AccessLevel; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class Reflection { public static Class<?> getClazz(final String path) throws ClassNotFoundException { return Class.forName(path); } public static Class<?> getClazz(final Field field) { return field.getType(); } public static Class<?>[] getClasses(final String path) throws ClassNotFoundException { return getClazz(path).getClasses(); } public static Class<?> getClasses(final String path, final int size) throws ClassNotFoundException { return getClazz(path).getClasses()[size]; } public static Class<?>[] getClasses(final Class<?> clazz) { return clazz.getClasses(); } public static Class<?> getClasses(final Class<?> clazz, final int size) { return clazz.getClasses()[size]; } public static Class<?>[] getDcClasses(final String path) throws ClassNotFoundException { return getClazz(path).getDeclaredClasses(); } public static Class<?> getDcClasses(final String path, final int size) throws ClassNotFoundException { return getClazz(path).getDeclaredClasses()[size]; } public static Class<?>[] getDcClasses(final Class<?> clazz) { return clazz.getDeclaredClasses(); } public static Class<?> getDcClasses(final Class<?> clazz, final int size) { return clazz.getDeclaredClasses()[size]; } public static Constructor<?> getConstructor(final String path, final Class<?>... parameterClass) throws ClassNotFoundException, NoSuchMethodException { return getClazz(path).getConstructor(parameterClass); } public static <T> Constructor<T> getConstructor(final Class<T> clazz, final Class<?>... parameterClass) throws NoSuchMethodException { return clazz.getConstructor(parameterClass); } public static Constructor<?> getDcConstructor(final String path, final Class<?>... parameterClass) throws ClassNotFoundException, NoSuchMethodException { final Constructor<?> constructor = getClazz(path).getDeclaredConstructor(parameterClass); constructor.setAccessible(true); return constructor; } public static <T> Constructor<T> getDcConstructor(final Class<T> clazz, final Class<?>... parameterClass) throws NoSuchMethodException { final Constructor<T> constructor = clazz.getDeclaredConstructor(parameterClass); constructor.setAccessible(true); return constructor; } public static Constructor<?>[] getConstructors(final String path) throws ClassNotFoundException { return getClazz(path).getConstructors(); } public static Constructor<?> getConstructors(final String path, final int size) throws ClassNotFoundException { return getClazz(path).getConstructors()[size]; } public static <T> Constructor<T>[] getConstructors(final Class<T> clazz) { return Arrays.stream(clazz.getConstructors()) .toArray(Constructor[]::new); } public static <T> Constructor<T> getConstructors(final Class<T> clazz, final int size) { return Arrays.stream(clazz.getConstructors()) .toArray(Constructor[]::new)[size]; } public static Constructor<?>[] getDcConstructors(final String path) throws ClassNotFoundException { return Arrays.stream(getClazz(path).getDeclaredConstructors()) .peek(constructor -> constructor.setAccessible(true)) .toArray(Constructor[]::new); } public static Constructor<?> getDcConstructors(final String path, final int size) throws ClassNotFoundException { final Constructor<?> constructor = getClazz(path).getDeclaredConstructors()[size]; constructor.setAccessible(true); return constructor; } public static <T> Constructor<T>[] getDcConstructors(final Class<T> clazz) { return Arrays.stream(clazz.getDeclaredConstructors()) .peek(constructor -> constructor.setAccessible(true)) .toArray(Constructor[]::new); } public static <T> Constructor<T> getDcConstructors(final Class<T> clazz, final int size) { final Constructor<T> constructor = Arrays.stream(clazz.getDeclaredConstructors()) .toArray(Constructor[]::new)[size]; constructor.setAccessible(true); return constructor; } public static Method getMethod(final String path, final String methodName, final Class<?>... parameterClass) throws ClassNotFoundException, NoSuchMethodException { return getClazz(path).getMethod(methodName, parameterClass); } public static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>... parameterClass) throws NoSuchMethodException { return clazz.getMethod(methodName, parameterClass); } public static Method getDcMethod(final String path, final String methodName, final Class<?>... parameterClass) throws ClassNotFoundException, NoSuchMethodException { final Method method = getClazz(path).getDeclaredMethod(methodName, parameterClass); method.setAccessible(true); return method; } public static Method getDcMethod(final Class<?> clazz, final String methodName, final Class<?>... parameterClass) throws NoSuchMethodException { final Method method = clazz.getDeclaredMethod(methodName, parameterClass); method.setAccessible(true); return method; } public static Method[] getMethods(final String path) throws ClassNotFoundException { return getClazz(path).getMethods(); } public static Method getMethods(final String path, final int size) throws ClassNotFoundException { return getClazz(path).getMethods()[size]; } public static Method[] getMethods(final Class<?> clazz) { return clazz.getMethods(); } public static Method getMethods(final Class<?> clazz, final int size) { return clazz.getMethods()[size]; } public static Method[] getDcMethods(final String path) throws ClassNotFoundException { return Arrays.stream(getClazz(path).getDeclaredMethods()) .peek(method -> method.setAccessible(true)) .toArray(Method[]::new); } public static Method getDcMethods(final String path, final int size) throws ClassNotFoundException { final Method method = getClazz(path).getDeclaredMethods()[size]; method.setAccessible(true); return method; } public static Method[] getDcMethods(final Class<?> clazz) { return Arrays.stream(clazz.getDeclaredMethods()) .peek(method -> method.setAccessible(true)) .toArray(Method[]::new); } public static Method getDcMethods(final Class<?> clazz, final int size) { final Method method = clazz.getDeclaredMethods()[size]; method.setAccessible(true); return method; } public static Field getField(final String path, final String variableName) throws ClassNotFoundException, NoSuchFieldException { return getClazz(path).getField(variableName); } public static Field getField(final Class<?> clazz, final String variableName) throws NoSuchFieldException { return clazz.getField(variableName); } public static Field getDcField(final String path, final String variableName) throws ClassNotFoundException, NoSuchFieldException { final Field field = getClazz(path).getDeclaredField(variableName); field.setAccessible(true); return field; } public static Field getDcField(final Class<?> clazz, final String variableName) throws NoSuchFieldException { final Field field = clazz.getDeclaredField(variableName); field.setAccessible(true); return field; } public static Field[] getFields(final String path) throws ClassNotFoundException { return getClazz(path).getFields(); } public static Field getFields(final String path, final int size) throws ClassNotFoundException { return getClazz(path).getFields()[size]; } public static Field[] getFields(final Class<?> clazz) { return clazz.getFields(); } public static Field getFields(final Class<?> clazz, final int size) { return clazz.getFields()[size]; } public static Field[] getDcFields(final String path) throws ClassNotFoundException { return Arrays.stream(getClazz(path).getDeclaredFields()) .peek(field -> field.setAccessible(true)) .toArray(Field[]::new); } public static Field getDcFields(final String path, final int size) throws ClassNotFoundException { final Field field = getClazz(path).getDeclaredFields()[size]; field.setAccessible(true); return field; } public static Field[] getDcFields(final Class<?> clazz) { return Arrays.stream(clazz.getDeclaredFields()) .peek(field -> field.setAccessible(true)) .toArray(Field[]::new); } public static Field getDcFields(final Class<?> clazz, final int size) { final Field field = clazz.getDeclaredFields()[size]; field.setAccessible(true); return field; } public static <T extends Annotation> boolean containsAnnotation(final Class<?> clazz, final Class<T> annotation) { return clazz.isAnnotationPresent(annotation); } public static <T extends Annotation> boolean containsAnnotation(final Constructor<?> constructor, final Class<T> annotation) { return constructor.isAnnotationPresent(annotation); } public static <T extends Annotation> boolean containsAnnotation(final Field field, final Class<T> annotation) { return field.isAnnotationPresent(annotation); } public static <T extends Annotation> T getAnnotation(final Class<?> clazz, final Class<T> annotation) { return clazz.getAnnotation(annotation); } public static <T extends Annotation> T getAnnotation(final Constructor<?> constructor, final Class<T> annotation) { return constructor.getAnnotation(annotation); } public static <T extends Annotation> T getAnnotation(final Field field, final Class<T> annotation) { return field.getAnnotation(annotation); } public static <T> T instance(final Constructor<T> constructor) throws IllegalAccessException, InvocationTargetException, InstantiationException { return constructor.newInstance(); } public static <T> T instance(final Constructor<T> constructor, final Object... args) throws IllegalAccessException, InvocationTargetException, InstantiationException { return constructor.newInstance(args); } public static Object invoke(final Method method, final Object instance, final Object... args) throws InvocationTargetException, IllegalAccessException { return method.invoke(instance, args); } public static Object invokeStatic(final Method method, final Object... args) throws InvocationTargetException, IllegalAccessException { return method.invoke(null, args); } public static Object get(final Field field, final Object instance) throws IllegalAccessException { return field.get(instance); } public static Object getStatic(final Field field) throws IllegalAccessException { return field.get(null); } }
35.301887
100
0.732674
37a5efa556aca68854b975fdaa54a71bec4443ad
5,248
package com.fasterxml.jackson.dataformat.xml.misc; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.XmlTestBase; public class PolymorphicTypesTest extends XmlTestBase { @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY) static class BaseTypeWithClassProperty { } static class SubTypeWithClassProperty extends BaseTypeWithClassProperty { public String name; public SubTypeWithClassProperty() { } public SubTypeWithClassProperty(String s) { name = s; } } @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.WRAPPER_OBJECT) protected static class BaseTypeWithClassObject { } protected static class SubTypeWithClassObject extends BaseTypeWithClassObject { public String name; public SubTypeWithClassObject() { } public SubTypeWithClassObject(String s) { name = s; } } @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") protected static class TypeWithClassPropertyAndObjectId { public String id; public TypeWithClassPropertyAndObjectId() {} public TypeWithClassPropertyAndObjectId(String id) { this.id = id; } } protected static class Wrapper { public List<TypeWithClassPropertyAndObjectId> data; public Wrapper(){} public Wrapper(List<TypeWithClassPropertyAndObjectId> data) { this.data = data; } } // [dataformat-xml#451] @JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION) @JsonSubTypes(@JsonSubTypes.Type(Child451.class)) public interface Value451 {} public static class Child451 implements Value451 { private final String property1; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public Child451(@JsonProperty("property1") String property1) { this.property1 = property1; } public String getProperty1() { return property1; } } /* /********************************************************************** /* Test methods /********************************************************************** */ private final XmlMapper MAPPER = newMapper(); public void testAsClassProperty() throws Exception { String xml = MAPPER.writeValueAsString(new SubTypeWithClassProperty("Foobar")); // Type info should be written as an attribute, so: final String exp = "<SubTypeWithClassProperty _class=\"com.fasterxml.jackson.dataformat.xml.misc.PolymorphicTypesTest..SubTypeWithClassProperty\">" //"<SubTypeWithClassProperty><_class>com.fasterxml.jackson.xml.types.TestPolymorphic..SubTypeWithClassProperty</_class>" +"<name>Foobar</name></SubTypeWithClassProperty>" ; assertEquals(exp, xml); Object result = MAPPER.readValue(xml, BaseTypeWithClassProperty.class); assertNotNull(result); assertEquals(SubTypeWithClassProperty.class, result.getClass()); assertEquals("Foobar", ((SubTypeWithClassProperty) result).name); } public void testAsClassObject() throws Exception { String xml = MAPPER.writeValueAsString(new SubTypeWithClassObject("Foobar")); Object result = MAPPER.readValue(xml, BaseTypeWithClassObject.class); assertNotNull(result); assertEquals(SubTypeWithClassObject.class, result.getClass()); assertEquals("Foobar", ((SubTypeWithClassObject) result).name); } // Test for [dataformat-xml#81] public void testAsPropertyWithObjectId() throws Exception { List<TypeWithClassPropertyAndObjectId> data = new ArrayList<PolymorphicTypesTest.TypeWithClassPropertyAndObjectId>(); TypeWithClassPropertyAndObjectId object = new TypeWithClassPropertyAndObjectId("Foobar"); data.add(object); // This will be written as an id reference instead of object; as such, no type info will be written. data.add(object); String xml = MAPPER.writeValueAsString(new Wrapper(data)); Wrapper result = MAPPER.readValue(xml, Wrapper.class); assertNotNull(result); assertSame(result.data.get(0), result.data.get(1)); assertEquals("Foobar", result.data.get(0).id); } // Test for [dataformat-xml#451] public void testDeduction() throws Exception { String xml = MAPPER.writeValueAsString(new Child451("value1")); assertTrue(xml.contains("<property1>value1</property1>")); // and try reading back for funsies Value451 result = MAPPER.readValue(xml, Value451.class); assertNotNull(result); assertEquals(Child451.class, result.getClass()); } }
39.164179
140
0.686357
9c71a244cc68c50da74d325e15fd18ef2c810eb4
5,331
/* * Copyright 2008 The MemeDB Contributors (see CONTRIBUTORS) * 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 memedb.backend; import java.io.File; import java.util.Map; import java.util.Set; import org.json.JSONArray; import memedb.MemeDB; import memedb.document.Document; import memedb.utils.Lock; public interface Backend { public void init(MemeDB memeDB); public void shutdown(); /** * Returns a set of the names of all databases * @return Set of database names */ public Set<String> getDatabaseNames(); /** * This method must not be called directly, use * MemeDB.addDatabase(). * The backend must contact the DBState to sequence the * database deletion <u>before</u> attempting to add * the database. * @return sequence number obtained from the DBState */ public long addDatabase(String name) throws BackendException; /** * Iterable for all documents in database */ public Iterable<Document> allDocuments(String db); /** * This method must not be called directly, use * MemeDB.deleteDatabase(). * The backend must contact the DBState to sequence the * database deletion <u>before</u> attempting to remove * the database. * @return sequence number obtained from the DBState */ public long deleteDatabase(String name) throws BackendException; /** * Before actually deleting a database document, the backend must call * DBState.deleteDocument(). * @param db Database name * @param id Document id * @throws memedb.backend.BackendException */ public void deleteDocument(String db,String id) throws BackendException; /** * Returns true if the database exists * @param db Database name * @return true if database exists */ public boolean doesDatabaseExist(String db); /** * Returns true if the document exists in the specified database * @param db Database name * @param id Document id * @return true if document exists */ public boolean doesDocumentExist(String db, String id); /** * Returns true if the document exists and has the specified revision * @param db Database name * @param id Document id * @param revision Revision id * @return true if db/document/revision exists */ public boolean doesDocumentRevisionExist(String db, String id, String revision); /** * Returns the sequence number when the database was created * @param db Database name * @return sequence number or null if not available */ public Long getDatabaseCreationSequenceNumber(String db); /** * Returns information about the database * @param name Database name * @return Map of keys to values */ public Map<String,Object> getDatabaseStats(String name); /** * Iterable for documents in an array of ids */ public Iterable<Document> getDocuments(String db, String[] ids); /** * Retrieves the latest revision of the document by id * @param db Database name * @param id Document id * @return document from database or null */ public Document getDocument(String db,String id); public Document getDocument(String db,String id, String rev); /** * Returns total number of documents in database * @param db Database name * @return document count, or null if db doesn't exist */ public Long getDocumentCount(String db); /** * Returns a JSONArray of all current revisions for a document * @param db Database name * @param id Document id * @return JSONArray of revision ids */ public JSONArray getDocumentRevisions(String db,String id); /** * Returns the MemeDB instance */ public MemeDB getMeme(); /** * Some content types (scripts) may need access to the actual * revision file path. If the backend is not backed on disk, this * should create a tempory file that can be used instead. * @throws BackendException if this is not possible or not implemented. **/ public File getRevisionFilePath(Document doc) throws BackendException; /** * Retrieves a lock on the specified document **/ public Lock lockForUpdate(String db,String id) throws BackendException; /** * Before saving a Document, the backend must call DBState.updateDocument() * and once the Document is physically committed, DBState.finalizeDocument(). * If the Document has not been modifed, both should be skipped. */ public Document saveDocument(Document doc) throws BackendException; public Document saveDocument(Document doc, Lock lock) throws BackendException; /** * This makes a place-holder file to avoid revision name duplicates. * @return true if the revision does not exist and was successfully created; false if the revision already exists */ public boolean touchRevision(String database, String id, String rev); }
30.815029
115
0.716001
b827cf8cd7ee7f940a687e46f0a9a0411c609f5a
4,833
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.preferences.client.central.tree; import java.util.ArrayList; import java.util.List; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.jboss.errai.ioc.client.api.ManagedInstance; import org.uberfire.client.mvp.UberElement; import org.uberfire.ext.preferences.client.central.hierarchy.HierarchyInternalItemPresenter; import org.uberfire.ext.preferences.client.central.hierarchy.HierarchyItemPresenter; import org.uberfire.ext.preferences.client.central.hierarchy.HierarchyItemView; import org.uberfire.ext.preferences.client.event.HierarchyItemSelectedEvent; import org.uberfire.ext.preferences.shared.bean.PreferenceHierarchyElement; public class TreeHierarchyInternalItemPresenter implements HierarchyInternalItemPresenter { public interface View extends HierarchyItemView, UberElement<TreeHierarchyInternalItemPresenter> { void select(); void selectElement(); } private final View view; private final ManagedInstance<TreeHierarchyInternalItemPresenter> treeHierarchyInternalItemPresenterProvider; private final ManagedInstance<TreeHierarchyLeafItemPresenter> treeHierarchyLeafItemPresenterProvider; private final Event<HierarchyItemSelectedEvent> hierarchyItemSelectedEvent; private List<HierarchyItemPresenter> hierarchyItems; private PreferenceHierarchyElement<?> hierarchyElement; private int level; @Inject public TreeHierarchyInternalItemPresenter( final View view, final ManagedInstance<TreeHierarchyInternalItemPresenter> treeHierarchyInternalItemPresenterProvider, final ManagedInstance<TreeHierarchyLeafItemPresenter> treeHierarchyLeafItemPresenterProvider, final Event<HierarchyItemSelectedEvent> hierarchyItemSelectedEvent ) { this.view = view; this.treeHierarchyInternalItemPresenterProvider = treeHierarchyInternalItemPresenterProvider; this.treeHierarchyLeafItemPresenterProvider = treeHierarchyLeafItemPresenterProvider; this.hierarchyItemSelectedEvent = hierarchyItemSelectedEvent; } @Override public <T> void init( final PreferenceHierarchyElement<T> preference, final int level, boolean tryToSelectChild ) { hierarchyElement = preference; this.level = level; hierarchyItems = new ArrayList<>(); for ( PreferenceHierarchyElement<?> child : preference.getChildren() ) { HierarchyItemPresenter hierarchyItem; if ( child.hasChildren() ) { hierarchyItem = treeHierarchyInternalItemPresenterProvider.get(); } else { hierarchyItem = treeHierarchyLeafItemPresenterProvider.get(); } hierarchyItem.init( child, level + 1, tryToSelectChild && !child.isSelectable() ); if ( child.isSelectable() ) { hierarchyItem.fireSelect(); tryToSelectChild = false; } hierarchyItems.add( hierarchyItem ); } view.init( this ); } @Override public void fireSelect() { view.select(); } public void select() { if ( hierarchyElement.isSelectable() ) { final HierarchyItemSelectedEvent event = new HierarchyItemSelectedEvent( hierarchyElement ); hierarchyItemSelectedEvent.fire( event ); view.selectElement(); } } public void hierarchyItemSelectedEvent( @Observes HierarchyItemSelectedEvent hierarchyItemSelectedEvent ) { if ( !hierarchyElement.getId().equals( hierarchyItemSelectedEvent ) ) { view.deselect(); } } @Override public View getView() { return view; } public PreferenceHierarchyElement<?> getHierarchyElement() { return hierarchyElement; } public List<HierarchyItemPresenter> getHierarchyItems() { return hierarchyItems; } public int getLevel() { return level; } }
36.067164
148
0.695427
85cf3b2d0eb1aa5c51d847c77427bd644758e0fd
182
package com.sixliu.creditloan.workflow.dao; /** *@author:MG01867 *@date:2018年8月13日 *@E-mail:[email protected] *@version: *@describe //TODO */ public interface BaseDao { }
15.166667
44
0.681319
2d4567616b6cda8ed98a3013698bc00ab29532ce
22,553
/* * (C) Copyright 2017 David Jennings * * 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: * David Jennings */ package org.jennings.geotools; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; /** * This class can be used to create Ellipses * * * @author david */ public class Ellipse { static final boolean debug = CONSTANTS.debug; /** * * Will not work for Ellipses where semi-major axis is greater than half * circumference of Earth * * Also may have issues when ellipses extend into polar regions * * Uses GreatCircle to calculate points on the ellipse. * * @param clon Center Longitude * @param clat Center Latitude * @param a Semi-Major Axis (km) * @param b Semi-Minor Axis (km) * @param rotationDeg Clockwise rotation in degrees. For 0 semi-major axis * is North-South * @param numPoints The actual number of points returned will be * approximately this amount * @param isClockwise For GeoJSON set false; for Esri Geometries set true * @return JSONArray with ellipse points */ public JSONArray createEllipse(double clon, double clat, Double a, Double b, Double rotationDeg, Integer numPoints, boolean isClockwise) { GreatCircle gc = new GreatCircle(); if (numPoints == null) { numPoints = 20; } if (a == null) { // default to 500 meters or 0.50 km a = 0.50; } if (b == null) { // default to 50 meters or 0.050 km b = 0.050; } if (rotationDeg == null) { rotationDeg = 0.0; } if (a < b) { // Switch a and b // Semimajor axis should be the larger of the two double t = a; a = b; b = t; } // If this was a circle then even distribuation would be d double d = 360.0 / (numPoints - 1); // The number of points returns will depend on eccentricity ArrayList<GeographicCoordinate> coords = new ArrayList<>(); double v = 360.0; GeographicCoordinate coord1 = new GeographicCoordinate(clon, clat); GeographicCoordinate lastcoord = coord1; while (v > 0.0001) { double r = v * CONSTANTS.D2R; double sv = Math.sin(r); double cv = Math.cos(r); double radiusKM = a * b / Math.sqrt(a * a * sv * sv + b * b * cv * cv); double bearing = v; if (bearing > 180) { bearing = bearing - 360; } DistanceBearing distb = new DistanceBearing(radiusKM, bearing); if (rotationDeg != 0.0) { bearing = (distb.getBearing() + rotationDeg) % 360.0; if (bearing > 180) { bearing = bearing - 360; } distb.setBearing(bearing); } GeographicCoordinate nc = gc.getNewCoordPair(coord1, distb); // Only add the nc if it is different from previous double lon = nc.getLon(); double lat = nc.getLat(); if (Math.abs(lon - lastcoord.getLon()) < 0.00001 && Math.abs(lat - lastcoord.getLat()) < 0.00001) { // skip this point too close to previous } else { coords.add(nc); if (debug) { System.out.println(v + "," + bearing + "," + radiusKM + "," + lon + "," + lat); } lastcoord = nc; } // Densifying the points around 0 and 360 and 180; just 10 degrees out really improved shape of ellipse if (v > 350 || v < 10 || (v > 170 && v < 190)) { v = v - d * b / a; } else { v = v - d; } } // Added code to prevent adding a last point that was too close to the end point. GeographicCoordinate firstPoint = coords.get(0); GeographicCoordinate lastPoint = coords.get(coords.size() - 1); if (Math.abs(firstPoint.getLon() - lastPoint.getLon()) < 0.00001 && Math.abs(firstPoint.getLat() - lastPoint.getLat()) < 0.00001) { // Replace last point with first coords.set(coords.size() - 1, firstPoint); } else { // Append firstpoint coords.add(firstPoint); if (debug) { System.out.println(-1 + "," + -1 + "," + -1 + "," + firstPoint.getLon() + "," + firstPoint.getLat()); } } // System.exit(0); GeographicCoordinate nc1; GeographicCoordinate nc2; JSONArray[] exteriorRing = new JSONArray[2]; exteriorRing[0] = new JSONArray(); exteriorRing[1] = new JSONArray(); int ringNum = 0; nc1 = coords.get(0); int i = 0; double lon1 = nc1.getLon(); double lat1 = nc1.getLat(); if (debug) { System.out.println(i + ":" + lon1 + "," + lat1); } JSONArray coord = new JSONArray("[" + lon1 + ", " + lat1 + "]"); exteriorRing[ringNum].put(coord); i++; boolean crossedDTEast = false; boolean crossedDTWest = false; boolean crossedZeroEast = false; boolean crossedZeroWest = false; while (i < coords.size()) { nc2 = coords.get(i); // Compare coordinates double lon2 = nc2.getLon(); double lat2 = nc2.getLat(); if (lon1 == 0.0 && lon2 < 0.0) { crossedZeroWest = true; // Switch ringnum if (ringNum == 0) { ringNum = 1; } else if (ringNum == 1) { ringNum = 0; } // Add nc1 to ring coord = new JSONArray("[" + lon1 + ", " + lat1 + "]"); exteriorRing[ringNum].put(coord); } else if (lon2 == 0.0 && lon1 < 0.0) { crossedZeroEast = true; // Add nc2 to ring coord = new JSONArray("[" + lon2 + ", " + lat2 + "]"); exteriorRing[ringNum].put(coord); if (crossedZeroWest) { // close ring exteriorRing[ringNum].put(exteriorRing[ringNum].get(0)); } // Switch ringnum if (ringNum == 0) { ringNum = 1; } else if (ringNum == 1) { ringNum = 0; } } else if (lon2 > 0.0 && lon1 < 0.0) { if (Math.abs(lon2 - lon1) > 180.0) { // Crossing DT heading west if (debug) { System.out.println("Crossing DT heading west"); } crossedDTWest = true; double x1 = (lon1 < 0) ? lon1 + 360.0 : lon1; double x2 = (lon2 < 0) ? lon2 + 360.0 : lon2; double crossing = gc.findCrossing(x1, lat1, x2, lat2, 180.0); if (debug) { System.out.println(crossing); } // Add point to current ring coord = new JSONArray("[-180.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); if (crossedZeroWest) { // South Pole in Footprint coord = new JSONArray("[-180.0, -90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[0.0, -90.0]"); exteriorRing[ringNum].put(coord); } // Swith to other ring if (ringNum == 0) { ringNum = 1; } else if (ringNum == 1) { ringNum = 0; } if (crossedZeroWest) { // South Pole in Footprint coord = new JSONArray("[0.0, -90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[180, -90.0]"); exteriorRing[ringNum].put(coord); } // Add point to other ring coord = new JSONArray("[180.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); } else { // or gone from -1.xx to 1.xx (Crossing 0 heading east) if (debug) { System.out.println("Crossing 0 heading east"); System.out.println("lon1 = " + lon1); System.out.println("lon2 = " + lon2); } crossedZeroEast = true; // -1.xx to 1.00 double x1 = lon1; double x2 = lon2; double crossing = gc.findCrossing(x1, lat1, x2, lat2, 0.0); if (debug) { System.out.println(crossing); } // Add point to current ring coord = new JSONArray("[0.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); if (crossedDTEast) { // North Pole is in footprint add 180,90 and 0, 90 coord = new JSONArray("[0.0,90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[-180.0,90.0]"); exteriorRing[ringNum].put(coord); } // Swith to other ring if (ringNum == 0) { ringNum = 1; } else if (ringNum == 1) { ringNum = 0; } if (crossedDTEast) { // North pole is in foot print add point 0,90, -180,90 coord = new JSONArray("[180.0,90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[0.0,90.0]"); exteriorRing[ringNum].put(coord); } // Add point to other ring coord = new JSONArray("[0.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); } } else if (lon2 < 0.0 && lon1 >= 0.0) { if (Math.abs(lon2 - lon1) > 180.0) { // Either gone from 179.xx to -179.xx (Crossing DT heading west) if (debug) { System.out.println("Crossing DT heading east"); } crossedDTEast = true; double x1 = (lon1 < 0) ? lon1 + 360.0 : lon1; double x2 = (lon2 < 0) ? lon2 + 360.0 : lon2; double crossing = gc.findCrossing(x1, lat1, x2, lat2, 180.0); if (debug) { System.out.println(crossing); } coord = new JSONArray("[180.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); if (crossedZeroEast) { // North Pole in Footprint coord = new JSONArray("[180.0, 90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[0.0, 90.0]"); exteriorRing[ringNum].put(coord); } // Swith to other ring if (ringNum == 0) { ringNum = 1; } else if (ringNum == 1) { ringNum = 0; } if (crossedZeroEast) { // North Pole in Footprint coord = new JSONArray("[0.0, 90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[-180, 90.0]"); exteriorRing[ringNum].put(coord); } coord = new JSONArray("[-180.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); } else { if (debug) { System.out.println("Crossing 0 heading west"); } crossedZeroWest = true; // or gone from 1.xx to -1.xx (Crossing 0 heading west double x1 = lon1; double x2 = lon2; double crossing = gc.findCrossing(x1, lat1, x2, lat2, 0.0); if (debug) { System.out.println(crossing); } // Add point to current ring coord = new JSONArray("[0.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); if (crossedDTWest) { // South Pole is in footprint coord = new JSONArray("[0.0,-90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[180.0,-90.0]"); exteriorRing[ringNum].put(coord); } // Swith to other ring if (ringNum == 0) { ringNum = 1; } else if (ringNum == 1) { ringNum = 0; } if (crossedDTWest) { // North pole is in foot print add point 0,90, -180,90 coord = new JSONArray("[-180.0,-90.0]"); exteriorRing[ringNum].put(coord); coord = new JSONArray("[0.0,-90.0]"); exteriorRing[ringNum].put(coord); } // Add point to other ring coord = new JSONArray("[0.0, " + crossing + "]"); exteriorRing[ringNum].put(coord); } } else if (lon1 == 0.0) { if (lon2 > 0.0) { } else { } } if (debug) { System.out.println(i + ":" + lon2 + "," + lat2); } if (i < coords.size() - 1) { // Inject last coord coord = new JSONArray("[" + lon2 + ", " + lat2 + "]"); exteriorRing[ringNum].put(coord); } nc1 = nc2; lon1 = nc1.getLon(); lat1 = nc1.getLat(); i++; } JSONArray polys = new JSONArray(); JSONArray poly; for (i = 0; i < 2; i++) { poly = new JSONArray(); if (exteriorRing[i].length() > 0) { // Add last point same as first exteriorRing[i].put(exteriorRing[i].get(0)); if (isClockwise) { // Reverse order JSONArray reversedPoly = new JSONArray(); int j = exteriorRing[i].length() - 1; while (j >= 0) { reversedPoly.put(exteriorRing[i].get(j)); j--; } polys.put(reversedPoly); } else { poly.put(exteriorRing[i]); polys.put(poly); } } } if (debug) { int j = 0; while (j < 2) { System.out.println("exteriorRing[" + j + "]"); i = 0; while (i < exteriorRing[j].length()) { System.out.println(exteriorRing[j].get(i)); i++; } j++; } } // Create the Geom return polys; } public String createEsrijsonEllipse(int id, double lon, double lat, double a, double b, double rot, int numPoints) { Ellipse el = new Ellipse(); // Clockwise Poly JSONArray polys; polys = el.createEllipse(lon, lat, a, b, rot, numPoints, true); JSONArray rngs = new JSONArray(); rngs.put(polys.getJSONArray(0).getJSONArray(0)); try { rngs.put(polys.getJSONArray(1).getJSONArray(0)); } catch (Exception e) { // ok to ignore } JSONObject geom = new JSONObject(); geom.put("rings", rngs); JSONObject esriJson = new JSONObject(); esriJson.put("a", a); esriJson.put("b", b); esriJson.put("rot", rot); esriJson.put("clon", lon); esriJson.put("clat", lat); esriJson.put("geometry", geom); return esriJson.toString(); } public String createWktEllipse(double lon, double lat, double a, double b, double rot, int numPoints) { JSONArray polys = createEllipse(lon, lat, a, b, rot, numPoints, false); int numPolys = polys.length(); StringBuffer buf = new StringBuffer(); if (numPolys == 1) { // Polygon buf.append("POLYGON (("); JSONArray ring = polys.getJSONArray(0).getJSONArray(0); int numPts = ring.length(); //System.out.println("numPts:" + numPts); int cnt = 0; while (cnt < numPts) { JSONArray pt = ring.getJSONArray(cnt); //System.out.println(pt); buf.append(String.valueOf(pt.getDouble(0)) + " " + String.valueOf(pt.getDouble(1))); cnt++; if (cnt < numPts) { buf.append(","); } } buf.append("))"); } else { // Multipolygon buf.append("MULTIPOLYGON ("); int cntPoly = 0; while (cntPoly < numPolys) { JSONArray ring = polys.getJSONArray(cntPoly).getJSONArray(0); int numPts = ring.length(); int cntPt = 0; buf.append("(("); while (cntPt < numPts) { JSONArray pt = ring.getJSONArray(cntPt); //System.out.println(pt); buf.append(String.valueOf(pt.getDouble(0)) + " " + String.valueOf(pt.getDouble(1))); cntPt++; if (cntPt < numPts) { buf.append(","); } } buf.append("))"); cntPoly++; if (cntPoly < numPolys) { buf.append(","); } } buf.append(")"); } System.out.println(numPolys); return buf.toString(); } public String createGeoJsonEllipse(int id, double lon, double lat, double a, double b, double rot, int numPoints) { JSONObject featureCollection = new JSONObject(); featureCollection.put("type", "FeatureCollection"); JSONArray features = new JSONArray(); JSONObject feature = new JSONObject(); feature.put("type", "Feature"); // Add properties (At least one is required) JSONObject properties = new JSONObject(); properties.put("a", a); properties.put("b", b); properties.put("rot", rot); properties.put("clon", lon); properties.put("clat", lat); feature.put("properties", properties); // Get the coordinates JSONArray coords = createEllipse(lon, lat, a, b, rot, numPoints, false); JSONObject geom = new JSONObject(); geom.put("type", "MultiPolygon"); geom.put("coordinates", coords); feature.put("geometry", geom); features.put(feature); featureCollection.put("features", features); return featureCollection.toString(); } public String createEllipse(int id, double lon, double lat, double a, double b, double rot, int numPoints, GeomType geomType) { switch (geomType) { case EsriJson: return createEllipse(lon, lat, a, b, rot, numPoints, true).toString(); case GeoJson: return createEllipse(lon, lat, a, b, rot, numPoints, false).toString(); case Wkt: return createWktEllipse(lon, lat, a, b, rot, numPoints); } return null; } public static void main(String args[]) { // GeoJSON Lint: http://geojsonlint.com/ // Wkt Lint: http://arthur-e.github.io/Wicket/sandbox-gmaps3.html // Need to fix so that EsriJson returns Geom correctly // Random polys in grids (e.g. landgrids.csv) // Polys in fixed pattern 1 meter circle every 1km Ellipse t = new Ellipse(); System.out.println(t.createEllipse(1, 0, 0, 400, 100, 45, 50, GeomType.GeoJson)); System.out.println(t.createEllipse(1, 0, 0, 400, 100, 45, 50, GeomType.EsriJson)); System.out.println(t.createEllipse(1, 0, 0, 400, 100, 45, 50, GeomType.Wkt)); System.out.println(); System.out.println(t.createEllipse(1, 10, 10, 400, 100, 45, 50, GeomType.GeoJson)); System.out.println(t.createEllipse(1, 10, 10, 400, 100, 45, 50, GeomType.EsriJson)); System.out.println(t.createEllipse(1, 10, 10, 400, 100, 45, 50, GeomType.Wkt)); } }
34.696923
142
0.452357
5a6cab3d30a0dd879664a24aad9ec4ee42917089
1,014
package network.gateway.broker; import data.*; import exception.RobinhoodException; import org.joda.time.DateTime; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public interface Broker { Set<Instrument> getAllInstruments(); float getBuyingPower() throws RobinhoodException; Collection<Asset> getOwnedAssets() throws RobinhoodException; Collection<Order> getRecentOrders() throws RobinhoodException; List<EquityHistorical> getHistoricalValues() throws RobinhoodException; List<Map<String, String>> getQuotes(final Collection<String> symbols) throws RobinhoodException; Map<String, String> getQuote(final String symbol) throws RobinhoodException; OrderStatus buyShares(final String symbol, final int shares) throws RobinhoodException; OrderStatus sellShares(final String symbol, final int shares) throws RobinhoodException; MarketState getMarketStateForDate(final DateTime dateTime) throws RobinhoodException; }
28.971429
100
0.795858
78adb856f28b792b1d68e8ca8af66ca63296b1da
42,824
/* * Copyright (C) 2015 Peter Gregus for GravityBox Project (C3C076@xda) * 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.wrbug.gravitybox.nougat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.wrbug.gravitybox.nougat.ModStatusBar.StatusBarState; import com.wrbug.gravitybox.nougat.ledcontrol.LedSettings; import com.wrbug.gravitybox.nougat.ledcontrol.QuietHours; import com.wrbug.gravitybox.nougat.ledcontrol.QuietHoursActivity; import com.wrbug.gravitybox.nougat.ledcontrol.LedSettings.ActiveScreenMode; import com.wrbug.gravitybox.nougat.ledcontrol.LedSettings.HeadsUpMode; import com.wrbug.gravitybox.nougat.ledcontrol.LedSettings.LedMode; import com.wrbug.gravitybox.nougat.ledcontrol.LedSettings.Visibility; import com.wrbug.gravitybox.nougat.ledcontrol.LedSettings.VisibilityLs; import android.app.ActivityManager; import android.app.KeyguardManager; import android.app.Notification; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioManager; import android.os.Binder; import android.os.Handler; import android.os.PowerManager; import android.os.SystemClock; import android.provider.Settings; import android.service.notification.StatusBarNotification; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; public class ModLedControl { private static final String TAG = "GB:ModLedControl"; public static final boolean DEBUG = BuildConfig.DEBUG; private static final String CLASS_NOTIFICATION_MANAGER_SERVICE = "com.android.server.notification.NotificationManagerService"; private static final String CLASS_VIBRATOR_SERVICE = "com.android.server.VibratorService"; private static final String CLASS_BASE_STATUSBAR = "com.android.systemui.statusbar.BaseStatusBar"; private static final String CLASS_PHONE_STATUSBAR = "com.android.systemui.statusbar.phone.PhoneStatusBar"; private static final String CLASS_NOTIF_DATA = "com.android.systemui.statusbar.NotificationData"; private static final String CLASS_NOTIF_DATA_ENTRY = "com.android.systemui.statusbar.NotificationData.Entry"; private static final String CLASS_NOTIFICATION_RECORD = "com.android.server.notification.NotificationRecord"; private static final String CLASS_HEADS_UP_MANAGER_ENTRY = "com.android.systemui.statusbar.policy.HeadsUpManager.HeadsUpEntry"; public static final String PACKAGE_NAME_SYSTEMUI = "com.android.systemui"; private static final String NOTIF_EXTRA_HEADS_UP_MODE = "gbHeadsUpMode"; private static final String NOTIF_EXTRA_HEADS_UP_TIMEOUT = "gbHeadsUpTimeout"; private static final String NOTIF_EXTRA_ACTIVE_SCREEN = "gbActiveScreen"; private static final String NOTIF_EXTRA_ACTIVE_SCREEN_MODE = "gbActiveScreenMode"; private static final String NOTIF_EXTRA_ACTIVE_SCREEN_POCKET_MODE = "gbActiveScreenPocketMode"; public static final String NOTIF_EXTRA_PROGRESS_TRACKING = "gbProgressTracking"; public static final String NOTIF_EXTRA_VISIBILITY_LS = "gbVisibilityLs"; public static final String NOTIF_EXTRA_HIDE_PERSISTENT = "gbHidePersistent"; private static final String SETTING_ZEN_MODE = "zen_mode"; public static final String ACTION_CLEAR_NOTIFICATIONS = "gravitybox.intent.action.CLEAR_NOTIFICATIONS"; private static XSharedPreferences mPrefs; private static XSharedPreferences mQhPrefs; private static Context mContext; private static PowerManager mPm; private static SensorManager mSm; private static KeyguardManager mKm; private static Sensor mProxSensor; private static QuietHours mQuietHours; private static Map<String, Long> mNotifTimestamps = new HashMap<String, Long>(); private static boolean mUserPresent; private static Object mNotifManagerService; private static boolean mProximityWakeUpEnabled; private static boolean mScreenOnDueToActiveScreen; private static AudioManager mAudioManager; private static Integer mDefaultNotificationLedColor; private static Integer mDefaultNotificationLedOn; private static Integer mDefaultNotificationLedOff; private static SensorEventListener mProxSensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { try { final boolean screenCovered = event.values[0] != mProxSensor.getMaximumRange(); if (DEBUG) log("mProxSensorEventListener: " + event.values[0] + "; screenCovered=" + screenCovered); if (!screenCovered) { performActiveScreen(); } } catch (Throwable t) { XposedBridge.log(t); } finally { try { mSm.unregisterListener(this, mProxSensor); } catch (Throwable t) { // should never happen } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private static BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(LedSettings.ACTION_UNC_SETTINGS_CHANGED)) { mPrefs.reload(); if (intent.hasExtra(LedSettings.EXTRA_UNC_AS_ENABLED)) { toggleActiveScreenFeature(intent.getBooleanExtra( LedSettings.EXTRA_UNC_AS_ENABLED, false)); } } else if (action.equals(QuietHoursActivity.ACTION_QUIET_HOURS_CHANGED)) { mQhPrefs.reload(); mQuietHours = new QuietHours(mQhPrefs); } else if (action.equals(Intent.ACTION_USER_PRESENT)) { if (DEBUG) log("User present"); mUserPresent = true; mScreenOnDueToActiveScreen = false; } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { mUserPresent = false; mScreenOnDueToActiveScreen = false; } else if (action.equals(ACTION_CLEAR_NOTIFICATIONS)) { clearNotifications(); } else if (action.equals(GravityBoxSettings.ACTION_PREF_POWER_CHANGED) && intent.hasExtra(GravityBoxSettings.EXTRA_POWER_PROXIMITY_WAKE)) { mProximityWakeUpEnabled = intent.getBooleanExtra( GravityBoxSettings.EXTRA_POWER_PROXIMITY_WAKE, false); } } }; public static void log(String message) { XposedBridge.log(TAG + ": " + message); } public static void initAndroid(final XSharedPreferences mainPrefs, final ClassLoader classLoader) { mPrefs = new XSharedPreferences(GravityBox.PACKAGE_NAME, "ledcontrol"); mPrefs.makeWorldReadable(); mQhPrefs = new XSharedPreferences(GravityBox.PACKAGE_NAME, "quiet_hours"); mQhPrefs.makeWorldReadable(); mQuietHours = new QuietHours(mQhPrefs); mProximityWakeUpEnabled = mainPrefs.getBoolean(GravityBoxSettings.PREF_KEY_POWER_PROXIMITY_WAKE, false); try { final Class<?> nmsClass = XposedHelpers.findClass(CLASS_NOTIFICATION_MANAGER_SERVICE, classLoader); XposedBridge.hookAllConstructors(nmsClass, new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { if (mNotifManagerService == null) { mNotifManagerService = param.thisObject; mContext = (Context) XposedHelpers.callMethod(param.thisObject, "getContext"); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(LedSettings.ACTION_UNC_SETTINGS_CHANGED); intentFilter.addAction(Intent.ACTION_USER_PRESENT); intentFilter.addAction(QuietHoursActivity.ACTION_QUIET_HOURS_CHANGED); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(ACTION_CLEAR_NOTIFICATIONS); intentFilter.addAction(GravityBoxSettings.ACTION_PREF_POWER_CHANGED); mContext.registerReceiver(mBroadcastReceiver, intentFilter); toggleActiveScreenFeature(!mPrefs.getBoolean(LedSettings.PREF_KEY_LOCKED, false) && mPrefs.getBoolean(LedSettings.PREF_KEY_ACTIVE_SCREEN_ENABLED, false)); hookNotificationDelegate(); if (DEBUG) log("Notification manager service initialized"); } } }); XposedHelpers.findAndHookMethod(CLASS_NOTIFICATION_MANAGER_SERVICE, classLoader, "enqueueNotificationInternal", String.class, String.class, int.class, int.class, String.class, int.class, Notification.class, int[].class, int.class, notifyHook); XposedHelpers.findAndHookMethod(CLASS_NOTIFICATION_MANAGER_SERVICE, classLoader, "applyZenModeLocked", CLASS_NOTIFICATION_RECORD, applyZenModeHook); XposedHelpers.findAndHookMethod(CLASS_NOTIFICATION_MANAGER_SERVICE, classLoader, "updateLightsLocked", updateLightsLockedHook); XposedBridge.hookAllMethods(XposedHelpers.findClass(CLASS_VIBRATOR_SERVICE, classLoader), "startVibrationLocked", startVibrationHook); } catch (Throwable t) { XposedBridge.log(t); } } private static XC_MethodHook notifyHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { try { if (mPrefs.getBoolean(LedSettings.PREF_KEY_LOCKED, false)) { if (DEBUG) log("Ultimate notification control feature locked."); return; } Notification n = (Notification) param.args[6]; if (Utils.isVerneeApolloDevice()) { XposedHelpers.setIntField(param.thisObject, "mDefaultNotificationColor", ((n.defaults & Notification.DEFAULT_LIGHTS) != 0 ? getDefaultNotificationLedColor() : n.ledARGB)); XposedHelpers.setIntField(param.thisObject, "mDefaultNotificationLedOn", ((n.defaults & Notification.DEFAULT_LIGHTS) != 0 ? getDefaultNotificationLedOn() : n.ledOnMS)); XposedHelpers.setIntField(param.thisObject, "mDefaultNotificationLedOff", ((n.defaults & Notification.DEFAULT_LIGHTS) != 0 ? getDefaultNotificationLedOff() : n.ledOffMS)); } if (n.extras.containsKey("gbIgnoreNotification")) return; Object oldRecord = getOldNotificationRecord(param.args[0], param.args[4], param.args[5], param.args[8]); Notification oldN = getNotificationFromRecord(oldRecord); final String pkgName = (String) param.args[0]; LedSettings ls = LedSettings.deserialize(mPrefs.getStringSet(pkgName, null)); if (!ls.getEnabled()) { // use default settings in case they are active ls = LedSettings.deserialize(mPrefs.getStringSet("default", null)); if (!ls.getEnabled() && !mQuietHours.quietHoursActive(ls, n, mUserPresent)) { return; } } if (DEBUG) log(pkgName + ": " + ls.toString()); final boolean qhActive = mQuietHours.quietHoursActive(ls, n, mUserPresent); final boolean qhActiveIncludingLed = qhActive && mQuietHours.muteLED; final boolean qhActiveIncludingVibe = qhActive && ( (mQuietHours.mode != QuietHours.Mode.WEAR && mQuietHours.muteVibe) || (mQuietHours.mode == QuietHours.Mode.WEAR && mUserPresent)); final boolean qhActiveIncludingActiveScreen = qhActive && !mPrefs.getBoolean(LedSettings.PREF_KEY_ACTIVE_SCREEN_IGNORE_QUIET_HOURS, false); if (ls.getEnabled()) { n.extras.putBoolean(NOTIF_EXTRA_PROGRESS_TRACKING, ls.getProgressTracking()); n.extras.putString(NOTIF_EXTRA_VISIBILITY_LS, ls.getVisibilityLs().toString()); n.extras.putBoolean(NOTIF_EXTRA_HIDE_PERSISTENT, ls.getHidePersistent()); } // whether to ignore ongoing notification boolean isOngoing = ((n.flags & Notification.FLAG_ONGOING_EVENT) != 0 || (n.flags & Notification.FLAG_FOREGROUND_SERVICE) != 0); // additional check if old notification had a foreground service flag set since it seems not to be propagated // for updated notifications (until Notification gets processed by WorkerHandler which is too late for us) if (!isOngoing && oldN != null) { isOngoing = (oldN.flags & Notification.FLAG_FOREGROUND_SERVICE) != 0; if (DEBUG) log("Old notification foreground service check: isOngoing=" + isOngoing); } if (isOngoing && !ls.getOngoing() && !qhActive) { if (DEBUG) log("Ongoing led control disabled. Ignoring."); return; } // lights if (qhActiveIncludingLed || (ls.getEnabled() && !(isOngoing && !ls.getOngoing()) && (ls.getLedMode() == LedMode.OFF || currentZenModeDisallowsLed(ls.getLedDnd()) || shouldIgnoreUpdatedNotificationLight(oldRecord, ls.getLedIgnoreUpdate())))) { n.defaults &= ~Notification.DEFAULT_LIGHTS; n.flags &= ~Notification.FLAG_SHOW_LIGHTS; } else if (ls.getEnabled() && ls.getLedMode() == LedMode.OVERRIDE && !(isOngoing && !ls.getOngoing())) { n.flags |= Notification.FLAG_SHOW_LIGHTS; if (Utils.isVerneeApolloDevice()) { n.defaults |= Notification.DEFAULT_LIGHTS; XposedHelpers.setIntField(param.thisObject, "mDefaultNotificationColor", ls.getColor()); XposedHelpers.setIntField(param.thisObject, "mDefaultNotificationLedOn", ls.getLedOnMs()); XposedHelpers.setIntField(param.thisObject, "mDefaultNotificationLedOff", ls.getLedOffMs()); } else { n.defaults &= ~Notification.DEFAULT_LIGHTS; n.ledOnMS = ls.getLedOnMs(); n.ledOffMS = ls.getLedOffMs(); n.ledARGB = ls.getColor(); } } // vibration if (qhActiveIncludingVibe) { n.defaults &= ~Notification.DEFAULT_VIBRATE; n.vibrate = null; } else if (ls.getEnabled() && !(isOngoing && !ls.getOngoing())) { if (ls.getVibrateOverride() && ls.getVibratePattern() != null && ((n.defaults & Notification.DEFAULT_VIBRATE) != 0 || n.vibrate != null || !ls.getVibrateReplace())) { n.defaults &= ~Notification.DEFAULT_VIBRATE; n.vibrate = ls.getVibratePattern(); } } // sound if (qhActive || (ls.getEnabled() && ls.getSoundToVibrateDisabled() && isRingerModeVibrate())) { n.defaults &= ~Notification.DEFAULT_SOUND; n.sound = null; n.flags &= ~Notification.FLAG_INSISTENT; } else { if (ls.getSoundOverride() && ((n.defaults & Notification.DEFAULT_SOUND) != 0 || n.sound != null || !ls.getSoundReplace())) { n.defaults &= ~Notification.DEFAULT_SOUND; n.sound = ls.getSoundUri(); } if (ls.getSoundOnlyOnce()) { if (ls.getSoundOnlyOnceTimeout() > 0) { if (mNotifTimestamps.containsKey(pkgName)) { long delta = System.currentTimeMillis() - mNotifTimestamps.get(pkgName); if (delta > 500 && delta < ls.getSoundOnlyOnceTimeout()) { n.defaults &= ~Notification.DEFAULT_SOUND; n.defaults &= ~Notification.DEFAULT_VIBRATE; n.sound = null; n.vibrate = null; n.flags &= ~Notification.FLAG_ONLY_ALERT_ONCE; } else { mNotifTimestamps.put(pkgName, System.currentTimeMillis()); } } else { mNotifTimestamps.put(pkgName, System.currentTimeMillis()); } } else { n.flags |= Notification.FLAG_ONLY_ALERT_ONCE; } } else { n.flags &= ~Notification.FLAG_ONLY_ALERT_ONCE; } if (ls.getInsistent()) { n.flags |= Notification.FLAG_INSISTENT; } else { n.flags &= ~Notification.FLAG_INSISTENT; } } if (ls.getEnabled()) { // heads up mode n.extras.putString(NOTIF_EXTRA_HEADS_UP_MODE, ls.getHeadsUpMode().toString()); if (ls.getHeadsUpMode() != HeadsUpMode.OFF) { n.extras.putInt(NOTIF_EXTRA_HEADS_UP_TIMEOUT, ls.getHeadsUpTimeout()); } // active screen mode if (ls.getActiveScreenMode() != ActiveScreenMode.DISABLED && !(ls.getActiveScreenIgnoreUpdate() && oldN != null) && n.priority > Notification.PRIORITY_MIN && ls.getVisibilityLs() != VisibilityLs.CLEARABLE && ls.getVisibilityLs() != VisibilityLs.ALL && !qhActiveIncludingActiveScreen && !isOngoing && mPm != null && mKm.isKeyguardLocked()) { n.extras.putBoolean(NOTIF_EXTRA_ACTIVE_SCREEN, true); n.extras.putString(NOTIF_EXTRA_ACTIVE_SCREEN_MODE, ls.getActiveScreenMode().toString()); } // visibility if (ls.getVisibility() != Visibility.DEFAULT) { n.visibility = ls.getVisibility().getValue(); } } if (DEBUG) log("Notification info: defaults=" + n.defaults + "; flags=" + n.flags); } catch (Throwable t) { XposedBridge.log(t); } } }; private static Object getOldNotificationRecord(Object pkg, Object tag, Object id, Object userId) { Object oldNotifRecord = null; try { ArrayList<?> notifList = (ArrayList<?>) XposedHelpers.getObjectField( mNotifManagerService, "mNotificationList"); synchronized (notifList) { int index = (Integer) XposedHelpers.callMethod( mNotifManagerService, "indexOfNotificationLocked", pkg, tag, id, userId); if (index >= 0) { oldNotifRecord = notifList.get(index); } } } catch (Throwable t) { log("Error in getOldNotificationRecord: " + t.getMessage()); if (DEBUG) XposedBridge.log(t); } if (DEBUG) log("getOldNotificationRecord: has old record: " + (oldNotifRecord != null)); return oldNotifRecord; } private static Notification getNotificationFromRecord(Object record) { Notification notif = null; if (record != null) { try { notif = (Notification) XposedHelpers.callMethod(record, "getNotification"); } catch (Throwable t) { log("Error in getNotificationFromRecord: " + t.getMessage()); if (DEBUG) XposedBridge.log(t); } } return notif; } private static boolean notificationRecordHasLight(Object record) { boolean hasLight = false; if (record != null) { try { String key = (String) XposedHelpers.callMethod(record, "getKey"); List<?> lights = (List<?>) XposedHelpers.getObjectField( mNotifManagerService, "mLights"); hasLight = lights.contains(key); } catch (Throwable t) { log("Error in notificationRecordHasLight: " + t.getMessage()); if (DEBUG) XposedBridge.log(t); } } if (DEBUG) log("notificationRecordHasLight: " + hasLight); return hasLight; } private static boolean shouldIgnoreUpdatedNotificationLight(Object record, boolean ignore) { boolean shouldIgnore = (ignore && record != null && !notificationRecordHasLight(record)); if (DEBUG) log("shouldIgnoreUpdatedNotificationLight: " + shouldIgnore); return shouldIgnore; } private static int getDefaultNotificationLedColor() { if (mDefaultNotificationLedColor == null) { mDefaultNotificationLedColor = getDefaultNotificationProp( "config_defaultNotificationColor", "color", 0xff000080); } return mDefaultNotificationLedColor; } private static int getDefaultNotificationLedOn() { if (mDefaultNotificationLedOn == null) { mDefaultNotificationLedOn = getDefaultNotificationProp( "config_defaultNotificationLedOn", "integer", 500); } return mDefaultNotificationLedOn; } private static int getDefaultNotificationLedOff() { if (mDefaultNotificationLedOff == null) { mDefaultNotificationLedOff = getDefaultNotificationProp( "config_defaultNotificationLedOff", "integer", 0); } return mDefaultNotificationLedOff; } @SuppressWarnings("deprecation") private static int getDefaultNotificationProp(String resName, String resType, int defVal) { int val = defVal; try { Context ctx = (Context) XposedHelpers.callMethod( mNotifManagerService, "getContext"); Resources res = ctx.getResources(); int resId = res.getIdentifier(resName, resType, "android"); if (resId != 0) { switch (resType) { case "color": val = res.getColor(resId); break; case "integer": val = res.getInteger(resId); break; } } } catch (Throwable t) { if (DEBUG) XposedBridge.log(t); } return val; } private static XC_MethodHook applyZenModeHook = new XC_MethodHook() { @SuppressWarnings("deprecation") @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { try { Notification n = (Notification) XposedHelpers.callMethod(param.args[0], "getNotification"); if (!n.extras.containsKey(NOTIF_EXTRA_ACTIVE_SCREEN) || !n.extras.containsKey(NOTIF_EXTRA_ACTIVE_SCREEN_MODE) || !(mPm != null && !mPm.isScreenOn() && mKm.isKeyguardLocked())) { n.extras.remove(NOTIF_EXTRA_ACTIVE_SCREEN); return; } n.extras.remove(NOTIF_EXTRA_ACTIVE_SCREEN); // check if intercepted by Zen if (!mPrefs.getBoolean(LedSettings.PREF_KEY_ACTIVE_SCREEN_IGNORE_QUIET_HOURS, false) && (boolean) XposedHelpers.callMethod(param.args[0], "isIntercepted")) { if (DEBUG) log("Active screen: intercepted by Zen - ignoring"); n.extras.remove(NOTIF_EXTRA_ACTIVE_SCREEN_MODE); return; } // set additional params final ActiveScreenMode asMode = ActiveScreenMode.valueOf( n.extras.getString(NOTIF_EXTRA_ACTIVE_SCREEN_MODE)); n.extras.putBoolean(NOTIF_EXTRA_ACTIVE_SCREEN_POCKET_MODE, !mProximityWakeUpEnabled && mPrefs.getBoolean(LedSettings.PREF_KEY_ACTIVE_SCREEN_POCKET_MODE, true)); if (DEBUG) log("Performing Active Screen with mode " + asMode.toString()); if (mSm != null && mProxSensor != null && n.extras.getBoolean(NOTIF_EXTRA_ACTIVE_SCREEN_POCKET_MODE)) { mSm.registerListener(mProxSensorEventListener, mProxSensor, SensorManager.SENSOR_DELAY_FASTEST); if (DEBUG) log("Performing active screen using proximity sensor"); } else { performActiveScreen(); } } catch (Throwable t) { XposedBridge.log(t); } } }; private static XC_MethodHook updateLightsLockedHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (mScreenOnDueToActiveScreen) { try { XposedHelpers.setBooleanField(param.thisObject, "mScreenOn", false); if (DEBUG) log("updateLightsLocked: Screen on due to active screen - pretending it's off"); } catch (Throwable t) { XposedBridge.log(t); } } } }; private static XC_MethodHook startVibrationHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (mQuietHours.quietHoursActive() && (mQuietHours.muteSystemVibe || mQuietHours.mode == QuietHours.Mode.WEAR)) { if (DEBUG) log("startVibrationLocked: system level vibration suppressed"); param.setResult(null); } } }; private static void hookNotificationDelegate() { try { Object notifDel = XposedHelpers.getObjectField(mNotifManagerService, "mNotificationDelegate"); XposedHelpers.findAndHookMethod(notifDel.getClass(), "clearEffects", new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { if (mScreenOnDueToActiveScreen) { if (DEBUG) log("clearEffects: suppressed due to ActiveScreen"); param.setResult(null); } } }); } catch (Throwable t) { XposedBridge.log(t); } } private static boolean isRingerModeVibrate() { try { if (mAudioManager == null) { mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); } return (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE); } catch (Throwable t) { XposedBridge.log(t); return false; } } private static boolean currentZenModeDisallowsLed(String dnd) { if (dnd == null || dnd.isEmpty()) return false; try { int zenMode = Settings.Global.getInt(mContext.getContentResolver(), SETTING_ZEN_MODE, 0); List<String> dndList = Arrays.asList(dnd.split(",")); return dndList.contains(Integer.toString(zenMode)); } catch (Throwable t) { XposedBridge.log(t); return false; } } private static void toggleActiveScreenFeature(boolean enable) { try { if (enable && mContext != null) { mPm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); mKm = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); mSm = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); mProxSensor = mSm.getDefaultSensor(Sensor.TYPE_PROXIMITY); } else { mProxSensor = null; mSm = null; mPm = null; mKm = null; } if (DEBUG) log("Active screen feature: " + enable); } catch (Throwable t) { XposedBridge.log(t); } } private static void performActiveScreen() { new Handler().postDelayed(new Runnable() { @Override public void run() { long ident = Binder.clearCallingIdentity(); try { XposedHelpers.callMethod(mPm, "wakeUp", SystemClock.uptimeMillis()); mScreenOnDueToActiveScreen = true; } finally { Binder.restoreCallingIdentity(ident); } } }, 1000); } private static void clearNotifications() { try { if (mNotifManagerService != null) { XposedHelpers.callMethod(mNotifManagerService, "cancelAllLocked", android.os.Process.myUid(), android.os.Process.myPid(), XposedHelpers.callStaticMethod(ActivityManager.class, "getCurrentUser"), 3, (Object)null, true); } } catch (Throwable t) { XposedBridge.log(t); } } // SystemUI package private static Object mStatusBar; private static XSharedPreferences mSysUiPrefs; private static BroadcastReceiver mSystemUiBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(GravityBoxSettings.ACTION_HEADS_UP_SETTINGS_CHANGED)) { mSysUiPrefs.reload(); } } }; public static void init(final XSharedPreferences prefs, final ClassLoader classLoader) { try { XposedBridge.hookAllMethods( XposedHelpers.findClass(CLASS_NOTIF_DATA, classLoader), "shouldFilterOut", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { StatusBarNotification sbn = (StatusBarNotification)param.args[0]; Notification n = sbn.getNotification(); // whether to hide persistent everywhere if (!sbn.isClearable() && n.extras.getBoolean(NOTIF_EXTRA_HIDE_PERSISTENT)) { param.setResult(true); return; } // whether to hide during keyguard if (ModStatusBar.getStatusBarState() != StatusBarState.SHADE) { VisibilityLs vls = n.extras.containsKey(NOTIF_EXTRA_VISIBILITY_LS) ? VisibilityLs.valueOf(n.extras.getString(NOTIF_EXTRA_VISIBILITY_LS)) : VisibilityLs.DEFAULT; switch (vls) { case CLEARABLE: param.setResult(sbn.isClearable()); break; case PERSISTENT: param.setResult(!sbn.isClearable()); break; case ALL: param.setResult(true); break; case DEFAULT: default: return; } } } }); } catch (Throwable t) { XposedBridge.log(t); } } public static void initHeadsUp(final XSharedPreferences prefs, final ClassLoader classLoader) { try { mSysUiPrefs = prefs; XposedHelpers.findAndHookMethod(CLASS_PHONE_STATUSBAR, classLoader, "start", new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { mStatusBar = param.thisObject; Context context = (Context) XposedHelpers.getObjectField(mStatusBar, "mContext"); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(GravityBoxSettings.ACTION_HEADS_UP_SETTINGS_CHANGED); context.registerReceiver(mSystemUiBroadcastReceiver, intentFilter); } }); XposedHelpers.findAndHookMethod(CLASS_BASE_STATUSBAR, classLoader, "shouldPeek", CLASS_NOTIF_DATA_ENTRY, StatusBarNotification.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { // disable heads up if notification is for different user in multi-user environment if (!(Boolean)XposedHelpers.callMethod(param.thisObject, "isNotificationForCurrentProfiles", param.args[1])) { if (DEBUG) log("HeadsUp: Notification is not for current user"); return; } StatusBarNotification sbn = (StatusBarNotification) param.args[1]; Context context = (Context) XposedHelpers.getObjectField(param.thisObject, "mContext"); Notification n = sbn.getNotification(); int statusBarWindowState = XposedHelpers.getIntField(param.thisObject, "mStatusBarWindowState"); boolean showHeadsUp = false; // no heads up if app with DND enabled is in the foreground if (shouldNotDisturb(context)) { if (DEBUG) log("shouldInterrupt: NO due to DND app in the foreground"); showHeadsUp = false; // disable when panels are disabled } else if (!(Boolean) XposedHelpers.callMethod(param.thisObject, "panelsEnabled")) { if (DEBUG) log("shouldInterrupt: NO due to panels being disabled"); showHeadsUp = false; // get desired mode set by UNC or use default } else { HeadsUpMode mode = n.extras.containsKey(NOTIF_EXTRA_HEADS_UP_MODE) ? HeadsUpMode.valueOf(n.extras.getString(NOTIF_EXTRA_HEADS_UP_MODE)) : HeadsUpMode.DEFAULT; if (DEBUG) log("Heads up mode: " + mode.toString()); switch (mode) { default: case DEFAULT: showHeadsUp = (Boolean) param.getResult(); break; case ALWAYS: showHeadsUp = isHeadsUpAllowed(sbn, context); break; case OFF: showHeadsUp = false; break; case IMMERSIVE: showHeadsUp = isStatusBarHidden(statusBarWindowState) && isHeadsUpAllowed(sbn, context); break; } } param.setResult(showHeadsUp); } }); XposedHelpers.findAndHookMethod(CLASS_HEADS_UP_MANAGER_ENTRY, classLoader, "updateEntry", new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { Object huMgr = XposedHelpers.getSurroundingThis(param.thisObject); Object entry = XposedHelpers.getObjectField(param.thisObject, "entry"); if (entry == null || (boolean)XposedHelpers.callMethod(huMgr, "hasFullScreenIntent", entry)) return; XposedHelpers.callMethod(param.thisObject, "removeAutoRemovalCallbacks"); StatusBarNotification sbNotif = (StatusBarNotification) XposedHelpers.getObjectField(entry, "notification"); Notification n = sbNotif.getNotification(); int timeout = n.extras.containsKey(NOTIF_EXTRA_HEADS_UP_TIMEOUT) ? n.extras.getInt(NOTIF_EXTRA_HEADS_UP_TIMEOUT) * 1000 : mSysUiPrefs.getInt(GravityBoxSettings.PREF_KEY_HEADS_UP_TIMEOUT, 5) * 1000; if (timeout > 0) { Handler H = (Handler) XposedHelpers.getObjectField(huMgr, "mHandler"); H.postDelayed((Runnable)XposedHelpers.getObjectField( param.thisObject, "mRemoveHeadsUpRunnable"), timeout); } } }); } catch (Throwable t) { XposedBridge.log(t); } } private static boolean keyguardAllowsHeadsUp(Context context) { boolean isShowingAndNotOccluded; boolean isInputRestricted; Object kgViewManager = XposedHelpers.getObjectField(mStatusBar, "mStatusBarKeyguardViewManager"); isShowingAndNotOccluded = ((boolean)XposedHelpers.callMethod(kgViewManager, "isShowing") && !(boolean)XposedHelpers.callMethod(kgViewManager, "isOccluded")); isInputRestricted = (boolean)XposedHelpers.callMethod(kgViewManager, "isInputRestricted"); return (!isShowingAndNotOccluded && !isInputRestricted); } private static boolean isHeadsUpAllowed(StatusBarNotification sbn, Context context) { if (context == null) return false; PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); Notification n = sbn.getNotification(); return (pm.isInteractive() && keyguardAllowsHeadsUp(context) && (!sbn.isOngoing() || n.fullScreenIntent != null || (n.extras.getInt("headsup", 0) != 0))); } private static boolean isStatusBarHidden(int statusBarWindowState) { return (statusBarWindowState != 0); } @SuppressWarnings("deprecation") private static String getTopLevelPackageName(Context context) { try { final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); ComponentName cn = taskInfo.get(0).topActivity; return cn.getPackageName(); } catch (Throwable t) { log("Error getting top level package: " + t.getMessage()); return null; } } private static boolean shouldNotDisturb(Context context) { String pkgName = getTopLevelPackageName(context); final XSharedPreferences uncPrefs = new XSharedPreferences(GravityBox.PACKAGE_NAME, "ledcontrol"); if(!uncPrefs.getBoolean(LedSettings.PREF_KEY_LOCKED, false) && pkgName != null) { LedSettings ls = LedSettings.deserialize(uncPrefs.getStringSet(pkgName, null)); return (ls.getEnabled() && ls.getHeadsUpDnd()); } else { return false; } } }
49.853318
132
0.566365
429426d3498b87cc66ef400d5e472418ca78667b
2,731
package com.actitime.tests.base; import java.io.IOException; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import com.actitime.driver.Driver; import com.actitime.driver.DriverFactory; import com.actitime.reports.ExtentReport; import com.actitime.web_pages.WebDashboard; import com.actitime.web_pages.WebLogin; import com.actitime.web_pages.WebUsers; import com.actitime.app_pages.*; import com.actitime.device_pages.*; /* * BaseTest */ public class BaseTest extends DriverFactory { /* Before Class */ @Parameters({ "browser" }) @BeforeClass(alwaysRun = true) public void beforeClass(String browser) throws Exception { extent = ExtentReport.getExtent(); if (Driver.getRunOn().equalsIgnoreCase("grid")) { if (Driver.getType().equalsIgnoreCase("Desktop")) { driver = invokeBrowserInGrid(browser); webLoginPO = PageFactory.initElements(driver, WebLogin.class); webDashBoardPO = PageFactory.initElements(driver, WebDashboard.class); webUsersPO = PageFactory.initElements(driver, WebUsers.class); } else if (Driver.getType().equalsIgnoreCase("Device")) { appiumStart(); driver = setupInGrid(browser); deviceLoginPO = PageFactory.initElements(driver,DeviceLogin.class); deviceDashBoardPO = PageFactory.initElements(driver,DeviceDashboard.class); } else if (Driver.getType().equalsIgnoreCase("App")) { appiumStart(); driver = setupApp(browser); appCreateNewFormPO = PageFactory.initElements(driver, CreateForm.class); } } else if (Driver.getRunOn().equalsIgnoreCase("StandAlone")) { if (Driver.getType().equalsIgnoreCase("Desktop")) { driver = invokeBrowser(browser); webLoginPO = PageFactory.initElements(driver, WebLogin.class); webDashBoardPO = PageFactory.initElements(driver, WebDashboard.class); webUsersPO = PageFactory.initElements(driver, WebUsers.class); } else if (Driver.getType().equalsIgnoreCase("Device")) { appiumStart(); driver = setup(browser); deviceLoginPO = PageFactory.initElements(driver, DeviceLogin.class); deviceDashBoardPO = PageFactory.initElements(driver, DeviceDashboard.class); } else if (Driver.getType().equalsIgnoreCase("App")) { appiumStart(); setupApp(browser); appCreateNewFormPO = PageFactory.initElements(driver, CreateForm.class); } } } /* After Class */ @AfterClass public void afterClass() throws IOException, InterruptedException { extent.flush(); if (Driver.getType().equalsIgnoreCase("Device")) { appiumStop(); } else if (Driver.getType().equalsIgnoreCase("Desktop")) { closeBrowser(); } } }
34.1375
80
0.740388
ce60c04f69327d1a828589ed85a4f1ba4ab8d04a
455
package tally.load; import com.google.inject.AbstractModule; import com.google.inject.Provides; public class FileScannerModule extends AbstractModule { @Override protected void configure() { } @Provides FileScanner provideFileScanner(DataLoader dataLoader) { //return new RecursiveFileScanner(dataLoader, ".yaml"); //return new ThreadedFileScanner(dataLoader, ".yaml"); return new WalkTreeFileScanner(dataLoader, ".yaml"); } }
23.947368
59
0.753846
42b5b1618c5cc59be667ab5add9e656c4ce15b38
1,771
/** * Package groovy_parallel_patterns.functionals.pipelines provides a number of processes that can be used as * a component in larger networks. Each process comprises a network of * other processes, typically, Worker, WorkerTerminating and Collect.<p> * The processes are supplied in a number of different variations depending * on the nature of the channel connections provided by the process as follows.<p> * * One expects the one end of a channel<br> * Collect means a collection containing a Collect process as the last or * only element in the process<br> * * The nature of the process is defined by concepts such as<br> * * Pipeline a sequence of process undertaking a series of operations on * a data object as it passes through the pipeline, a so called task * parallel architecture<br> * *<pre> * Author, Licence and Copyright statement * author Jon Kerridge * School of Computing * Edinburgh Napier University * Merchiston Campus, * Colinton Road * Edinburgh EH10 5DT * * Author contact: j.kerridge (at) napier.ac.uk * * Copyright Jon Kerridge Edinburgh Napier University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *</pre> * */ package groovy_parallel_patterns.functionals.pipelines;
38.5
108
0.742518
38dfb863d601624f01f7805ea1df21128c240385
3,406
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.tools.rumen; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskID; import org.apache.hadoop.mapreduce.TaskType; /** * Event to record unsuccessful (Killed/Failed) completion of task attempts * */ public class TaskAttemptUnsuccessfulCompletionEvent implements HistoryEvent { private TaskID taskId; private TaskType taskType; private TaskAttemptID attemptId; private long finishTime; private String hostname; private String error; private String status; /** * Create an event to record the unsuccessful completion of attempts * @param id Attempt ID * @param taskType Type of the task * @param status Status of the attempt * @param finishTime Finish time of the attempt * @param hostname Name of the host where the attempt executed * @param error Error string */ public TaskAttemptUnsuccessfulCompletionEvent(TaskAttemptID id, TaskType taskType, String status, long finishTime, String hostname, String error) { this.taskId = id.getTaskID(); this.taskType = taskType; this.attemptId = id; this.finishTime = finishTime; this.hostname = hostname; this.error = error; this.status = status; } /** Get the task id */ public TaskID getTaskId() { return taskId; } /** Get the task type */ public TaskType getTaskType() { return taskType; } /** Get the attempt id */ public TaskAttemptID getTaskAttemptId() { return attemptId; } /** Get the finish time */ public long getFinishTime() { return finishTime; } /** Get the name of the host where the attempt executed */ public String getHostname() { return hostname; } /** Get the error string */ public String getError() { return error; } /** Get the task status */ public String getTaskStatus() { return status; } /** Get the event type */ public EventType getEventType() { if (status.equals("FAILED")) { if (taskType == TaskType.JOB_SETUP) { return EventType.SETUP_ATTEMPT_FAILED; } else if (taskType == TaskType.JOB_CLEANUP) { return EventType.CLEANUP_ATTEMPT_FAILED; } return attemptId.isMap() ? EventType.MAP_ATTEMPT_FAILED : EventType.REDUCE_ATTEMPT_FAILED; } else { if (taskType == TaskType.JOB_SETUP) { return EventType.SETUP_ATTEMPT_KILLED; } else if (taskType == TaskType.JOB_CLEANUP) { return EventType.CLEANUP_ATTEMPT_KILLED; } return attemptId.isMap() ? EventType.MAP_ATTEMPT_KILLED : EventType.REDUCE_ATTEMPT_KILLED; } } }
34.06
77
0.707575
588435999bb97f7ec4d7e4cc0a1f677a636819a6
4,147
package club.javalearn.admin.config; import club.javalearn.admin.shiro.DefaultAuthorizingRealm; import club.javalearn.admin.shiro.JwtFilter; import club.javalearn.admin.shiro.LoginLimitHashedCredentialsMatcher; import net.sf.ehcache.CacheManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.mgt.SessionsSecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.Filter; import java.util.HashMap; import java.util.Map; /** * Created with IntelliJ IDEA. * * @author king-pan * Date: 2018-12-03 * Time: 15:05 * Description: Shiro的配置类 */ @Configuration public class ShiroConfig { /** * 先走 filter ,然后 filter 如果检测到请求头存在 token,则用 token 去 login,走 Realm 去验证 */ @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); // 添加自己的过滤器并且取名为jwt Map<String, Filter> filterMap = new HashMap<>(20); //设置我们自定义的JWT过滤器 filterMap.put("jwt", new JwtFilter()); factoryBean.setFilters(filterMap); factoryBean.setSecurityManager(securityManager); // 设置无权限时跳转的 url; factoryBean.setUnauthorizedUrl("/unauthorized/无权限"); Map<String, String> filterRuleMap = new HashMap<>(20); // 所有请求通过我们自己的JWT Filter filterRuleMap.put("/logout", "logout"); filterRuleMap.put("/**", "jwt"); // 访问 /unauthorized/** 不通过JWTFilter filterRuleMap.put("/unauthorized/**", "anon"); factoryBean.setFilterChainDefinitionMap(filterRuleMap); return factoryBean; } /** * 添加注解支持 */ @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); // 强制使用cglib,防止重复代理和可能引起代理出错的问题 // https://zhuanlan.zhihu.com/p/29161098 defaultAdvisorAutoProxyCreator.setProxyTargetClass(true); return defaultAdvisorAutoProxyCreator; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public SessionsSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(getDefaultAuthorizingRealm()); return securityManager; } /** * 配置自定义的权限登录器 */ @Bean public DefaultAuthorizingRealm getDefaultAuthorizingRealm() { DefaultAuthorizingRealm authorizingRealm = new DefaultAuthorizingRealm(); // 配置自定义的密码比较器 //authorizingRealm.setCredentialsMatcher(loginLimitHashedCredentialsMatcher()); return authorizingRealm; } /** * 配置自定义的密码比较器 * * @return LoginLimitHashedCredentialsMatcher */ @Bean public LoginLimitHashedCredentialsMatcher loginLimitHashedCredentialsMatcher() { LoginLimitHashedCredentialsMatcher credentialsMatcher = new LoginLimitHashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName("sha-1"); credentialsMatcher.setHashIterations(10); return credentialsMatcher; } @Bean public CacheManager cacheManager() { return CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("ehcache.xml")); } }
31.9
117
0.734507
d9a0ab985963fc057e75368a7aa391efeaaa4859
2,394
/* * #%L * ===================================================== * _____ _ ____ _ _ _ _ * |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | | * | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| | * | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ | * |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_| * \____/ * * ===================================================== * * Hochschule Hannover * (University of Applied Sciences and Arts, Hannover) * Faculty IV, Dept. of Computer Science * Ricklinger Stadtweg 118, 30459 Hannover, Germany * * Email: [email protected] * Website: http://trust.f4.hs-hannover.de/ * * This file is part of visitmeta-common, version 0.5.0, * implemented by the Trust@HsH research group at the Hochschule Hannover. * %% * Copyright (C) 2012 - 2015 Trust@HsH * %% * 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 de.hshannover.f4.trust.visitmeta.implementations.internal; import java.util.ArrayList; import java.util.List; import de.hshannover.f4.trust.visitmeta.interfaces.Delta; import de.hshannover.f4.trust.visitmeta.interfaces.IdentifierGraph; /** * Internal representation of the changes of an IF-MAP graph structure between two points in time. * */ public class DeltaImpl implements Delta { private List<IdentifierGraph> mDeletes; private List<IdentifierGraph> mUpdates; public DeltaImpl(List<IdentifierGraph> deletes, List<IdentifierGraph> updates) { this.mDeletes = deletes; this.mUpdates = updates; } @Override public List<IdentifierGraph> getDeletes() { List<IdentifierGraph> oink = new ArrayList<>(); oink.addAll(mDeletes); return oink; } @Override public List<IdentifierGraph> getUpdates() { List<IdentifierGraph> oink = new ArrayList<>(); oink.addAll(mUpdates); return oink; } }
29.925
98
0.631161
1185339b2b61ccde6913ac4a911fb07dd9c86f77
11,461
package com.mcxiaoke.next.ui.widget.v7; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.v4.view.ActionProvider; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.Toast; import com.mcxiaoke.next.ui.BuildConfig; import com.mcxiaoke.next.ui.R; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * User: mcxiaoke * Date: 13-10-22 * Time: 下午4:00 * * 添加自定义ShareTarget支持,Updated: 2013-12-24 */ /** * 高级版的ShareActionProvider * 支持自定义优先显示的分享目标 */ public class AdvancedShareActionProvider extends ActionProvider implements MenuItem.OnMenuItemClickListener { public static final boolean DEBUG = BuildConfig.DEBUG; public static final String TAG = AdvancedShareActionProvider.class.getSimpleName(); public static final int WEIGHT_MAX = Integer.MAX_VALUE; public static final int WEIGHT_DEFAULT = 0; /** * 默认显示的分享目标数量 */ public static final int DEFAULT_LIST_LENGTH = 4; private final Object mLock = new Object(); private int mDefaultLength; private CharSequence mExpandLabel; private volatile int mWeightCounter; private Context mContext; private PackageManager mPackageManager; private Intent mIntent; private MenuItem.OnMenuItemClickListener mOnMenuItemClickListener; private List<String> mExtraPackages = new ArrayList<String>(); private List<String> mToRemovePackages = new ArrayList<String>(); private List<ShareTarget> mExtraTargets = new ArrayList<ShareTarget>(); private List<ShareTarget> mShareTargets = new ArrayList<ShareTarget>(); public AdvancedShareActionProvider(Context context) { super(context); mContext = context; mPackageManager = context.getPackageManager(); mWeightCounter = WEIGHT_MAX; mDefaultLength = DEFAULT_LIST_LENGTH; mExpandLabel = mContext.getString(R.string.share_action_provider_expand_label); } /** * 设置MenuItem的点击事件 * * @param listener listener */ public void setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener listener) { mOnMenuItemClickListener = listener; } /** * 添加自定义的分享目标(不会重新排序) * 注意:必须在setShareIntent之前调用 * * @param pkg 包名 */ public void addCustomPackage(String pkg) { if (!mExtraPackages.contains(pkg)) { mExtraPackages.add(pkg); } } /** * 添加自定义的分享目标(不会重新排序) * 注意:必须在setShareIntent之前调用 * * @param pkgs 包名集合 */ public void addCustomPackages(Collection<String> pkgs) { for (String pkg : pkgs) { addCustomPackage(pkg); } } /** * 清空自定义的分享目标 */ public void clearCustomPackages() { mExtraPackages.clear(); } /** * 从分享列表移除指定的app * 注意:必须在setShareIntent之前调用 * * @param pkg pkg */ public void removePackage(String pkg) { mToRemovePackages.add(pkg); } /** * 添加自定义的分享目标t * 注意:必须在setShareIntent之前调用 * * @param target target */ public void addShareTarget(ShareTarget target) { target.weight = --mWeightCounter; mExtraTargets.add(target); } /** * 设置默认显示的分享目标数量 * * @param length 数量 */ public void setDefaultLength(int length) { mDefaultLength = length; } public int getDefaultLength() { return mDefaultLength; } public void setExpandLabel(CharSequence label) { mExpandLabel = label; } /** * 设置分享Intent * 设置Intent会同时重新加载分享目标列表 * * @param intent Intent */ public void setShareIntent(Intent intent) { mIntent = intent; reloadActivities(); } /** * 设置Intent Extras * 注意:必须在setShareIntent之后调用 * * @param extras Bundle */ public void setIntentExtras(Bundle extras) { mIntent.replaceExtras(extras); } /** * 添加额外的参数到Intent * 注意:必须在setShareIntent之后调用 * * @param extras Bundle */ public void addIntentExtras(Bundle extras) { mIntent.putExtras(extras); } /** * 添加额外的参数到Intent * 注意:必须在setShareIntent之后调用 * * @param subject Intent.EXTRA_SUBJECT * @param text Intent.EXTRA_TEXT */ public void setIntentExtras(String subject, String text) { setIntentExtras(subject, text, null); } /** * 添加额外的参数到Intent * 注意:必须在setShareIntent之后调用 * * @param imageUri Intent.EXTRA_STREAM */ public void setIntentExtras(Uri imageUri) { setIntentExtras(null, null, imageUri); } /** * 添加额外的参数到Intent * 注意:必须在setShareIntent之后调用 * * @param subject Intent.EXTRA_SUBJECT * @param text Intent.EXTRA_TEXT * @param imageUri Intent.EXTRA_STREAM */ public void setIntentExtras(String subject, String text, Uri imageUri) { if (DEBUG) { Log.v(TAG, "setIntentExtras() subject=" + subject); Log.v(TAG, "setIntentExtras() text=" + text); Log.v(TAG, "setIntentExtras() imageUri=" + imageUri); } mIntent.putExtra(Intent.EXTRA_SUBJECT, subject); mIntent.putExtra(Intent.EXTRA_TEXT, text); if (imageUri != null) { mIntent.putExtra(Intent.EXTRA_STREAM, imageUri); } } public List<ShareTarget> getShareTargets() { return mShareTargets; } public List<ShareTarget> getDefaultShareTargets() { int length = Math.min(mDefaultLength, mShareTargets.size()); return mShareTargets.subList(0, length); } /** * 重新加载目标Activity列表 */ private void reloadActivities() { loadShareTargets(); sortShareTargets(); } private void loadShareTargets() { if (mIntent != null) { mShareTargets.clear(); List<ResolveInfo> activities = mPackageManager.queryIntentActivities(mIntent, PackageManager.MATCH_DEFAULT_ONLY); if (activities == null || activities.isEmpty()) { return; } for (ResolveInfo resolveInfo : activities) { ShareTarget target = toShareTarget(resolveInfo); mShareTargets.add(target); } } } private void sortShareTargets() { if (mShareTargets.size() > 0) { if (DEBUG) { Log.v(TAG, "sortShareTargets() mShareTargets size=" + mShareTargets.size()); Log.v(TAG, "sortShareTargets() mExtraPackages size=" + mExtraPackages.size()); } for (String pkg : mExtraPackages) { ShareTarget target = findShareTarget(pkg); if (target != null) { target.weight = --mWeightCounter; } } for (String pkg : mToRemovePackages) { ShareTarget target = findShareTarget(pkg); if (target != null) { mShareTargets.remove(target); } } mShareTargets.addAll(mExtraTargets); Collections.sort(mShareTargets); mExtraTargets.clear(); mExtraPackages.clear(); mToRemovePackages.clear(); final int size = mShareTargets.size(); for (int i = 0; i < size; i++) { mShareTargets.get(i).id = i; } } } /** * 根据报名查找某个ShareTarget * * @param pkg 包名 * @return index */ private ShareTarget findShareTarget(String pkg) { for (ShareTarget target : mShareTargets) { if (pkg.equals(target.packageName)) { return target; } } return null; } /** * 根据ResolveInfo生成ShareTarget * * @param resolveInfo ResolveInfo * @return ShareTarget */ private ShareTarget toShareTarget(ResolveInfo resolveInfo) { if (resolveInfo == null || resolveInfo.activityInfo == null) { return null; } ActivityInfo info = resolveInfo.activityInfo; ShareTarget target = new ShareTarget(info.loadLabel(mPackageManager), info.loadIcon(mPackageManager), null); target.packageName = info.packageName; target.className = info.name; return target; } @Override public View onCreateActionView() { return null; } @Override public boolean hasSubMenu() { return true; } /** * 根据Activity列表生成PopupMenu * * @param subMenu SubMenu that will be displayed */ @Override public void onPrepareSubMenu(SubMenu subMenu) { subMenu.clear(); if (DEBUG) { Log.v(TAG, "onPrepareSubMenu() mDefaultLength=" + mDefaultLength + " mShareTargets.size()=" + mShareTargets.size()); } int length = Math.min(mDefaultLength, mShareTargets.size()); Resources res = mContext.getResources(); for (int i = 0; i < length; i++) { ShareTarget target = mShareTargets.get(i); subMenu.add(0, i, i, target.title).setIcon(target.icon).setOnMenuItemClickListener(this); } if (mDefaultLength < mShareTargets.size()) { subMenu = subMenu.addSubMenu(Menu.NONE, mDefaultLength, mDefaultLength, mExpandLabel); for (int i = 0; i < mShareTargets.size(); i++) { ShareTarget target = mShareTargets.get(i); subMenu.add(0, i, i, target.title).setIcon(target.icon).setOnMenuItemClickListener(this); } } } /** * 按顺序处理,如果某一阶段返回true,忽略后续的处理 * * @param item * @return */ @Override public boolean onMenuItemClick(MenuItem item) { boolean handled = false; ShareTarget target = mShareTargets.get(item.getItemId()); // 首先响应target自带的listener if (target.listener != null) { handled = target.listener.onMenuItemClick(item); } if (handled) { return true; } // 其次响应外部设置的listener if (mOnMenuItemClickListener != null) { handled = mOnMenuItemClickListener.onMenuItemClick(item); } if (handled) { return true; } if (target.packageName == null || target.className == null) { return true; } // 最后响应默认的intent ComponentName chosenName = new ComponentName( target.packageName, target.className); Intent intent = new Intent(mIntent); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setComponent(chosenName); if (DEBUG) { Log.v(TAG, "onMenuItemClick() target=" + chosenName); } try { mContext.startActivity(intent); } catch (Exception e) { Log.e(TAG, "onMenuItemClick() error: " + e); Toast.makeText(mContext, R.string.share_action_provider_target_not_found, Toast.LENGTH_SHORT).show(); } return true; } }
27.616867
128
0.605445
2f634bb69ef62e9486f90258b0b1a408d3fb900e
12,425
/* * Copyright [2012-2014] PayPal Software Foundation * * 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 ml.shifu.shifu.core; import java.util.Arrays; import ml.shifu.shifu.container.obj.ColumnBinning; import ml.shifu.shifu.container.obj.ColumnConfig; import ml.shifu.shifu.container.obj.ColumnType; import ml.shifu.shifu.container.obj.ModelNormalizeConf.NormType; import ml.shifu.shifu.udf.NormalizeUDF.CategoryMissingNormType; import org.testng.Assert; import org.testng.annotations.Test; public class NormalizerTest { @Test public void computeZScore() { Assert.assertEquals(0.0, Normalizer.computeZScore(2, 2, 1, 6.0)[0]); Assert.assertEquals(6.0, Normalizer.computeZScore(12, 2, 1, 6.0)[0]); Assert.assertEquals(-2.0, Normalizer.computeZScore(2, 4, 1, 2)[0]); // If stdDev == 0, return 0 Assert.assertEquals(0.0, Normalizer.computeZScore(12, 2, 0, 6.0)[0]); } @Test public void getZScore1() { ColumnConfig config = new ColumnConfig(); config.setMean(2.0); config.setStdDev(1.0); config.setColumnType(ColumnType.N); Assert.assertEquals(0.0, Normalizer.normalize(config, "2", 6.0).get(0)); Assert.assertEquals(0.0, Normalizer.normalize(config, "ABC", 0.1).get(0)); } @Test public void getZScore2() { ColumnConfig config = new ColumnConfig(); config.setMean(2.0); config.setStdDev(1.0); config.setColumnType(ColumnType.N); Assert.assertEquals(-4.0, Normalizer.normalize(config, "-3", null).get(0)); } @Test public void getZScore3() { ColumnConfig config = new ColumnConfig(); config.setColumnType(ColumnType.C); config.setMean(2.0); config.setStdDev(1.0); config.setBinCategory(Arrays.asList(new String[] { "1", "2", "3", "4", "ABC" })); config.setBinPosCaseRate(Arrays.asList(new Double[] { 0.1, 2.0, 0.3, 0.1 })); Assert.assertEquals(0.0, Normalizer.normalize(config, "2", 0.1).get(0)); // Assert.assertEquals(0.0, Normalizer.normalize(config, "5", 0.1); } @Test public void getZScore4() { ColumnConfig config = new ColumnConfig(); Normalizer n = new Normalizer(config, 0.1); config.setMean(2.0); config.setStdDev(1.0); config.setColumnType(ColumnType.N); Assert.assertEquals(0.0, n.normalize("2").get(0)); } @Test public void numericalNormalizeTest() { // Input setting ColumnConfig config = new ColumnConfig(); config.setMean(2.0); config.setStdDev(1.0); config.setColumnType(ColumnType.N); ColumnBinning cbin = new ColumnBinning(); cbin.setBinCountWoe(Arrays.asList(new Double[] { 10.0, 11.0, 12.0, 13.0, 6.5 })); cbin.setBinWeightedWoe(Arrays.asList(new Double[] { 20.0, 21.0, 22.0, 23.0, 16.5 })); cbin.setBinBoundary(Arrays.asList(new Double[] { Double.NEGATIVE_INFINITY, 2.0, 4.0, 6.0 })); cbin.setBinCountNeg(Arrays.asList(1, 2, 3, 4, 5)); cbin.setBinCountPos(Arrays.asList(5, 4, 3, 2, 1)); config.setColumnBinning(cbin); // Test zscore normalization Assert.assertEquals(Normalizer.normalize(config, "5.0", 4.0, NormType.ZSCALE).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "5.0", null, NormType.ZSCALE).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 4.0, NormType.ZSCALE).get(0), 0.0); Assert.assertEquals(Normalizer.normalize(config, null, 4.0, NormType.ZSCALE).get(0), 0.0); // Test old zscore normalization Assert.assertEquals(Normalizer.normalize(config, "5.0", 4.0, NormType.OLD_ZSCALE).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "5.0", null, NormType.OLD_ZSCALE).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 4.0, NormType.OLD_ZSCALE).get(0), 0.0); Assert.assertEquals(Normalizer.normalize(config, null, 4.0, NormType.OLD_ZSCALE).get(0), 0.0); // Test woe normalization Assert.assertEquals(Normalizer.normalize(config, "3.0", null, NormType.WEIGHT_WOE).get(0), 21.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", null, NormType.WEIGHT_WOE).get(0), 16.5); Assert.assertEquals(Normalizer.normalize(config, null, null, NormType.WEIGHT_WOE).get(0), 16.5); Assert.assertEquals(Normalizer.normalize(config, "3.0", null, NormType.WOE).get(0), 11.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", null, NormType.WOE).get(0), 6.5); Assert.assertEquals(Normalizer.normalize(config, null, null, NormType.WOE).get(0), 6.5); // Test hybrid normalization, for numerical use zscore. Assert.assertEquals(Normalizer.normalize(config, "5.0", 4.0, NormType.HYBRID).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "5.0", null, NormType.HYBRID).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 4.0, NormType.HYBRID).get(0), 0.0); Assert.assertEquals(Normalizer.normalize(config, null, 4.0, NormType.HYBRID).get(0), 0.0); // Currently WEIGHT_HYBRID and HYBRID act same for numerical value, both calculate zscore. Assert.assertEquals(Normalizer.normalize(config, "5.0", 4.0, NormType.WEIGHT_HYBRID).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "5.0", null, NormType.WEIGHT_HYBRID).get(0), 3.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 4.0, NormType.WEIGHT_HYBRID).get(0), 0.0); Assert.assertEquals(Normalizer.normalize(config, null, 4.0, NormType.WEIGHT_HYBRID).get(0), 0.0); // Test woe zscore normalization // Assert.assertEquals(Normalizer.normalize(config, "3.0", 10.0, NormType.WOE_ZSCORE), 0.2); // Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 12.0, NormType.WOE_ZSCORE), -1.6); // Assert.assertEquals(Normalizer.normalize(config, null, 12.0, NormType.WOE_ZSCORE), -1.6); // // Assert.assertEquals(Normalizer.normalize(config, "3.0", 20.0, NormType.WEIGHT_WOE_ZSCORE), 0.2); // Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 22.0, NormType.WEIGHT_WOE_ZSCORE), -1.6); // Assert.assertEquals(Normalizer.normalize(config, null, 22.0, NormType.WEIGHT_WOE_ZSCORE), -1.6); } @Test public void categoricalNormalizeTest() { // Input setting ColumnConfig config = new ColumnConfig(); config.setMean(0.2); config.setStdDev(1.0); config.setColumnType(ColumnType.C); ColumnBinning cbin = new ColumnBinning(); cbin.setBinCountWoe(Arrays.asList(new Double[] { 10.0, 11.0, 12.0, 13.0, 6.5 })); cbin.setBinWeightedWoe(Arrays.asList(new Double[] { 20.0, 21.0, 22.0, 23.0, 16.5 })); cbin.setBinCategory(Arrays.asList(new String[] { "a", "b", "c", "d" })); cbin.setBinPosRate(Arrays.asList(new Double[] { 0.2, 0.4, 0.8, 1.0 })); cbin.setBinCountNeg(Arrays.asList(1, 2, 3, 4, 5)); cbin.setBinCountPos(Arrays.asList(5, 4, 3, 2, 1)); config.setColumnBinning(cbin); // Test zscore normalization Assert.assertEquals(Normalizer.normalize(config, "b", 4.0, NormType.ZSCALE).get(0), 0.2); Assert.assertEquals(Normalizer.normalize(config, "b", null, NormType.ZSCALE).get(0), 0.2); Assert.assertEquals( Normalizer.normalize(config, "wrong_format", 4.0, NormType.ZSCALE, CategoryMissingNormType.MEAN).get(0), 0.0); Assert.assertEquals( Normalizer.normalize(config, null, 4.0, NormType.ZSCALE, CategoryMissingNormType.MEAN).get(0), 0.0); // Test old zscore normalization Assert.assertEquals(Normalizer.normalize(config, "b", 4.0, NormType.OLD_ZSCALE).get(0), 0.4); Assert.assertEquals(Normalizer.normalize(config, "b", null, NormType.OLD_ZSCALE).get(0), 0.4); Assert.assertEquals(Normalizer .normalize(config, "wrong_format", 4.0, NormType.OLD_ZSCALE, CategoryMissingNormType.MEAN).get(0), 0.2); Assert.assertEquals( Normalizer.normalize(config, null, 4.0, NormType.OLD_ZSCALE, CategoryMissingNormType.MEAN).get(0), 0.2); // Test woe normalization Assert.assertEquals(Normalizer.normalize(config, "c", null, NormType.WEIGHT_WOE).get(0), 22.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", null, NormType.WEIGHT_WOE).get(0), 16.5); Assert.assertEquals(Normalizer.normalize(config, null, null, NormType.WEIGHT_WOE).get(0), 16.5); Assert.assertEquals(Normalizer.normalize(config, "c", null, NormType.WOE).get(0), 12.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", null, NormType.WOE).get(0), 6.5); Assert.assertEquals(Normalizer.normalize(config, null, null, NormType.WOE).get(0), 6.5); // Test hybrid normalization, for categorical value use [weight]woe. Assert.assertEquals(Normalizer.normalize(config, "a", null, NormType.HYBRID).get(0), 10.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", null, NormType.HYBRID).get(0), 6.5); Assert.assertEquals(Normalizer.normalize(config, null, null, NormType.HYBRID).get(0), 6.5); Assert.assertEquals(Normalizer.normalize(config, "a", null, NormType.WEIGHT_HYBRID).get(0), 20.0); Assert.assertEquals(Normalizer.normalize(config, "wrong_format", null, NormType.WEIGHT_HYBRID).get(0), 16.5); Assert.assertEquals(Normalizer.normalize(config, null, null, NormType.WEIGHT_HYBRID).get(0), 16.5); // Test woe zscore normalization // Assert.assertEquals(Normalizer.normalize(config, "b", 12.0, NormType.WOE_ZSCORE), 0.2); // Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 13.0, NormType.WOE_ZSCORE), -1.6); // Assert.assertEquals(Normalizer.normalize(config, null, 13.0, NormType.WOE_ZSCORE), -1.6); // // Assert.assertEquals(Normalizer.normalize(config, "b", 22.0, NormType.WEIGHT_WOE_ZSCORE), 0.2); // Assert.assertEquals(Normalizer.normalize(config, "wrong_format", 23.0, NormType.WEIGHT_WOE_ZSCORE), -1.6); // Assert.assertEquals(Normalizer.normalize(config, null, 23.0, NormType.WEIGHT_WOE_ZSCORE), -1.6); } @Test public void testAsIsNorm() { // Input setting ColumnConfig config = new ColumnConfig(); config.setMean(0.2); config.setStdDev(1.0); config.setColumnType(ColumnType.N); Assert.assertEquals(Normalizer.normalize(config, "10", null , NormType.ASIS_PR).get(0), 10.0); Assert.assertEquals(Normalizer.normalize(config, "10", null , NormType.ASIS_WOE).get(0), 10.0); Assert.assertEquals(Normalizer.normalize(config, "10ab", null , NormType.ASIS_WOE).get(0), 0.2); config.setColumnType(ColumnType.C); config.setBinCategory(Arrays.asList(new String[]{"a", "b", "c"})); config.getColumnBinning().setBinCountWoe(Arrays.asList(new Double[]{0.2, 0.3, -0.1, 0.5})); config.getColumnBinning().setBinPosRate(Arrays.asList(new Double[]{0.1, 0.15, 0.4, 0.25})); Assert.assertEquals(Normalizer.normalize(config, "b", null , NormType.ASIS_PR).get(0), 0.15); Assert.assertEquals(Normalizer.normalize(config, "", null , NormType.ASIS_PR).get(0), 0.25); Assert.assertEquals(Normalizer.normalize(config, "c", null , NormType.ASIS_PR).get(0), 0.4); Assert.assertEquals(Normalizer.normalize(config, "b", null , NormType.ASIS_WOE).get(0), 0.3); Assert.assertEquals(Normalizer.normalize(config, "", null , NormType.ASIS_WOE).get(0), 0.5); Assert.assertEquals(Normalizer.normalize(config, "c", null , NormType.ASIS_WOE).get(0), -0.1); } }
53.787879
120
0.669698
81fdb5c9cf4ae78658cf8a4e81db9488f379c382
7,440
/* * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.springframework.data.gemfire.search.lucene; import static org.assertj.core.api.Assertions.assertThat; import java.io.Serializable; import java.time.LocalDate; import java.time.Month; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import lombok.Data; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.geode.cache.GemFireCache; import org.apache.geode.cache.Region; import org.apache.geode.cache.lucene.LuceneService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.DependsOn; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.data.annotation.Id; import org.springframework.data.gemfire.PartitionedRegionFactoryBean; import org.springframework.data.gemfire.config.annotation.PeerCacheApplication; import org.springframework.data.gemfire.util.SpringUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; /** * Integration tests for the Spring Data Geode, Apache Geode and Apache Lucene Integration. * * @author John Blum * @see org.junit.Test * @see lombok * @see org.apache.geode.cache.GemFireCache * @see org.apache.geode.cache.Region * @see org.apache.geode.cache.lucene.LuceneIndex * @see org.springframework.data.gemfire.config.annotation.PeerCacheApplication * @see org.springframework.test.context.ContextConfiguration * @see org.springframework.test.context.junit4.SpringRunner * @since 1.1.0 */ @RunWith(SpringRunner.class) @ContextConfiguration @SuppressWarnings("unused") public class LuceneOperationsIntegrationTests { private static final AtomicLong IDENTIFIER = new AtomicLong(0L); protected static final String GEMFIRE_LOG_LEVEL = "none"; private static Person jonDoe = Person.newPerson(LocalDate.of(1969, Month.JULY, 4), "Jon", "Doe").with("Master of Science"); private static Person janeDoe = Person.newPerson(LocalDate.of(1969, Month.AUGUST, 16), "Jane", "Doe").with("Doctor of Astrophysics"); private static Person cookieDoe = Person.newPerson(LocalDate.of(1991, Month.APRIL, 2), "Cookie", "Doe").with("Bachelor of Physics"); private static Person froDoe = Person.newPerson(LocalDate.of(1988, Month.MAY, 25), "Fro", "Doe").with("Doctor of Computer Science"); private static Person hoDoe = Person.newPerson(LocalDate.of(1984, Month.NOVEMBER, 11), "Ho", "Doe").with("Doctor of Math"); private static Person pieDoe = Person.newPerson(LocalDate.of(1996, Month.JUNE, 4), "Pie", "Doe").with("Master of Astronomy"); private static Person sourDoe = Person.newPerson(LocalDate.of(1999, Month.DECEMBER, 1), "Sour", "Doe").with("Bachelor of Art"); private static List<String> asNames(List<? extends Nameable> nameables) { return nameables.stream() .map(Nameable::getName) .collect(Collectors.toList()); } private static List<User> asUsers(Person... people) { return Arrays.stream(people) .map(User::from) .collect(Collectors.toList()); } @Autowired private ProjectingLuceneOperations template; @Test public void findsDoctorDoesAsTypePersonSuccessfully() { Collection<Person> doctorDoes = template.queryForValues("title: Doctor*", "title"); assertThat(doctorDoes).isNotNull(); assertThat(doctorDoes).hasSize(3); assertThat(doctorDoes).contains(janeDoe, froDoe, hoDoe); } @Test @SuppressWarnings("all") public void findsMasterDoesAsTypeUserSuccessfully() { List<User> masterDoes = template.query("title: Master*", "title", User.class); assertThat(masterDoes).isNotNull(); assertThat(masterDoes).hasSize(2); assertThat(masterDoes.stream().allMatch(user -> user instanceof User)).isTrue(); assertThat(asNames(masterDoes)).containsAll(asNames(asUsers(jonDoe, pieDoe))); } @SuppressWarnings("unused") @PeerCacheApplication(name = "LuceneOperationsIntegrationTests", logLevel = GEMFIRE_LOG_LEVEL) static class TestConfiguration { @Bean(name = "People") @DependsOn("personTitleIndex") PartitionedRegionFactoryBean<Long, Person> peopleRegion(GemFireCache gemfireCache) { PartitionedRegionFactoryBean<Long, Person> peopleRegion = new PartitionedRegionFactoryBean<>(); peopleRegion.setCache(gemfireCache); peopleRegion.setClose(false); peopleRegion.setPersistent(false); return peopleRegion; } @Bean LuceneServiceFactoryBean luceneService(GemFireCache gemfireCache) { LuceneServiceFactoryBean luceneService = new LuceneServiceFactoryBean(); luceneService.setCache(gemfireCache); return luceneService; } @Bean LuceneIndexFactoryBean personTitleIndex(GemFireCache gemfireCache) { LuceneIndexFactoryBean luceneIndex = new LuceneIndexFactoryBean(); luceneIndex.setCache(gemfireCache); luceneIndex.setFields("title"); luceneIndex.setIndexName("PersonTitleIndex"); luceneIndex.setRegionPath("/People"); return luceneIndex; } @Bean @DependsOn("personTitleIndex") ProjectingLuceneOperations luceneTemplate() { return new ProjectingLuceneTemplate("PersonTitleIndex", "/People"); } @EventListener(ContextRefreshedEvent.class) @SuppressWarnings("unchecked") public void loadPeople(ContextRefreshedEvent event) { Region<Long, Person> people = event.getApplicationContext().getBean("People", Region.class); Arrays.asList(jonDoe, janeDoe, cookieDoe, froDoe, hoDoe, pieDoe, sourDoe) .forEach(person -> { person.setId(IDENTIFIER.incrementAndGet()); people.put(person.getId(), person); }); LuceneService luceneService = event.getApplicationContext().getBean("luceneService", LuceneService.class); boolean flushed = SpringUtils.safeGetValue(() -> { try { return luceneService.waitUntilFlushed("PersonTitleIndex", "/People", 15L, TimeUnit.SECONDS); } catch (Throwable ignore) { return false; } }); assertThat(flushed).describedAs("LuceneIndex not flushed!").isTrue(); } } interface Nameable { String getName(); } @Data @RequiredArgsConstructor(staticName = "newPerson") static class Person implements Nameable, Serializable { @Id Long id; @NonNull LocalDate birthDate; @NonNull String firstName; @NonNull String lastName; String title; public String getName() { return String.format("%1$s %2$s", getFirstName(), getLastName()); } Person with(String title) { setTitle(title); return this; } } interface User extends Nameable { static User from(Person person) { return person::getName; } } }
32.068966
134
0.760753
916ee785a39c9d44f6f87bfeb139407d781330c2
919
package com.arrival.unit.listener; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.TestListenerAdapter; /** * @author: Aaron Kutekidila * @version: 1.0 * Created: 27.11.2015. * @since: 1.0 * Package: com.arrival.unit.listener */ public class TestListener extends TestListenerAdapter { /* @Override public void onTestStart(ITestResult arg0) { super.onTestStart(arg0); if (skipTests.contains(arg0.getMethod().getDescription())){ throw new SkipException("Skipping Test: " + arg0.getMethod().getDescription()); } } @Override public void onTestSkiped(ITestResult arg0) { super.onTestStart(arg0); if (skipTests.contains(arg0.getMethod().getDescription())){ throw new SkipException("Skipping Test: " + arg0.getMethod().getDescription()); } }*/ }
26.257143
67
0.639826
d15469b244be11da4e29e33bbaa3e5e74394d8c5
3,424
package org.dncf.client; import org.dncf.handler.ChildChannelHandler; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.net.InetSocketAddress; /** * Created by LJT on 17-6-6. * email: [email protected] */ @Component @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public class DNCNettyClient { private static Logger logger = LoggerFactory.getLogger(DNCNettyClient.class); @Autowired @Qualifier("bootstrap") private Bootstrap bootstrap; @Autowired @Qualifier("workerGroup") private EventLoopGroup workerGroup; @Autowired private InetSocketAddress address; @Autowired private ChildChannelHandler initializer; @Value("${server.ip:127.0.0.1}") private String host; @Value("${server.port:8888}") private int port; private Channel channel; public void start() throws Exception { try { logger.info("[info] >>> start netty client."); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(initializer); logger.info("[info] >>> set netty client params"); bootstrap.option(ChannelOption.SO_BACKLOG, 65535); //keep connect bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.TCP_NODELAY, true); channel = bootstrap.connect(host, port).syncUninterruptibly().channel(); } catch (Exception e) { e.printStackTrace(); logger.error("[info] >>> netty client start fail."); } } public void destroy() { try { if (channel != null) { channel.close(); } workerGroup.shutdownGracefully(); } catch (Exception e) { e.printStackTrace(); logger.error("[info] >>> destroy netty server exception." + e.getMessage()); } } private void checkConnect() { if (channel != null && channel.isActive()) return; //fast reconnect while (true) { try { channel = bootstrap.connect(host, port).syncUninterruptibly().channel(); if (channel == null || !channel.isActive()) { Thread.sleep(10); continue; } break; } catch (InterruptedException e) { e.printStackTrace(); } } } public void send(Object obj) { //check and reconnect checkConnect(); //send message; send2Server(obj); } private void send2Server(Object obj) { channel.writeAndFlush(obj); } }
28.533333
88
0.634346
08425648c432d174d71a2b28240dc72e94dfc782
2,125
/* * Copyright 2017 Bahman Movaqar * * 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.bahmanm.utils.geometry; import java.util.Arrays; /** * Represents a point in an n-dimensional metric space.<br> * * @author Bahman Movaqar <Bahman AT BahmanM.com> */ public class Point { /** coordinates on each dimension */ final private double[] coords; /** number of dimensions */ final private int dims; /** * Creates a Point using the given coordinates.<br> * * @param coords the given coordinates */ public Point(double[] coords) { assert(coords != null && coords.length != 0); this.coords = coords; dims = coords.length; } /** * Get number of dimensions. * * @return number of dimensions */ public int getDims() { return dims; } /** * Get coordinate value of a given dimension. * * @param dim the given dimension (first dimension is 0) * @return the coordinate value */ public double getCoord(int dim) { return coords[dim]; } @Override public int hashCode() { return Arrays.hashCode(coords) + dims; } @Override public boolean equals(Object obj) { if (obj == this) return true; else if (obj == null || obj.getClass() != Point.class) return false; else { Point other = (Point) obj; return dims == other.dims && Arrays.equals(coords, other.coords); } } @Override public Point clone() throws CloneNotSupportedException { return (Point) super.clone(); } @Override public String toString() { return "Point" + Arrays.toString(coords); } }
23.351648
75
0.660706
17660f5697b1ccac645ee3ee14115c6a9bfe65a4
3,276
package properties; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.regex.Pattern; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import ui.CommonUi; import ui.TreeComponentsFactory; public class Help { private static volatile Help help; private TreeView<String> tree; private Help() { } public static Help getInstance() { if (help == null) { help = new Help(); } return help; } private static String getHelpText(TreeItem<String> selectResult) { String helpTitle = selectResult.getValue(); String helpText = ""; int helpId = -1; for (HelpSection helpSection : HelpSection.values()) { if (helpTitle.equals(helpSection.getHelpTitle())) { helpId = helpSection.getHelpId(); break; } } try (InputStream inStream = Help.class.getResourceAsStream("/helptext.txt")) { BufferedReader buf = new BufferedReader(new InputStreamReader(inStream)); StringBuilder sb = new StringBuilder(); String line; while ((line = buf.readLine()) != null) { if (line.trim().equals("help " + helpId)) { line = buf.readLine(); while (line != null && !Pattern.matches("help \\d+", line.trim())) { //$NON-NLS-1$ sb.append(line).append("\n"); line = buf.readLine(); } } } helpText = sb.toString(); } catch (IOException e) { e.printStackTrace(); } return helpText; } @SuppressWarnings("unused") public void display(Stage window) { TreeComponentsFactory<String> treeBuilder = new TreeComponentsFactory<String>(); // Root TreeItem<String> treeRoot = new TreeItem<String>(); treeRoot.setExpanded(true); // General TreeItem<String> generalBranch = treeBuilder.buildBranch("General", treeRoot); List<HelpSection> helpTitles = HelpSection.getAllHelpSectionsinCategory(HelpSection.HelpCategory.GENERAL); for (HelpSection helpTitle : helpTitles) { treeBuilder.buildBranch(helpTitle.getHelpTitle(), generalBranch); } // Connections TreeItem<String> connectionBranch = treeBuilder.buildBranch("Connection", treeRoot); // Help description Label descripLabel = new Label(); descripLabel.setPadding(new Insets(20)); // Set the tree view and its event listener this.tree = new TreeView<String>(treeRoot); this.tree.setShowRoot(false); this.tree.setMaxWidth(600); this.tree.getSelectionModel().selectedItemProperty() .addListener((results, oldResult, selectResult) -> { descripLabel.setText(Help.getHelpText(selectResult)); }); Button backButton = CommonUi.buildBackToHomeButton(); BorderPane borderPane = new BorderPane(); borderPane.setLeft(this.tree); borderPane.setCenter(descripLabel); borderPane.setBottom(backButton); BorderPane.setAlignment(backButton, Pos.CENTER); BorderPane.setAlignment(descripLabel, Pos.TOP_CENTER); Scene scene = new Scene(borderPane, 600, 600); window.setScene(scene); window.show(); } }
27.3
108
0.715812
c035ad4d5e2397009901df8ab13d71ed79230222
9,718
/******************************************************************************* * Cloud Foundry * Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product includes a number of subcomponents with * separate copyright notices and license terms. Your use of these * subcomponents is subject to the terms and conditions of the * subcomponent's license, as noted in the LICENSE file. *******************************************************************************/ package org.cloudfoundry.identity.uaa.login; import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory; import org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory; import org.cloudfoundry.identity.uaa.config.YamlPropertiesFactoryBean; import org.cloudfoundry.identity.uaa.login.saml.IdentityProviderConfigurator; import org.cloudfoundry.identity.uaa.login.saml.IdentityProviderDefinition; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.security.saml.log.SAMLDefaultLogger; import org.springframework.util.StringUtils; import org.springframework.web.servlet.ViewResolver; import java.io.File; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * @author Dave Syer * */ public class BootstrapTests { private GenericXmlApplicationContext context; @Before public void setup() throws Exception { System.clearProperty("spring.profiles.active"); } @After public void cleanup() throws Exception { System.clearProperty("spring.profiles.active"); if (context != null) { context.close(); } Set<String> removeme = new HashSet<>(); for ( Map.Entry<Object,Object> entry : System.getProperties().entrySet()) { if (entry.getKey().toString().startsWith("login.")) { removeme.add(entry.getKey().toString()); } } for (String s : removeme) { System.clearProperty(s); } } @Test public void testRootContextDefaults() throws Exception { context = getServletContext(null, "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); assertNotNull(context.getBean("viewResolver", ViewResolver.class)); assertNotNull(context.getBean("resetPasswordController", ResetPasswordController.class)); } @Test public void testSamlProfileNoData() throws Exception { System.setProperty("login.saml.metadataTrustCheck", "false"); context = getServletContext("default", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); Assume.assumeTrue(context.getEnvironment().getProperty("login.idpMetadataURL")==null); assertNotNull(context.getBean("viewResolver", ViewResolver.class)); assertNotNull(context.getBean("samlLogger", SAMLDefaultLogger.class)); assertFalse(context.getBean(IdentityProviderConfigurator.class).isLegacyMetadataTrustCheck()); assertEquals(0, context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().size()); } @Test public void testLegacySamlHttpMetaUrl() throws Exception { System.setProperty("login.saml.metadataTrustCheck", "false"); System.setProperty("login.idpMetadataURL", "http://localhost:9696/nodata"); System.setProperty("login.idpEntityAlias", "testIDPFile"); context = getServletContext("default", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); assertNotNull(context.getBean("viewResolver", ViewResolver.class)); assertNotNull(context.getBean("samlLogger", SAMLDefaultLogger.class)); assertFalse(context.getBean(IdentityProviderConfigurator.class).isLegacyMetadataTrustCheck()); assertEquals( DefaultProtocolSocketFactory.class.getName(), context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().get(0).getSocketFactoryClassName() ); assertEquals( IdentityProviderDefinition.MetadataLocation.URL, context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().get(0).getType() ); } @Test public void testLegacySamlProfileMetadataFile() throws Exception { System.setProperty("login.idpMetadataFile", "./src/test/resources/test.saml.metadata"); System.setProperty("login.idpEntityAlias", "testIDPFile"); System.setProperty("login.saml.metadataTrustCheck", "false"); context = getServletContext("saml,fileMetadata", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); assertNotNull(context.getBean("viewResolver", ViewResolver.class)); assertNotNull(context.getBean("samlLogger", SAMLDefaultLogger.class)); assertFalse(context.getBean(IdentityProviderConfigurator.class).isLegacyMetadataTrustCheck()); assertEquals( IdentityProviderDefinition.MetadataLocation.FILE, context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().get(0).getType()); } @Test public void testLegacySamlProfileMetadataConfig() throws Exception { String metadataString = new Scanner(new File("./src/main/resources/sample-okta-localhost.xml")).useDelimiter("\\Z").next(); System.setProperty("login.idpMetadata", metadataString); System.setProperty("login.idpEntityAlias", "testIDPData"); context = getServletContext("saml,configMetadata", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); assertEquals( IdentityProviderDefinition.MetadataLocation.DATA, context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().get(0).getType()); } @Test public void testLegacySamlProfileHttpsMetaUrl() throws Exception { System.setProperty("login.saml.metadataTrustCheck", "false"); System.setProperty("login.idpMetadataURL", "https://localhost:9696/nodata"); System.setProperty("login.idpEntityAlias", "testIDPUrl"); context = getServletContext("default", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); assertNotNull(context.getBean("viewResolver", ViewResolver.class)); assertNotNull(context.getBean("samlLogger", SAMLDefaultLogger.class)); assertFalse(context.getBean(IdentityProviderConfigurator.class).isLegacyMetadataTrustCheck()); assertEquals( EasySSLProtocolSocketFactory.class.getName(), context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().get(0).getSocketFactoryClassName() ); assertEquals( IdentityProviderDefinition.MetadataLocation.URL, context.getBean(IdentityProviderConfigurator.class).getIdentityProviderDefinitions().get(0).getType() ); } @Test public void testMessageService() throws Exception { context = getServletContext("default", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); Object messageService = context.getBean("messageService"); assertNotNull(messageService); assertEquals(EmailService.class, messageService.getClass()); System.setProperty("notifications.url", ""); context = getServletContext("default", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); messageService = context.getBean("messageService"); assertNotNull(messageService); assertEquals(EmailService.class, messageService.getClass()); System.setProperty("notifications.url", "example.com"); context = getServletContext("default", "./src/main/resources/login.yml", "file:./src/main/webapp/WEB-INF/spring-servlet.xml"); messageService = context.getBean("messageService"); assertNotNull(messageService); assertEquals(NotificationsService.class, messageService.getClass()); } private GenericXmlApplicationContext getServletContext(String profiles, String loginYmlPath, String... resources) { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); if (profiles != null) { context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles)); } context.load(resources); // Simulate what happens in the webapp when the // YamlServletProfileInitializer kicks in YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new Resource[] { new FileSystemResource(loginYmlPath) }); context.getEnvironment().getPropertySources() .addLast(new PropertiesPropertySource("servletProperties", factory.getObject())); context.refresh(); return context; } }
48.834171
146
0.708479
19d0855a57ae221ca127f58520c94fcf7057c658
4,779
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.generated; import com.microsoft.graph.concurrency.*; import com.microsoft.graph.core.*; import com.microsoft.graph.extensions.*; import com.microsoft.graph.http.*; import com.microsoft.graph.generated.*; import com.microsoft.graph.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Base Education Root Request. */ public class BaseEducationRootRequest extends BaseRequest implements IBaseEducationRootRequest { /** * The request for the EducationRoot * * @param requestUrl The request url * @param client The service client * @param requestOptions The options for this request * @param responseClass The class of the reponse */ public BaseEducationRootRequest(final String requestUrl, final IBaseClient client, final java.util.List<Option> requestOptions, final Class responseClass) { super(requestUrl, client, requestOptions, responseClass); } /** * Gets the EducationRoot from the service * @param callback The callback to be called after success or failure. */ public void get(final ICallback<EducationRoot> callback) { send(HttpMethod.GET, callback, null); } /** * Gets the EducationRoot from the service * @return The EducationRoot from the request. * @throws ClientException This exception occurs if the request was unable to complete for any reason. */ public EducationRoot get() throws ClientException { return send(HttpMethod.GET, null); } /** * Delete this item from the service. * @param callback The callback when the deletion action has completed */ public void delete(final ICallback<Void> callback) {{ send(HttpMethod.DELETE, callback, null); }} /** * Delete this item from the service. * @throws ClientException if there was an exception during the delete operation */ public void delete() throws ClientException {{ send(HttpMethod.DELETE, null); }} /** * Patches this EducationRoot with a source * @param sourceEducationRoot The source object with updates * @param callback The callback to be called after success or failure. */ public void patch(final EducationRoot sourceEducationRoot, final ICallback<EducationRoot> callback) { send(HttpMethod.PATCH, callback, sourceEducationRoot); } /** * Patches this EducationRoot with a source * @param sourceEducationRoot The source object with updates * @return The updated EducationRoot * @throws ClientException This exception occurs if the request was unable to complete for any reason. */ public EducationRoot patch(final EducationRoot sourceEducationRoot) throws ClientException { return send(HttpMethod.PATCH, sourceEducationRoot); } /** * Creates a EducationRoot with a new object * @param newEducationRoot The new object to create * @param callback The callback to be called after success or failure. */ public void post(final EducationRoot newEducationRoot, final ICallback<EducationRoot> callback) { send(HttpMethod.POST, callback, newEducationRoot); } /** * Creates a EducationRoot with a new object * @param newEducationRoot The new object to create * @return The created EducationRoot * @throws ClientException This exception occurs if the request was unable to complete for any reason. */ public EducationRoot post(final EducationRoot newEducationRoot) throws ClientException { return send(HttpMethod.POST, newEducationRoot); } /** * Sets the select clause for the request * * @param value The select clause * @return The updated request */ public IEducationRootRequest select(final String value) { getQueryOptions().add(new QueryOption("$select", value)); return (EducationRootRequest)this; } /** * Sets the expand clause for the request * * @param value The expand clause * @return The updated request */ public IEducationRootRequest expand(final String value) { getQueryOptions().add(new QueryOption("$expand", value)); return (EducationRootRequest)this; } }
35.4
152
0.67127
cb13d81ed5d8c4ac255a3c00930c30e597b54058
638
package github.rpcappmodel.domain; import java.io.Serializable; public class DataIdTreeTuple implements Serializable { private static final long serialVersionUID = 1L; private int dataType = 0; private int subDataType = 0; private long dataId = 0; public int getDataType() { return dataType; } public void setDataType(int dataType) { this.dataType = dataType; } public int getSubDataType() { return subDataType; } public void setSubDataType(int subDataType) { this.subDataType = subDataType; } public long getDataId() { return dataId; } public void setDataId(long dataId) { this.dataId = dataId; } }
17.243243
54
0.731975
c97ff6116af0ba457cab6933110d6cba3f351d2b
16,730
package org.kuali.coeus.propdev.impl.budget.nonpersonnel; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.common.budget.framework.core.Budget; import org.kuali.coeus.common.budget.framework.core.BudgetConstants; import org.kuali.coeus.common.budget.framework.nonpersonnel.ApplyToPeriodsBudgetEvent; import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetDirectCostLimitEvent; import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetLineItem; import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetPeriodCostLimitEvent; import org.kuali.coeus.common.budget.framework.period.BudgetPeriod; import org.kuali.coeus.common.budget.impl.nonpersonnel.BudgetExpensesRuleEvent; import org.kuali.coeus.propdev.impl.budget.core.ProposalBudgetControllerBase; import org.kuali.coeus.propdev.impl.budget.core.ProposalBudgetForm; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.rice.krad.uif.UifParameters; import org.kuali.rice.krad.web.form.DialogResponse; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "/proposalBudget") public class ProposalBudgetPeriodProjectCostController extends ProposalBudgetControllerBase { private static final String EDIT_NONPERSONNEL_PERIOD_DIALOG_ID = "PropBudget-NonPersonnelCostsPage-EditNonPersonnel-Dialog"; private static final String EDIT_NONPERSONNEL_PARTICIPANT_DIALOG_ID = "PropBudget-NonPersonnelCostsPage-EditParticipantSupport-Dialog"; protected static final String CONFIRM_PERIOD_CHANGES_DIALOG_ID = "PropBudget-ConfirmPeriodChangesDialog"; protected static final String ADD_NONPERSONNEL_PERIOD_DIALOG_ID = "PropBudget-NonPersonnelCostsPage-AddNonPersonnel-Dialog"; protected static final String CONFIRM_SYNC_TO_PERIOD_COST_LIMIT_DIALOG_ID = "PropBudget-NonPersonnelCosts-SyncToPeriodCostLimit"; protected static final String CONFIRM_SYNC_TO_DIRECT_COST_LIMIT_DIALOG_ID = "PropBudget-NonPersonnelCosts-SyncToDirectCostLimit"; @Transactional @RequestMapping(params="methodToCall=assignLineItemToPeriod") public ModelAndView assignLineItemToPeriod(@RequestParam("budgetPeriodId") String budgetPeriodId, @ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { ModelAndView modelAndView = getModelAndViewService().getModelAndView(form); Budget budget = form.getBudget(); Long currentTabBudgetPeriodId = Long.parseLong(budgetPeriodId); BudgetPeriod budgetPeriod = getBudgetPeriod(currentTabBudgetPeriodId, budget); DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_PERIOD_CHANGES_DIALOG_ID); if(dialogResponse == null && budgetPeriod.getBudgetPeriod() > 1 && !isBudgetLineItemExists(budget)) { modelAndView = getModelAndViewService().showDialog(CONFIRM_PERIOD_CHANGES_DIALOG_ID, true, form); }else { boolean confirmResetDefault = dialogResponse == null ? true : dialogResponse.getResponseAsBoolean(); if(confirmResetDefault) { form.getAddProjectBudgetLineItemHelper().reset(); form.getAddProjectBudgetLineItemHelper().setCurrentTabBudgetPeriod(budgetPeriod); modelAndView = getModelAndViewService().showDialog(ADD_NONPERSONNEL_PERIOD_DIALOG_ID, true, form); } } return modelAndView; } @Transactional @RequestMapping(params="methodToCall=addLineItemToPeriod") public ModelAndView addLineItemToPeriod(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); BudgetPeriod currentTabBudgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); BudgetLineItem newBudgetLineItem = form.getAddProjectBudgetLineItemHelper().getBudgetLineItem(); newBudgetLineItem.setBudget(budget); getBudgetService().populateNewBudgetLineItem(newBudgetLineItem, currentTabBudgetPeriod); currentTabBudgetPeriod.getBudgetLineItems().add(newBudgetLineItem); getBudgetCalculationService().populateCalculatedAmount(budget, newBudgetLineItem); getBudgetService().recalculateBudgetPeriod(budget, currentTabBudgetPeriod); form.getAddProjectBudgetLineItemHelper().reset(); validateBudgetExpenses(budget, currentTabBudgetPeriod); return getModelAndViewService().getModelAndView(form); } @Transactional @RequestMapping(params="methodToCall=editNonPersonnelPeriodDetails") public ModelAndView editNonPersonnelPeriodDetails(@RequestParam("budgetPeriodId") String budgetPeriodId, @ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); String selectedLine = form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX); if (StringUtils.isNotEmpty(selectedLine)) { Long currentTabBudgetPeriodId = Long.parseLong(budgetPeriodId); BudgetPeriod budgetPeriod = getBudgetPeriod(currentTabBudgetPeriodId, budget); form.getAddProjectBudgetLineItemHelper().reset(); BudgetLineItem editBudgetLineItem = form.getBudget().getBudgetLineItems().get(Integer.parseInt(selectedLine)); String editLineIndex = Integer.toString(budgetPeriod.getBudgetLineItems().indexOf(editBudgetLineItem)); form.getAddProjectBudgetLineItemHelper().setBudgetLineItem(getDataObjectService().copyInstance(editBudgetLineItem)); form.getAddProjectBudgetLineItemHelper().setEditLineIndex(editLineIndex); form.getAddProjectBudgetLineItemHelper().setCurrentTabBudgetPeriod(budgetPeriod); form.getAddProjectBudgetLineItemHelper().setBudgetCategoryTypeCode(editBudgetLineItem.getBudgetCategory().getBudgetCategoryTypeCode()); } return getModelAndViewService().showDialog(EDIT_NONPERSONNEL_PERIOD_DIALOG_ID, true, form); } @Transactional @RequestMapping(params="methodToCall=deleteBudgetLineItem") public ModelAndView deleteBudgetLineItem(@RequestParam("budgetPeriodId") String budgetPeriodId, @ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); String selectedLine = form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX); if (StringUtils.isNotEmpty(selectedLine)) { BudgetLineItem deletedBudgetLineItem = form.getBudget().getBudgetLineItems().get(Integer.parseInt(selectedLine)); Long currentTabBudgetPeriodId = Long.parseLong(budgetPeriodId); BudgetPeriod budgetPeriod = getBudgetPeriod(currentTabBudgetPeriodId, budget); budgetPeriod.getBudgetLineItems().remove(deletedBudgetLineItem); validateBudgetExpenses(budget, budgetPeriod); form.setAjaxReturnType("update-page"); } return getModelAndViewService().getModelAndView(form); } @Transactional @RequestMapping(params="methodToCall=saveBudgetLineItem") public ModelAndView saveBudgetLineItem(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { setEditedBudgetLineItem(form); Budget budget = form.getBudget(); BudgetPeriod budgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); validateBudgetExpenses(budget, budgetPeriod); return getModelAndViewService().getModelAndView(form); } protected void validateBudgetExpenses(Budget budget, BudgetPeriod budgetPeriod) { getBudgetCalculationService().calculateBudgetPeriod(budget, budgetPeriod); String errorPath = BudgetConstants.BudgetAuditRules.NON_PERSONNEL_COSTS.getPageId(); getKcBusinessRulesEngine().applyRules(new BudgetExpensesRuleEvent(budget, errorPath)); } @Transactional @RequestMapping(params="methodToCall=saveAndApplyToLaterPeriods") public ModelAndView saveAndApplyToLaterPeriods(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); BudgetPeriod currentTabBudgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); BudgetLineItem budgetLineItem = form.getAddProjectBudgetLineItemHelper().getBudgetLineItem(); setEditedBudgetLineItem(form); getBudgetCalculationService().applyToLaterPeriods(budget,currentTabBudgetPeriod,budgetLineItem); validateBudgetExpenses(budget, currentTabBudgetPeriod); return getModelAndViewService().getModelAndView(form); } private void setEditedBudgetLineItem(ProposalBudgetForm form) { BudgetLineItem budgetLineItem = form.getAddProjectBudgetLineItemHelper().getBudgetLineItem(); BudgetPeriod budgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); setLineItemBudgetCategory(budgetLineItem); int editLineIndex = Integer.parseInt(form.getAddProjectBudgetLineItemHelper().getEditLineIndex()); BudgetLineItem newBudgetLineItem = getDataObjectService().save(budgetLineItem); budgetPeriod.getBudgetLineItems().set(editLineIndex, newBudgetLineItem); } @Transactional @RequestMapping(params="methodToCall=syncToPeriodCostDirectLimit") public ModelAndView syncToPeriodCostDirectLimit(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); BudgetPeriod currentTabBudgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); int editLineIndex = Integer.parseInt(form.getAddProjectBudgetLineItemHelper().getEditLineIndex()); BudgetLineItem budgetLineItem = currentTabBudgetPeriod.getBudgetLineItems().get(editLineIndex); DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_SYNC_TO_DIRECT_COST_LIMIT_DIALOG_ID); if(dialogResponse == null && currentTabBudgetPeriod.getTotalDirectCost().isGreaterThan(currentTabBudgetPeriod.getDirectCostLimit())) { return getModelAndViewService().showDialog(CONFIRM_SYNC_TO_DIRECT_COST_LIMIT_DIALOG_ID, true, form); }else { boolean confirmResetDefault = dialogResponse == null ? true : dialogResponse.getResponseAsBoolean(); if(confirmResetDefault) { BudgetLineItem editedBudgetLineItem = form.getAddProjectBudgetLineItemHelper().getBudgetLineItem(); editedBudgetLineItem.setLineItemCost(budgetLineItem.getLineItemCost()); boolean rulePassed = getKcBusinessRulesEngine().applyRules(new ApplyToPeriodsBudgetEvent(budget, "addProjectBudgetLineItemHelper.budgetLineItem.", editedBudgetLineItem, currentTabBudgetPeriod)); rulePassed &= getKcBusinessRulesEngine().applyRules(new BudgetDirectCostLimitEvent(budget, currentTabBudgetPeriod, editedBudgetLineItem, "addProjectBudgetLineItemHelper.budgetLineItem.")); if(rulePassed) { boolean syncComplete = getBudgetCalculationService().syncToPeriodDirectCostLimit(budget, currentTabBudgetPeriod, editedBudgetLineItem); if(!syncComplete) { getGlobalVariableService().getMessageMap().putError("addProjectBudgetLineItemHelper.budgetLineItem.lineItemCost", KeyConstants.INSUFFICIENT_AMOUNT_TO_PERIOD_DIRECT_COST_LIMIT_SYNC); } } } } return getModelAndViewService().getModelAndView(form); } @Transactional @RequestMapping(params="methodToCall=syncToPeriodCostLimit") public ModelAndView syncToPeriodCostLimit(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); BudgetPeriod currentTabBudgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); int editLineIndex = Integer.parseInt(form.getAddProjectBudgetLineItemHelper().getEditLineIndex()); BudgetLineItem budgetLineItem = currentTabBudgetPeriod.getBudgetLineItems().get(editLineIndex); DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_SYNC_TO_PERIOD_COST_LIMIT_DIALOG_ID); if(dialogResponse == null && currentTabBudgetPeriod.getTotalCost().isGreaterThan(currentTabBudgetPeriod.getTotalCostLimit())) { return getModelAndViewService().showDialog(CONFIRM_SYNC_TO_PERIOD_COST_LIMIT_DIALOG_ID, true, form); }else { boolean confirmResetDefault = dialogResponse == null ? true : dialogResponse.getResponseAsBoolean(); if(confirmResetDefault) { BudgetLineItem editedBudgetLineItem = form.getAddProjectBudgetLineItemHelper().getBudgetLineItem(); editedBudgetLineItem.setLineItemCost(budgetLineItem.getLineItemCost()); boolean rulePassed = getKcBusinessRulesEngine().applyRules(new ApplyToPeriodsBudgetEvent(budget, "addProjectBudgetLineItemHelper.budgetLineItem.", editedBudgetLineItem, currentTabBudgetPeriod)); rulePassed &= getKcBusinessRulesEngine().applyRules(new BudgetPeriodCostLimitEvent(budget, currentTabBudgetPeriod, editedBudgetLineItem, "addProjectBudgetLineItemHelper.budgetLineItem.")); if(rulePassed) { boolean syncComplete = getBudgetCalculationService().syncToPeriodCostLimit(budget, currentTabBudgetPeriod, editedBudgetLineItem); if(!syncComplete) { getGlobalVariableService().getMessageMap().putError("addProjectBudgetLineItemHelper.budgetLineItem.lineItemCost", KeyConstants.INSUFFICIENT_AMOUNT_TO_SYNC); } } } } return getModelAndViewService().getModelAndView(form); } @Transactional @RequestMapping(params="methodToCall=editParticipantDetails") public ModelAndView editParticipantDetails(@RequestParam("budgetPeriodId") String budgetPeriodId, @ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { Budget budget = form.getBudget(); Long currentTabBudgetPeriodId = Long.parseLong(budgetPeriodId); BudgetPeriod currentTabBudgetPeriod = getBudgetPeriod(currentTabBudgetPeriodId, budget); form.getAddProjectBudgetLineItemHelper().setCurrentTabBudgetPeriod(currentTabBudgetPeriod); String editLineIndex = Integer.toString(budget.getBudgetPeriods().indexOf(currentTabBudgetPeriod)); form.getAddProjectBudgetLineItemHelper().setEditLineIndex(editLineIndex); return getModelAndViewService().showDialog(EDIT_NONPERSONNEL_PARTICIPANT_DIALOG_ID, true, form); } @Transactional @RequestMapping(params="methodToCall=saveParticipantDetails") public ModelAndView saveParticipantDetails(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception { BudgetPeriod currentTabBudgetPeriod = form.getAddProjectBudgetLineItemHelper().getCurrentTabBudgetPeriod(); getDataObjectService().save(currentTabBudgetPeriod); return getModelAndViewService().getModelAndView(form); } private BudgetPeriod getBudgetPeriod(Long currentTabBudgetPeriodId, Budget budget) { for(BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { if(budgetPeriod.getBudgetPeriodId().equals(currentTabBudgetPeriodId)) { return budgetPeriod; } } return null; } private void setLineItemBudgetCategory(BudgetLineItem budgetLineItem) { if (budgetCategoryChanged(budgetLineItem)) { getDataObjectService().wrap(budgetLineItem).fetchRelationship("budgetCategory"); budgetLineItem.getCostElementBO().setBudgetCategory(budgetLineItem.getBudgetCategory()); budgetLineItem.getCostElementBO().setBudgetCategoryCode(budgetLineItem.getBudgetCategoryCode()); } else if (costElementChanged(budgetLineItem)) { getDataObjectService().wrap(budgetLineItem).fetchRelationship("costElementBO"); budgetLineItem.setBudgetCategoryCode(budgetLineItem.getCostElementBO().getBudgetCategoryCode()); budgetLineItem.setBudgetCategory(budgetLineItem.getCostElementBO().getBudgetCategory()); } //if both changed then one has to win because the category code is in multiple places } protected boolean costElementChanged(BudgetLineItem budgetLineItem) { return !budgetLineItem.getCostElement().equals(budgetLineItem.getCostElementBO().getCostElement()); } protected boolean budgetCategoryChanged(BudgetLineItem budgetLineItem) { return !budgetLineItem.getBudgetCategoryCode().equals(budgetLineItem.getBudgetCategory().getCode()); } private boolean isBudgetLineItemExists(Budget budget) { boolean lineItemExists = false; for(BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { if(budgetPeriod.getBudgetPeriod() > 1 && budgetPeriod.getBudgetLineItems().size() > 0) { lineItemExists = true; break; } } return lineItemExists; } }
64.346154
182
0.793425
d9c1a31af83cd45770f417b774efa6daca01a053
2,530
package combos; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; public class ArchivoMunicipios { private static String nombreArchivo = "Municipios.dat"; private RandomAccessFile archivo; public ArchivoMunicipios() throws FileNotFoundException { this.archivo = new RandomAccessFile(nombreArchivo,"rw" ); } public ArchivoMunicipios(String nombreArchivo) throws FileNotFoundException { this.archivo = new RandomAccessFile(nombreArchivo,"rw" ); } public ArrayList<Municipio> leerMunicipios() throws Exception { ArrayList<Municipio> municipios = new ArrayList<Municipio>(); long longitudArchivo = archivo.length(); int longitudRenglon = 60; int cantidadRegistros = (int) (longitudArchivo/longitudRenglon); reiniciarPuntero(); for(int i = 0; i < cantidadRegistros; i++) { Municipio municipio = new Municipio(); municipio.setEstadoId(archivo.readInt()); municipio.setMunicipioId(archivo.readInt()); municipio.setNombreMunicipio(archivo.readUTF().trim()); municipios.add(municipio); } return municipios; } public ArrayList<Municipio> buscarMunicipios(int estadoId) throws Exception { ArrayList<Municipio> municipios = new ArrayList<Municipio>(); long longitudArchivo = archivo.length(); int longitudRenglon = 60; int cantidadRegistros = (int) (longitudArchivo/longitudRenglon); reiniciarPuntero(); for(int i = 0; i < cantidadRegistros; i++) { Municipio municipio = new Municipio(); municipio.setEstadoId(archivo.readInt()); municipio.setMunicipioId(archivo.readInt()); municipio.setNombreMunicipio(archivo.readUTF().trim()); if (municipio.getEstadoId() == estadoId) { municipios.add(municipio); } } return municipios; } public Municipio buscarMunicipio(int estadoId, String nombreMunicipio) throws Exception { Municipio municipio = new Municipio(); long longitudArchivo = archivo.length(); int longitudRenglon = 60; int cantidadRegistros = (int) (longitudArchivo/longitudRenglon); reiniciarPuntero(); for(int i = 0; i < cantidadRegistros; i++) { municipio.setEstadoId(archivo.readInt()); municipio.setMunicipioId(archivo.readInt()); municipio.setNombreMunicipio(archivo.readUTF().trim()); if (municipio.getNombreMunicipio().equals(nombreMunicipio) && municipio.getEstadoId() == estadoId) { return municipio; } } return null; } public void reiniciarPuntero() throws IOException { archivo.seek(0); } }
29.418605
103
0.739921
60d1d11fcfd44b66fd9a3a7e2a6fcfeb1032d2cd
17,621
package com.appnext.base.b; import android.app.ActivityManager; import android.app.AppOpsManager; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Process; import android.text.TextUtils; import com.appnext.base.a.b.c; import com.appnext.base.b.d; import com.appnext.base.operations.a; import com.appnext.base.operations.b; import com.appnext.core.f; import com.appnext.core.i; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import java.lang.reflect.InvocationTargetException; import java.net.HttpRetryException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.json.JSONArray; import org.json.JSONObject; public final class j { private static final String TAG = "SdkHelper"; private static final long eI = 1000; private static final long eJ = 60000; private static final long eK = 3600000; private static final long eL = 86400000; public static boolean a(String str, String str2, c cVar) { char c = 65535; try { if (str2.hashCode() == 570418373) { if (str2.equals(d.fn)) { c = 0; } } if (c != 0) { return false; } return ((a) Class.forName(b.B(str)).getConstructor(new Class[]{c.class, Bundle.class}).newInstance(new Object[]{cVar, null})).aE(); } catch (InvocationTargetException e) { e.getCause().printStackTrace(); e.getCause(); return false; } catch (ClassNotFoundException unused) { return false; } } public static boolean a(Class cls) { try { if (e.getContext().getPackageManager().queryIntentServices(new Intent(e.getContext(), cls), 65536).size() > 0) { return true; } return false; } catch (Throwable unused) { } } public static List<String> a(Context context, long j, long j2) { List<ActivityManager.RunningTaskInfo> runningTasks; ArrayList arrayList = new ArrayList(); if (context == null) { return arrayList; } try { ActivityManager activityManager = (ActivityManager) context.getSystemService("activity"); if (Build.VERSION.SDK_INT < 21) { if (f.a(e.getContext(), "android.permission.GET_TASKS") && (runningTasks = activityManager.getRunningTasks(20)) != null && !runningTasks.isEmpty()) { for (ActivityManager.RunningTaskInfo next : runningTasks) { if (!b(context, next.baseActivity.getPackageName())) { arrayList.add(next.baseActivity.getPackageName()); } } } } else if (Build.VERSION.SDK_INT >= 21 && f(context.getApplicationContext())) { UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService("usagestats"); long currentTimeMillis = System.currentTimeMillis(); List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(4, currentTimeMillis - j, currentTimeMillis); if (queryUsageStats == null) { return arrayList; } ListIterator<UsageStats> listIterator = queryUsageStats.listIterator(); while (listIterator.hasNext()) { UsageStats next2 = listIterator.next(); if (Build.VERSION.SDK_INT >= 23) { if (!usageStatsManager.isAppInactive(next2.getPackageName()) && next2.getTotalTimeInForeground() >= j2) { if (!b(context, next2.getPackageName())) { arrayList.add(next2.getPackageName()); } } listIterator.remove(); } } } } catch (Throwable unused) { } return arrayList; } private static boolean b(Context context, String str) { try { if (str.contains("com.android")) { return true; } PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent("android.intent.action.MAIN"); intent.addCategory("android.intent.category.HOME"); List<ResolveInfo> queryIntentActivities = packageManager.queryIntentActivities(intent, 65536); if (queryIntentActivities != null) { for (ResolveInfo next : queryIntentActivities) { if (next.activityInfo != null && next.activityInfo.packageName.equals(str)) { return true; } } } Intent intent2 = new Intent("android.intent.action.MAIN", (Uri) null); intent2.addCategory("android.intent.category.LAUNCHER"); List<ResolveInfo> queryIntentActivities2 = context.getPackageManager().queryIntentActivities(intent2, 0); if (queryIntentActivities2 != null) { Iterator<ResolveInfo> it = queryIntentActivities2.iterator(); while (true) { if (!it.hasNext()) { break; } ResolveInfo next2 = it.next(); if (next2.activityInfo != null && next2.activityInfo.packageName.equals(str)) { if ((next2.activityInfo.flags & 129) != 0) { return true; } } } } return false; } catch (Throwable unused) { } } public static boolean f(Context context) { return ((AppOpsManager) context.getSystemService("appops")).checkOpNoThrow("android:get_usage_stats", Process.myUid(), context.getPackageName()) == 0; } public static void g(Context context) { try { List<c> as = com.appnext.base.a.a.X().ab().as(); if (as != null && as.size() == 0) { c cVar = new c(d.fe, "1", d.fj, "1", d.fn, "cdm", "cdm" + System.currentTimeMillis(), (String) null); com.appnext.base.a.a.X().ab().a(cVar); com.appnext.base.services.b.a.d(context).a(cVar, true); } } catch (Throwable unused) { } } public static boolean h(Context context) throws Exception { AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); return advertisingIdInfo != null && advertisingIdInfo.isLimitAdTrackingEnabled(); } public static boolean i(Context context) { try { AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); if (advertisingIdInfo == null || advertisingIdInfo.isLimitAdTrackingEnabled()) { return true; } return false; } catch (Throwable unused) { } } public static boolean b(String str, Map<String, String> map) { c t = com.appnext.base.a.a.X().ab().t(str); if (t == null || d.ff.equalsIgnoreCase(t.ak()) || map.isEmpty()) { return true; } String str2 = i.hm + "/data"; HashMap hashMap = new HashMap(); String b = f.b(e.getContext(), true); if (TextUtils.isEmpty(b)) { b = i.aR().getString(i.fB, ""); } if (TextUtils.isEmpty(b)) { return false; } hashMap.put("aid", b); hashMap.put("cuid", b + "_" + System.currentTimeMillis()); hashMap.put("lvid", "4.7.2"); try { hashMap.put("localdate", a(new Date())); hashMap.put("timezone", aT()); hashMap.put("app_package", e.getPackageName()); } catch (Throwable unused) { hashMap.put("app_package", ""); } for (Map.Entry next : map.entrySet()) { hashMap.put((String) next.getKey(), (String) next.getValue()); } StringBuilder sb = new StringBuilder("-------Sending to server data for key = "); sb.append(str); sb.append(" ----------"); for (Map.Entry entry : hashMap.entrySet()) { StringBuilder sb2 = new StringBuilder("---- "); sb2.append((String) entry.getKey()); sb2.append(" : "); sb2.append((String) entry.getValue()); sb2.append(" ----"); } try { byte[] a2 = f.a(str2, (Object) hashMap, false, (int) d.fd, d.a.HashMap); if (a2 != null) { new StringBuilder("result send data: ").append(new String(a2, "UTF-8")); } return true; } catch (HttpRetryException e) { int responseCode = e.responseCode(); String message = e.getMessage(); StringBuilder sb3 = new StringBuilder("(Type:HttpRetryException)"); sb3.append(message); sb3.append(" "); sb3.append(responseCode); return false; } catch (Throwable th) { new StringBuilder("(Type:Throwable) ").append(th.getMessage()); return false; } } public static String aT() { StringBuilder sb = new StringBuilder(9); try { Calendar instance = Calendar.getInstance(TimeZone.getDefault(), Locale.US); int i = (instance.get(15) + instance.get(16)) / 60000; char c = '+'; if (i < 0) { c = '-'; i = -i; } sb.append("GMT"); sb.append(c); a(sb, 2, i / 60); sb.append(':'); a(sb, 2, i % 60); } catch (Throwable unused) { } return sb.toString(); } private static void a(StringBuilder sb, int i, int i2) { try { String num = Integer.toString(i2); for (int i3 = 0; i3 < 2 - num.length(); i3++) { sb.append('0'); } sb.append(num); } catch (Throwable unused) { } } public static String a(Date date) { StringBuilder sb = new StringBuilder(); try { sb.append(new SimpleDateFormat("EEE MMM dd HH:mm:ss", Locale.US).format(date)); sb.append(" "); sb.append(aT()); sb.append(" "); sb.append(new SimpleDateFormat("yyyy", Locale.US).format(date)); } catch (Throwable unused) { } return sb.toString(); } public static int g(String str, String str2) { long j; long j2; try { if (!TextUtils.isEmpty(str) && TextUtils.isDigitsOnly(str)) { if (!TextUtils.isEmpty(str2)) { int intValue = Integer.valueOf(str).intValue(); if (d.fh.equalsIgnoreCase(str2)) { return intValue; } if (d.fi.equalsIgnoreCase(str2)) { j = (long) intValue; j2 = eJ; } else if (d.fj.equalsIgnoreCase(str2)) { j = (long) intValue; j2 = eK; } else if (d.fk.equalsIgnoreCase(str2)) { j = (long) intValue; j2 = eL; } return (int) (j * j2); } } } catch (Throwable unused) { } return -1; } public static void a(String str, String str2, d.a aVar) { com.appnext.base.a.a.X().aa().b(new com.appnext.base.a.b.b(str, str2, aVar.getType())); } public static Object a(String str, d.a aVar) { try { List<com.appnext.base.a.b.b> v = com.appnext.base.a.a.X().aa().v(str); if (v == null || v.isEmpty()) { return null; } return b(v.get(0).ai(), aVar); } catch (Throwable unused) { return null; } } /* renamed from: com.appnext.base.b.j$1 reason: invalid class name */ static /* synthetic */ class AnonymousClass1 { static final /* synthetic */ int[] fF; /* JADX WARNING: Can't wrap try/catch for region: R(14:0|1|2|3|4|5|6|7|8|9|10|11|12|(3:13|14|16)) */ /* JADX WARNING: Can't wrap try/catch for region: R(16:0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|16) */ /* JADX WARNING: Failed to process nested try/catch */ /* JADX WARNING: Missing exception handler attribute for start block: B:11:0x003e */ /* JADX WARNING: Missing exception handler attribute for start block: B:13:0x0049 */ /* JADX WARNING: Missing exception handler attribute for start block: B:3:0x0012 */ /* JADX WARNING: Missing exception handler attribute for start block: B:5:0x001d */ /* JADX WARNING: Missing exception handler attribute for start block: B:7:0x0028 */ /* JADX WARNING: Missing exception handler attribute for start block: B:9:0x0033 */ static { /* com.appnext.base.b.d$a[] r0 = com.appnext.base.b.d.a.values() int r0 = r0.length int[] r0 = new int[r0] fF = r0 com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.Integer // Catch:{ NoSuchFieldError -> 0x0012 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0012 } r2 = 1 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0012 } L_0x0012: int[] r0 = fF // Catch:{ NoSuchFieldError -> 0x001d } com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.Double // Catch:{ NoSuchFieldError -> 0x001d } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x001d } r2 = 2 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x001d } L_0x001d: int[] r0 = fF // Catch:{ NoSuchFieldError -> 0x0028 } com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.Long // Catch:{ NoSuchFieldError -> 0x0028 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0028 } r2 = 3 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0028 } L_0x0028: int[] r0 = fF // Catch:{ NoSuchFieldError -> 0x0033 } com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.Boolean // Catch:{ NoSuchFieldError -> 0x0033 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0033 } r2 = 4 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0033 } L_0x0033: int[] r0 = fF // Catch:{ NoSuchFieldError -> 0x003e } com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.Set // Catch:{ NoSuchFieldError -> 0x003e } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x003e } r2 = 5 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x003e } L_0x003e: int[] r0 = fF // Catch:{ NoSuchFieldError -> 0x0049 } com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.JSONArray // Catch:{ NoSuchFieldError -> 0x0049 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0049 } r2 = 6 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0049 } L_0x0049: int[] r0 = fF // Catch:{ NoSuchFieldError -> 0x0054 } com.appnext.base.b.d$a r1 = com.appnext.base.b.d.a.JSONObject // Catch:{ NoSuchFieldError -> 0x0054 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0054 } r2 = 7 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0054 } L_0x0054: return */ throw new UnsupportedOperationException("Method not decompiled: com.appnext.base.b.j.AnonymousClass1.<clinit>():void"); } } public static Object b(String str, d.a aVar) { try { switch (AnonymousClass1.fF[aVar.ordinal()]) { case 1: return Integer.valueOf(str); case 2: return Double.valueOf(str); case 3: return Long.valueOf(str); case 4: return Boolean.valueOf(str); case 5: return new HashSet(Arrays.asList(str.split(","))); case 6: return new JSONArray(str); case 7: return new JSONObject(str); default: return str; } } catch (Throwable unused) { return null; } } }
41.36385
165
0.524488
cd5e0c362b92630633a93a1fdd85baf8741ede7e
189
package com.sap.olingo.jpa.processor.core.testmodel; import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; @EdmEnumeration() public enum ABCClassifiaction { A, B, C; }
21
70
0.783069
0c9057cd2aa444e281d6ae712fec29e2884300bd
2,095
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; public class DependencyExample { DependencyManager dependencyManager; public DependencyExample() { dependencyManager = new DependencyManager(); } public void executeCommand(String... args) throws Exception { String command = args[0]; ArrayList<String> argsList = new ArrayList<>(Arrays.asList(args).subList(1, args.length)); switch (command) { case "DEPEND": dependencyManager.associateDependency(argsList.get(0), new ArrayList<>(argsList.subList(1, argsList.size()))); break; case "INSTALL": dependencyManager.installDependency(argsList.get(0)); break; case "REMOVE": dependencyManager.removeDependency(argsList.get(0)); break; case "LIST": dependencyManager.listDependencies(); break; case "END": System.exit(0); default: throw new Exception("UNKNOWN COMMAND"); } } public void executeScript(String script) throws Exception { String[] lines = script.split("\n"); for (String line : lines) { System.out.println(line); String[] args = line.trim().split(" "); executeCommand(args); } } public static void main(String args[]) { DependencyExample dependencyExample = new DependencyExample(); String str = ""; try (InputStream inputStream = dependencyExample.getClass().getClassLoader().getResourceAsStream("Progra.dat"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { while ((str = bufferedReader.readLine()) != null) { dependencyExample.executeCommand(str.trim().split(" ")); } } catch (Exception e) { e.printStackTrace(); } } }
34.916667
126
0.591885
6681ea5aedde523e0a4d3f9c080badd79fee93a6
1,717
/* * Copyright 2003 The Apache Software Foundation * * 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.sf.cglib.beans; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; /** * @author Chris Nokleberg <a href="mailto:[email protected]">[email protected]</a> * @version $Id: BeanMapProxy.java,v 1.2 2004/06/24 21:15:17 herbyderby Exp $ */ public class BeanMapProxy implements InvocationHandler { private Map map; public static Object newInstance(Map map, Class[] interfaces) { return Proxy.newProxyInstance(map.getClass().getClassLoader(), interfaces, new BeanMapProxy(map)); } public BeanMapProxy(Map map) { this.map = map; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { String name = m.getName(); if (name.startsWith("get")) { return map.get(name.substring(3)); } else if (name.startsWith("set")) { map.put(name.substring(3), args[0]); return null; } return null; } }
33.019231
87
0.655795
264b9daa4f94f6c52bee13f30cec191a2a42c060
5,330
package com.autuan.common.utils.excel; import org.apache.commons.io.FilenameUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ExcelRead { private static final String XLS = "xls"; private static final String XLSX = "xlsx"; private static final String SEPARATOR = "|"; public ExcelRead() { } public static List<List<Object>> exportListFromExcel(InputStream is, String extensionName, int sheetNum) throws IOException { Workbook workbook = null; System.out.println("extensionName=========={}" + extensionName); if (extensionName.toLowerCase().equals("xls")) { System.out.println("XLS格式"); workbook = new HSSFWorkbook(is); } else if (extensionName.toLowerCase().equals("xlsx")) { System.out.println("XLSX格式"); workbook = new XSSFWorkbook(is); } if (null == workbook) { return null; } return exportListFromExcel((Workbook) workbook, sheetNum); } public static List<List<Object>> exportListFromExcel(File file, int sheetNum) throws IOException { return exportListFromExcel(new FileInputStream(file), FilenameUtils.getExtension(file.getName()), sheetNum); } private static List<List<Object>> exportListFromExcel(Workbook workbook, int sheetNum) { Sheet sheet = workbook.getSheetAt(sheetNum); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); List<List<Object>> list = new ArrayList(); int minRowIx = sheet.getFirstRowNum(); int maxRowIx = sheet.getLastRowNum(); for (int rowIx = minRowIx; rowIx <= maxRowIx; ++rowIx) { List<Object> rowList = new ArrayList<>(); Row row = sheet.getRow(rowIx); StringBuilder sb = new StringBuilder(); short minColIx = row.getFirstCellNum(); short maxColIx = row.getLastCellNum(); for (short colIx = minColIx; colIx <= maxColIx; ++colIx) { Cell cell = row.getCell(new Integer(colIx)); CellValue cellValue = evaluator.evaluate(cell); if (cellValue != null) { switch (cellValue.getCellType()) { case NUMERIC: { if (DateUtil.isCellDateFormatted(cell)) { rowList.add(cell.getLocalDateTimeCellValue()); sb.append("|" + cell.getDateCellValue()); } else { rowList.add(cellValue.getNumberValue()); sb.append("|" + (long) cellValue.getNumberValue()); } break; } case STRING: { rowList.add(cellValue.getStringValue()); sb.append("|" + cellValue.getStringValue()); break; } case BOOLEAN: { rowList.add(cellValue.getBooleanValue()); sb.append("|" + cellValue.getBooleanValue()); break; } default: { break; } } } else { rowList.add(null); sb.append("|"); } } // list.add(sb.toString()); list.add(rowList); } return list; } private static List<Object> objList = null; private static int objListSize = 0; public static void setObjList(List<Object> list) { objList = list; objListSize = list.size(); } public static String getStr(int i) { if (objListSize <= i) { return null; } return String.valueOf(objList.get(i)); } public static String getStrDef(int i, String def) { if (objListSize <= i) { return def; } return String.valueOf(objList.get(i)); } public static BigDecimal getBigDecimalDef(int i, BigDecimal def) { if (objListSize <= i) { return def; } return new BigDecimal(String.valueOf(objList.get(i))); } public static LocalDateTime getLocalDateTime(int i) { if (objListSize <= i) { return null; } Object obj = objList.get(i); if (obj instanceof LocalDateTime) { return (LocalDateTime) obj; } if (obj instanceof String) { String dateStr = (String) obj; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return LocalDateTime.parse(dateStr, formatter); } return null; } }
35.533333
129
0.547092
2bc78b5b7c3f7f354d96dc0220bab1819ca6d8ff
914
package com.open.framework.supports.customform.entity; import lombok.Data; import lombok.experimental.Accessors; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @Author hsj * @Description 自定义表单子表对象 * @Date 2019-03-25 09:23:00 **/ @Data @Accessors(chain = true) @Entity public class CustomFormChild implements Serializable { @Id private String gid; private String code; private String name; /** * 排序字段,直接写结果 code desc,name asc */ private String orderBy; /** * 默认code的下划线,MrlCode-->mrl_code */ private String tableName; /** * 主表gid */ private String customFormGid; @Transient private List<CustomFormDetail> fields; /** * 新增1,修改2,删除3 */ private Integer cudState; /** * 创建时间 */ private Date createTime; /** *修改时间 */ private Date modifyTime; }
17.576923
54
0.654267
0b11e008d24ac9413d044748707be62f2c16b6ef
613
/**Created by wangzhuozhou on 2015/08/01. * Copyright © 2015-2018 Sensors Data Inc. All rights reserved. */ package com.sensorsdata.analytics.android.sdk; public class SensorsDataGPSLocation { /** * 纬度 */ private long latitude; /** * 经度 */ private long longitude; public long getLatitude() { return latitude; } public void setLatitude(long latitude) { this.latitude = latitude; } public long getLongitude() { return longitude; } public void setLongitude(long longitude) { this.longitude = longitude; } }
18.575758
66
0.615008
33cf8d4724c395fd823b436ad13ccb582e1108a9
1,298
package com.beaver.drools.exampl.drools_operations; import com.beaver.drools.example.fact.Person; import com.beaver.drools.util.KieSessionUtil; import org.kie.api.runtime.StatelessKieSession; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * The "collect" keyword is used to find all the elements that match a specific condition <br> * and group them into a collection. <br> * <p> * Created by beaver on 2017/4/10. */ public class CollectFromObjectsExample { public static void main(String[] args) { KieSessionUtil kieSessionUtil = new KieSessionUtil(); kieSessionUtil.addFromClassPath("/rules/drools_operations/CollectFromObjectsExample.drl", StandardCharsets.UTF_8.name()); kieSessionUtil.verifyRules(); StatelessKieSession statelessKieSession = kieSessionUtil.build().newStatelessKieSession(); Person person = new Person(); person.addAddress("山东"); person.addAddress("北京"); person.addAddress("大连"); person.setAge(88); person.setName("doctorwho"); person.putExGirlfriend("1", "李清照"); Person person1 = new Person(); person1.setName("李清照"); statelessKieSession.execute(Arrays.asList(person, person1)); } }
33.282051
129
0.686441
375e2cdbe01429bb355536e8974bfe9c4c78c0e3
1,516
package io.github.a5h73y.carz.other; import io.github.a5h73y.carz.Carz; import java.util.HashMap; import java.util.Map; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; /** * Delay sensitive tasks. */ public enum DelayTasks { INSTANCE; private final Map<String, Long> delays = new HashMap<>(); DelayTasks() { initialiseCleanup(); } public static DelayTasks getInstance() { return INSTANCE; } /** * Delay an event from firing several times. * * @param player target player * @return player able to perform event */ public boolean delayPlayer(Player player, int secondsDelay) { if (!delays.containsKey(player.getName())) { delays.put(player.getName(), System.currentTimeMillis()); return true; } long lastAction = delays.get(player.getName()); int secondsElapsed = (int) ((System.currentTimeMillis() - lastAction) / 1000); if (secondsElapsed >= secondsDelay) { delays.put(player.getName(), System.currentTimeMillis()); return true; } return false; } /** * Clear the cleanup cache every hour. * To keep the size of the map relatively small. */ private void initialiseCleanup() { new BukkitRunnable() { @Override public void run() { delays.clear(); } }.runTaskTimer(Carz.getInstance(), 0, 3600000); } }
24.451613
86
0.601583
520410cfd440fba49e7a9aad1dc390db82cdfc28
278
package Model; public class Zombie { private boolean isAlive = true; /*On instantiation creates a Zombie*/ public Zombie(){ } public boolean isAlive(){ return isAlive; } public void kill(){ isAlive = false; } }
16.352941
42
0.553957
c78b0ed742f38e7c9904d954656655c0dd55d4d1
1,535
package com.w1sh.medusa; import com.w1sh.medusa.core.Instance; import com.w1sh.medusa.services.SlashCommandService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration; import javax.annotation.PreDestroy; @SpringBootApplication(exclude = MongoReactiveRepositoriesAutoConfiguration.class) public class Main implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(Main.class); private final Instance instance; private final SlashCommandService slashCommandService; public Main(Instance instance, SlashCommandService slashCommandService) { this.instance = instance; this.slashCommandService = slashCommandService; } public static void main(String[] args) { Thread.currentThread().setName("medusa-main"); SpringApplication.run(Main.class, args); } @Override public void run(String... args) { instance.initialize(); for (int i = 0; i < args.length; ++i) { log.info("args[{}]: {}", i, args[i]); } } @PreDestroy public void onDestroy() { log.info("Shutting down Medusa - live for {}", Instance.getUptime()); slashCommandService.saveAllCached(); log.info("Shutdown complete"); } }
32.659574
100
0.727036
dfe689bd03f83d2d4937f6b9d059a203322f0232
3,800
package de.schkola.kitchenscanner.task; import de.schkola.kitchenscanner.database.Allergy; import de.schkola.kitchenscanner.database.Customer; import de.schkola.kitchenscanner.database.LunchDatabase; import de.schkola.kitchenscanner.util.StringUtil; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; public class CsvImportTask extends ProgressAsyncTask<InputStream, Void, Boolean> { private final LunchDatabase database; private final boolean allergy; private final Set<String> duplicateXba = Collections.synchronizedSet(new LinkedHashSet<>()); private CsvImportTask.CsvImportListener cil; public CsvImportTask(LunchDatabase db, boolean allergy) { this.database = db; this.allergy = allergy; } public void setCsvImportListener(CsvImportTask.CsvImportListener cil) { this.cil = cil; } @Override protected Boolean doInBackground(InputStream... inputStreams) { try { CSVFormat format = CSVFormat.DEFAULT.withAllowMissingColumnNames(); if (!allergy) { format = format.withDelimiter(';') .withSkipHeaderRecord() .withHeader(); } CSVParser csvParser = CSVParser.parse(inputStreams[0], StandardCharsets.ISO_8859_1, format); if (allergy) { database.allergyDao().deleteAll(); scanAllergy(csvParser, database); } else { scanDay(csvParser, database); } } catch (IOException e) { e.printStackTrace(); } finally { try { inputStreams[0].close(); } catch (IOException ignored) { } } return null; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (cil != null && !duplicateXba.isEmpty()) { cil.onDuplicateXba(duplicateXba); } } private void scanDay(CSVParser csvParser, LunchDatabase database) { try { for (CSVRecord record : csvParser) { Customer customer = new Customer(); customer.grade = record.get("Klasse"); customer.xba = Integer.parseInt(record.get("XBA")); customer.name = record.get("Name"); customer.lunch = StringUtil.getLunch(record.get("Gericht")); Customer checkCustomer = database.customerDao().getCustomer(customer.xba); if (checkCustomer != null) { duplicateXba.add(String.format("[%s]: %s", record.get("XBA"), record.get("Name"))); continue; } database.customerDao().insertCustomer(customer); } } catch (Exception ex) { throw new RuntimeException("Error in reading CSV file: ", ex); } } private void scanAllergy(CSVParser csvParser, LunchDatabase database) { int xba = 0; int allergy = 1; try { for (CSVRecord record : csvParser) { Allergy a = new Allergy(); a.xba = Integer.parseInt(record.get(xba)); a.allergy = record.get(allergy); database.allergyDao().insertAllergy(a); } } catch (Exception ex) { throw new RuntimeException("Error in reading CSV file: " + ex); } } public interface CsvImportListener { void onDuplicateXba(Set<String> duplicateXba); } }
35.185185
104
0.602632
776775ffb53edb4c10c9b5ee94817f90b7262eba
2,123
package com.laninhacompany.ecommerce.models; import java.time.LocalDate; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; @Entity @Table(name = "pedido") public class Pedido { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "total") private Double total; @Column(name = "data", nullable = false) private LocalDate data_pedido = LocalDate.now(); @ManyToOne() @JoinColumn(name = "id_pagamento", referencedColumnName = "id") private Pagamento pagamento; @JsonIgnore @ManyToOne() @JoinColumn(name = "id_cliente", referencedColumnName = "id") private Cliente cliente; @OneToMany(targetEntity = Carrinho.class, mappedBy = "pedido", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set<Carrinho> setCarrinho; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Double getTotal() { return total; } public void setTotal(Double total) { this.total = total; } public LocalDate getData_pedido() { return data_pedido; } public void setData_pedido(LocalDate data_pedido) { this.data_pedido = data_pedido; } public Pagamento getPagamento() { return pagamento; } public void setPagamento(Pagamento pagamento) { this.pagamento = pagamento; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Set<Carrinho> getSetCarrinho() { return setCarrinho; } public void setSetCarrinho(Set<Carrinho> setCarrinho) { this.setCarrinho = setCarrinho; } }
21.444444
114
0.758832
7eb6cde01a494b5fe1cf480db6d4bc2532d3c15a
168
package no.nav.foreldrepenger.mottak.gsak.api; import java.util.List; public interface GsakSakAdapter { void ping(); List<GsakSak> finnSaker(String fnr); }
15.272727
46
0.732143
25b1f813b7f0199685c8b3c9cbdfe2ab31f14f34
276
package com.helospark.tactview.ui.javafx.tabs; public class TabActiveRequest { private String editorId; public TabActiveRequest(String curveEditorId) { this.editorId = curveEditorId; } public String getEditorId() { return editorId; } }
18.4
51
0.688406
704f042b011e778895f6a78a9cb8694da8039ebb
2,861
package orm; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.Query; @Entity @Table(name="REGRESSION_MODEL") public class RegressionModel { @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "regressionModelIdSeq") @SequenceGenerator(name = "regressionModelIdSeq", sequenceName = "regression_model_id_seq", allocationSize = 1) @Id private Integer id; @ManyToOne @JoinColumn(name="SCORING_MODEL_ID") private ScoringModel scoringModel; @ManyToOne @JoinColumn(name="COMPANY_ID") private Company company; @Column(name="DAY_OFFSET") private Integer dayOffset; @Column(name="R_EXPRESSION") private String rExpression; @Enumerated(EnumType.STRING) @Column(name = "MODEL_TYPE") private RegressionModelType modelType; public RegressionModel() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public ScoringModel getScoringModel() { return scoringModel; } public void setScoringModel(ScoringModel scoringModel) { this.scoringModel = scoringModel; } public Integer getDayOffset() { return dayOffset; } public void setDayOffset(Integer dayOffset) { this.dayOffset = dayOffset; } public String getrExpression() { return rExpression; } public void setrExpression(String rExpression) { this.rExpression = rExpression; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public RegressionModelType getModelType() { return modelType; } public void setModelType(RegressionModelType modelType) { this.modelType = modelType; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(id).append(Constants.toStringDelimeter).append(scoringModel.getId()).append(Constants.toStringDelimeter); builder.append(company.getId()).append(Constants.toStringDelimeter).append(dayOffset).append(Constants.toStringDelimeter); builder.append(rExpression.substring(0,10)).append(Constants.toStringDelimeter); builder.append(modelType);; return builder.toString(); } public static RegressionModel findById(int regressionModelId) { Query query = SessionManager.createQuery("from RegressionModel where id = :id"); query.setInteger("id", regressionModelId); @SuppressWarnings("rawtypes") List list = query.list(); if (list.size() > 0) { return (RegressionModel)list.get(0); } else { return null; } } }
23.644628
124
0.76267
d2030ba58824cce6e1cf19f2f21eb249f75ebf5e
3,829
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.kafka; import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants; import org.apache.hadoop.hive.ql.plan.TableDesc; import org.apache.log4j.Logger; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; public class KafkaBackedTableProperties { private static final Logger LOG = Logger.getLogger(KafkaBackedTableProperties.class); public static final String KAFKA_URI = "kafka.service.uri"; public static final String KAFKA_URL = "kafka.service.url"; public static final String KAFKA_PORT = "kafka.service.port"; public static final String KAFKA_WHITELIST_TOPICS = "kafka.whitelist.topics"; public static final String KAFKA_AVRO_SCHEMA_FILE = "kafka.avro.schema.file"; public static final String COLUMN_NAMES = "columns"; public static final String COLUMN_TYPES = "columns.types"; public static final String COLUMN_COMMENTS = "columns.comments"; /* * This method initializes properties of the external table and populates * the jobProperties map with them so that they can be used throughout the job. */ public void initialize(Properties tableProperties, Map<String,String> jobProperties, TableDesc tableDesc) { // Set kafka.whitelist.topics in the jobProperty String kafkaWhitelistTopics = tableProperties.getProperty(KAFKA_WHITELIST_TOPICS); LOG.debug("Kafka whitelist topics : " + kafkaWhitelistTopics); jobProperties.put(KAFKA_WHITELIST_TOPICS, kafkaWhitelistTopics); // Set kafka.avro.schema.file in the jobProperty String kafkaAvroSchemaFile = tableProperties.getProperty(KAFKA_AVRO_SCHEMA_FILE, null); if (kafkaAvroSchemaFile != null) { LOG.debug("Kafka avro schema file : " + kafkaAvroSchemaFile); jobProperties.put(KAFKA_AVRO_SCHEMA_FILE, kafkaAvroSchemaFile); } // Set kafka.url and kafka.port in the jobProperty String kafkaUri = tableProperties.getProperty(KAFKA_URI); LOG.debug("Kafka URI : " + kafkaUri); jobProperties.put(KAFKA_URI, kafkaUri); final String[] uriSplits = kafkaUri.split(":"); String kafkaUrl = uriSplits[0]; String kafkaPort = uriSplits[1]; LOG.debug("Kafka URL : " + kafkaUrl); jobProperties.put(KAFKA_URL, kafkaUrl); LOG.debug("Kafka PORT : " + kafkaPort); jobProperties.put(KAFKA_PORT, kafkaPort); // Set column names in the jobProperty String columnNames = tableProperties.getProperty(COLUMN_NAMES); LOG.debug("Column Names : " + columnNames); jobProperties.put(COLUMN_NAMES, columnNames); // Set column types in the jobProperty String columnTypes = tableProperties.getProperty(COLUMN_TYPES); LOG.debug("Column Types : " + columnTypes); jobProperties.put(COLUMN_TYPES, columnTypes); // Set column types in the jobProperty String columnComments = tableProperties.getProperty(COLUMN_COMMENTS); LOG.debug("Column Comments : " + columnComments); jobProperties.put(COLUMN_COMMENTS, columnComments); } }
43.511364
91
0.749021
24c0f4aff577332cdcf90a856917661ac4e12f9c
10,710
/** * Copyright 2019 ForgeRock AS. * * 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 com.forgerock.consumer.data.right.model.v1_1_1; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Objects; /** * BankingAccount */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-03-05T15:13:51.111520Z[Europe/London]") public class BankingAccount { @JsonProperty("accountId") private String accountId = null; @JsonProperty("creationDate") private String creationDate = null; @JsonProperty("displayName") private String displayName = null; @JsonProperty("nickname") private String nickname = null; /** * Open or closed status for the account. If not present then OPEN is assumed */ public enum OpenStatusEnum { OPEN("OPEN"), CLOSED("CLOSED"); private String value; OpenStatusEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static OpenStatusEnum fromValue(String text) { for (OpenStatusEnum b : OpenStatusEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("openStatus") private OpenStatusEnum openStatus = OpenStatusEnum.OPEN; @JsonProperty("isOwned") private Boolean isOwned = true; @JsonProperty("maskedNumber") private String maskedNumber = null; @JsonProperty("productCategory") private BankingProductCategory productCategory = null; @JsonProperty("productName") private String productName = null; public BankingAccount accountId(String accountId) { this.accountId = accountId; return this; } /** * A unique ID of the account adhering to the standards for ID permanence * @return accountId **/ @ApiModelProperty(required = true, value = "A unique ID of the account adhering to the standards for ID permanence") @NotNull public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public BankingAccount creationDate(String creationDate) { this.creationDate = creationDate; return this; } /** * Date that the account was created (if known) * @return creationDate **/ @ApiModelProperty(value = "Date that the account was created (if known)") public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public BankingAccount displayName(String displayName) { this.displayName = displayName; return this; } /** * The display name of the account as defined by the bank. This should not incorporate account numbers or PANs. If it does the values should be masked according to the rules of the MaskedAccountString common type. * @return displayName **/ @ApiModelProperty(required = true, value = "The display name of the account as defined by the bank. This should not incorporate account numbers or PANs. If it does the values should be masked according to the rules of the MaskedAccountString common type.") @NotNull public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public BankingAccount nickname(String nickname) { this.nickname = nickname; return this; } /** * A customer supplied nick name for the account * @return nickname **/ @ApiModelProperty(value = "A customer supplied nick name for the account") public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public BankingAccount openStatus(OpenStatusEnum openStatus) { this.openStatus = openStatus; return this; } /** * Open or closed status for the account. If not present then OPEN is assumed * @return openStatus **/ @ApiModelProperty(value = "Open or closed status for the account. If not present then OPEN is assumed") public OpenStatusEnum getOpenStatus() { return openStatus; } public void setOpenStatus(OpenStatusEnum openStatus) { this.openStatus = openStatus; } public BankingAccount isOwned(Boolean isOwned) { this.isOwned = isOwned; return this; } /** * Flag indicating that the customer associated with the authorisation is an owner of the account. Does not indicate sole ownership, however. If not present then 'true' is assumed * @return isOwned **/ @ApiModelProperty(value = "Flag indicating that the customer associated with the authorisation is an owner of the account. Does not indicate sole ownership, however. If not present then 'true' is assumed") public Boolean isIsOwned() { return isOwned; } public void setIsOwned(Boolean isOwned) { this.isOwned = isOwned; } public BankingAccount maskedNumber(String maskedNumber) { this.maskedNumber = maskedNumber; return this; } /** * A masked version of the account. Whether BSB/Account Number, Credit Card PAN or another number * @return maskedNumber **/ @ApiModelProperty(required = true, value = "A masked version of the account. Whether BSB/Account Number, Credit Card PAN or another number") @NotNull public String getMaskedNumber() { return maskedNumber; } public void setMaskedNumber(String maskedNumber) { this.maskedNumber = maskedNumber; } public BankingAccount productCategory(BankingProductCategory productCategory) { this.productCategory = productCategory; return this; } /** * Get productCategory * @return productCategory **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public BankingProductCategory getProductCategory() { return productCategory; } public void setProductCategory(BankingProductCategory productCategory) { this.productCategory = productCategory; } public BankingAccount productName(String productName) { this.productName = productName; return this; } /** * The unique identifier of the account as defined by the data holder (akin to model number for the account) * @return productName **/ @ApiModelProperty(required = true, value = "The unique identifier of the account as defined by the data holder (akin to model number for the account)") @NotNull public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BankingAccount bankingAccount = (BankingAccount) o; return Objects.equals(this.accountId, bankingAccount.accountId) && Objects.equals(this.creationDate, bankingAccount.creationDate) && Objects.equals(this.displayName, bankingAccount.displayName) && Objects.equals(this.nickname, bankingAccount.nickname) && Objects.equals(this.openStatus, bankingAccount.openStatus) && Objects.equals(this.isOwned, bankingAccount.isOwned) && Objects.equals(this.maskedNumber, bankingAccount.maskedNumber) && Objects.equals(this.productCategory, bankingAccount.productCategory) && Objects.equals(this.productName, bankingAccount.productName); } @Override public int hashCode() { return Objects.hash(accountId, creationDate, displayName, nickname, openStatus, isOwned, maskedNumber, productCategory, productName); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BankingAccount {\n"); sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n"); sb.append(" creationDate: ").append(toIndentedString(creationDate)).append("\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" nickname: ").append(toIndentedString(nickname)).append("\n"); sb.append(" openStatus: ").append(toIndentedString(openStatus)).append("\n"); sb.append(" isOwned: ").append(toIndentedString(isOwned)).append("\n"); sb.append(" maskedNumber: ").append(toIndentedString(maskedNumber)).append("\n"); sb.append(" productCategory: ").append(toIndentedString(productCategory)).append("\n"); sb.append(" productName: ").append(toIndentedString(productName)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
32.553191
260
0.664052
7f8149e4852a050d39b708c45b4c9981a32e2905
763
package io.connectedhealth_idaas.eventbuilder.dataobjects.financial.hipaa; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; public class M13 { private String M13_01_StandardCarrierAlphaCode; private String M13_02_LocationIdentifier; private String M13_03_AmendmentTypeCode; private String M13_04_BillofLadingWaybillNumber; private String M13_05_Quantity; private String M13_06_AmendmentCode; private String M13_07_ActionCode; private String M13_08_BillofLadingWaybillNumber; private String M13_09_StandardCarrierAlphaCode; private String M13_10_StandardCarrierAlphaCode; private String M13_11_IdentificationCodeQualifier; private String M13_12_IdentificationCode; public String toString() { return ReflectionToStringBuilder.toString(this);} }
38.15
76
0.885976
26ecc4a6c9e7bcdc6973ad52e0e56bcc27d3c402
1,180
package frostillicus.controller; import javax.faces.context.FacesContext; import javax.faces.event.PhaseEvent; import com.ibm.xsp.extlib.util.ExtLibUtil; import lotus.domino.*; public class BasicXPageController implements XPageController { private static final long serialVersionUID = 1L; public BasicXPageController() { } public void beforePageLoad() throws Exception { } public void afterPageLoad() throws Exception { } public void beforeRenderResponse(PhaseEvent event) throws Exception { } public void afterRenderResponse(PhaseEvent event) throws Exception { } public void afterRestoreView(PhaseEvent event) throws Exception { } protected static Object resolveVariable(String varName) { return ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), varName); } public boolean isEditable() { return false; } public String getServerAbbreviatedName() throws NotesException { Session session = ExtLibUtil.getCurrentSession(); String server = session.getServerName(); Name name = session.createName(server); String abbreviatedName = name.getAbbreviated(); name.recycle(); return abbreviatedName; } }
31.052632
81
0.765254
0d7a7cabc85e6dee3231bad30673dee1f45e0276
7,597
/******************************************************************************* * Copyright 2012 Geoscience Australia * * 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 au.gov.ga.worldwind.viewer.panels.geonames; import gov.nasa.worldwind.geom.Angle; import gov.nasa.worldwind.geom.LatLon; import java.awt.Color; import java.awt.Font; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import au.gov.ga.worldwind.common.util.ColorFont; /** * Helper class for searching the GeoNames.org database. * * @author Michael de Hoog ([email protected]) */ public class GeoNamesSearch { private final static String GEONAMES_SEARCH = "http://ws.geonames.org/search"; private final static String GEONAMES_USERNAME = "gam3dv"; private final static Map<String, ColorFont> colorFonts = new HashMap<String, ColorFont>(); private final static ColorFont defaultColorFont = new ColorFont(Font.decode("Arial-PLAIN-10"), Color.white, Color.black); static { colorFonts.put("A", new ColorFont(Font.decode("Arial-BOLD-11"), Color.lightGray, Color.black)); colorFonts.put("H", new ColorFont(Font.decode("Arial-PLAIN-10"), Color.cyan, Color.black)); colorFonts.put("L", new ColorFont(Font.decode("Arial-PLAIN-10"), Color.green, Color.black)); colorFonts.put("P", new ColorFont(Font.decode("Arial-BOLD-11"), Color.yellow, Color.black)); colorFonts.put("R", new ColorFont(Font.decode("Arial-PLAIN-10"), Color.red, Color.black)); colorFonts.put("S", new ColorFont(Font.decode("Arial-PLAIN-10"), Color.pink, Color.black)); colorFonts.put("T", new ColorFont(Font.decode("Arial-PLAIN-10"), Color.orange, Color.black)); colorFonts.put("U", new ColorFont(Font.decode("Arial-PLAIN-10"), Color.blue, Color.black)); colorFonts.put("V", new ColorFont(Font.decode("Arial-PLAIN-10"), new Color(0, 128, 0), Color.black)); } /** * Enum of different search types supported by geonames.org. */ public static enum SearchType { FUZZY("q"), PLACE("name"), EXACT("name_equals"); public final String queryParameter; SearchType(String queryParameter) { this.queryParameter = queryParameter; } } /** * Container class to store results from a geonames.org search. */ public static class Results { public final String error; public final List<GeoName> places; public Results(List<GeoName> places) { this.places = places; this.error = null; } public Results(String error) { this.error = error; this.places = null; } } /** * Search geonames.org for the given text, and parse and return the results. * * @param text * Text to search for * @param type * Type of search to perform * @return Search results. */ public static Results search(String text, SearchType type) { try { text = URLEncoder.encode(text, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return new Results(e.getMessage()); } URL url = null; try { url = new URL(GEONAMES_SEARCH + "?username=" + GEONAMES_USERNAME + "&style=long&" + type.queryParameter + "=" + text); } catch (MalformedURLException e) { e.printStackTrace(); return new Results(e.getMessage()); } try { InputStream is = url.openStream(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(is); return parse(document); } catch (Exception e) { e.printStackTrace(); return new Results(e.getMessage()); } } private static Results parse(Document document) { NodeList resultsCount = document.getElementsByTagName("totalResultsCount"); if (resultsCount.getLength() <= 0) { try { NodeList statusList = document.getElementsByTagName("status"); Node status = statusList.item(0); Node message = status.getAttributes().getNamedItem("message"); String error = message.getTextContent(); return new Results(error); } catch (Exception e) { return new Results("Unknown error occurred"); } } List<GeoName> places = new ArrayList<GeoName>(); NodeList nodes = document.getElementsByTagName("geoname"); if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NodeList children = node.getChildNodes(); String name = null; String fcl = null; String fcode = null; String fclName = null; String fcodeName = null; Integer geonameId = null; Double lat = null; Double lon = null; String country = null; for (int j = 0; j < children.getLength(); j++) { try { Node child = children.item(j); if (child.getNodeName().equals("name")) { name = child.getTextContent(); } else if (child.getNodeName().equals("countryName")) { country = child.getTextContent(); } else if (child.getNodeName().equals("fcl")) { fcl = child.getTextContent(); } else if (child.getNodeName().equals("fcode")) { fcode = child.getTextContent(); } else if (child.getNodeName().equals("fclName")) { fclName = child.getTextContent(); } else if (child.getNodeName().equals("fcodeName")) { fcodeName = child.getTextContent(); } else if (child.getNodeName().equals("lat")) { lat = Double.valueOf(child.getTextContent()); } else if (child.getNodeName().equals("lng")) { lon = Double.valueOf(child.getTextContent()); } else if (child.getNodeName().equals("geonameId")) { geonameId = Integer.valueOf(child.getTextContent()); } } catch (Exception e) { } } if (lat != null && lon != null && name != null && name.length() > 0) { LatLon latlon = new LatLon(Angle.fromDegreesLatitude(lat), Angle.fromDegreesLongitude(lon)); ColorFont colorFont = colorFonts.get(fcl); if (colorFont == null) { colorFont = defaultColorFont; } GeoName place = new GeoName(name, country, geonameId, latlon, fcl, fclName, fcode, fcodeName, colorFont); places.add(place); } } } return new Results(places); } }
29.445736
109
0.634593
7ca8157b3af5b37efcd5cfdc6f88b71a68e8d265
382
package shapesMitApfel; /** * Beschreiben Sie hier die Klasse Picture. * * @author Denise Schmitz * @since 31.01.2021 */ public class Picture { Circle sonne, mond; public Picture() { sonne = new Circle(); sonne.moveUp(); mond = new Circle(); } public void makeVisible() { sonne.makeVisible(); mond.makeVisible(); } }
14.692308
43
0.58377
47c558035bf200f39c054208174af6c188881f63
6,676
package com.zyl.melife.camera.model; import android.content.Context; import com.zyl.melife.ICameraData; /** * Created by yuyidong on 15/7/17. */ public class AbsCameraModel implements ICameraModel { private boolean mIsBind = false; private ICameraData mCameraService; // private LocationClient mLocationClient; private double mLatitude; private double mLontitude; @Override public ICameraSetting getSettingModel() { return null; } @Override public ICameraFocus getFocusModel() { return null; } @Override public void setTouchArea(int width, int height) { } @Override public void openCamera(String id, int orientation) { } @Override public void reopenCamera(String id, int orientation) { } @Override public void startPreview() { } @Override public void reStartPreview() { } @Override public void stopPreview() { } @Override public void closeCamera() { } @Override public long capture(boolean sound, int ratio, boolean isMirror) { return 0l; } @Override public void onCreate(Context context) { // mLocationClient = new LocationClient(context); // mLocationClient.registerLocationListener(new BDLocationListener() { // @Override // public void onReceiveLocation(BDLocation bdLocation) { // mLatitude = bdLocation.getLatitude(); // mLontitude = bdLocation.getLongitude(); // } // }); // LocationClientOption option = new LocationClientOption(); // option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 // option.setCoorType("gcj02");//可选,默认gcj02,设置返回的定位结果坐标系, // int span = 2000; // option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 //// option.setIsNeedAddress(checkGeoLocation.isChecked());//可选,设置是否需要地址信息,默认不需要 // option.setOpenGps(true);//可选,默认false,设置是否使用gps // option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 // option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 // option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要 // mLocationClient.setLocOption(option); // mLocationClient.start(); // bindService(context); } @Override public void onDestroy(Context context) { // mLocationClient.stop(); // unBindService(context); } // private void bindService(Context context) { // Intent intent = new Intent(context, CameraService.class); // context.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); // } // private ServiceConnection mServiceConnection = new ServiceConnection() { // // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // mCameraService = ICameraData.Stub.asInterface(service); // mIsBind = true; // } // // @Override // public void onServiceDisconnected(ComponentName name) { // mCameraService = null; // mIsBind = false; // } // }; // private void unBindService(Context context) { // if (mIsBind) { // context.unbindService(mServiceConnection); // mIsBind = false; // } // } public boolean addData2Service(byte[] data, String cameraId, long time, int categoryId, boolean isMirror, int ratio) { boolean bool = true; // int size = data.length; // String fileName = time + ".data"; // File file = new File(FilePathUtils.getSandBoxDir() + fileName); // OutputStream outputStream = null; // try { // if (!file.exists()) { // file.createNewFile(); // } // outputStream = new FileOutputStream(file); // outputStream.write(data); // outputStream.flush(); // } catch (IOException e) { // bool = false; // e.printStackTrace(); // } finally { // if (outputStream != null) { // try { // outputStream.close(); // } catch (IOException e) { // bool = false; // e.printStackTrace(); // } // } // } // // int orientation = 0;//todo 这个还没做,下个版本做 // // String latitude0 = String.valueOf((int) mLatitude) + "/1,"; // String latitude1 = String.valueOf((int) ((mLatitude - (int) mLatitude) * 60) + "/1,"); // String latitude2 = String.valueOf((int) ((((mLatitude - (int) mLatitude) * 60) - ((int) ((mLatitude - (int) mLatitude) * 60))) * 60 * 10000)) + "/10000"; // String latitude = new StringBuilder(latitude0).append(latitude1).append(latitude2).toString(); // String lontitude0 = String.valueOf((int) mLontitude) + "/1,"; // String lontitude1 = String.valueOf((int) ((mLontitude - (int) mLontitude) * 60) + "/1,"); // String lontitude2 = String.valueOf((int) ((((mLontitude - (int) mLontitude) * 60) - ((int) ((mLontitude - (int) mLontitude) * 60))) * 60 * 10000)) + "/10000"; // String lontitude = new StringBuilder(lontitude0).append(lontitude1).append(lontitude2).toString(); // int whiteBalance = 0; // if (getSettingModel().getSupportedWhiteBalance().size() > 0) { // if (getSettingModel().getWhiteBalance() != ICameraParams.WHITE_BALANCE_AUTO) { // whiteBalance = 1; // } // } // //todo 这里的flash是指拍照的那个时候闪光灯是否打开了,所以啊。。。这个。。。。 // int flash = 0; // if (getSettingModel().getSupportedFlash().size() > 0) { // if (getSettingModel().getFlash() != ICameraParams.FLASH_OFF) { // flash = 1; // } // } // Size size1 = getSettingModel().getPictureSize(); // int imageLength = size1.getHeight(); // int imageWidth = size1.getWidth(); // if (ratio == Const.CAMERA_SANDBOX_PHOTO_RATIO_1_1) { // imageLength = imageWidth; // } // String make = Build.BRAND; // String model = Build.MODEL; // try { // mCameraService.add(fileName, size, cameraId, time, categoryId, isMirror, ratio, // orientation, latitude, lontitude, whiteBalance, flash, imageLength, imageWidth, make, model); // } catch (RemoteException e) { // e.printStackTrace(); // bool = false; // } return bool; } }
33.717172
168
0.587178