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
|
---|---|---|---|---|---|
f81bc3422df19dc62513155c5fe914a799ade994 | 31,433 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.accessibility.compositor;
import android.annotation.TargetApi;
import android.content.Context;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.RangeInfoCompat;
import androidx.core.view.accessibility.AccessibilityWindowInfoCompat;
import android.text.Spannable;
import android.text.style.LocaleSpan;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.InputMethodSubtype;
import com.google.android.accessibility.utils.AccessibilityNodeInfoUtils;
import com.google.android.accessibility.utils.BuildVersionUtils;
import com.google.android.accessibility.utils.ImageContents;
import com.google.android.accessibility.utils.LocaleUtils;
import com.google.android.accessibility.utils.PackageManagerUtils;
import com.google.android.accessibility.utils.Role;
import com.google.android.accessibility.utils.SpeechCleanupUtils;
import com.google.android.accessibility.utils.WebInterfaceUtils;
import com.google.android.accessibility.utils.parsetree.ParseTree;
import com.google.android.accessibility.utils.parsetree.ParseTree.VariableDelegate;
import com.google.android.accessibility.utils.traversal.ReorderedChildrenIterator;
import com.google.android.libraries.accessibility.utils.log.LogUtils;
import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A VariableDelegate that maps data from AccessibilityEvent and AccessibilityNodeInfoCompat */
class NodeVariables implements ParseTree.VariableDelegate {
private static final String TAG = "NodeVariables";
// IDs of variables.
private static final int NODE_ROLE = 7000;
private static final int NODE_TEXT = 7001;
private static final int NODE_CONTENT_DESCRIPTION = 7002;
private static final int NODE_CHILDREN = 7003;
private static final int NODE_CHILDREN_ASCENDING = 7004;
private static final int NODE_ROLE_DESCRIPTION = 7005;
private static final int NODE_CHECKABLE = 7006;
private static final int NODE_CHECKED = 7007;
private static final int NODE_IS_VISIBLE = 7008;
private static final int NODE_IS_ACCESSIBILITY_FOCUSABLE = 7009;
private static final int NODE_IS_FOCUSED = 7010;
private static final int NODE_IS_ACCESSIBILITY_FOCUSED = 7011;
private static final int NODE_LIVE_REGION = 7012;
private static final int NODE_IS_PASSWORD = 7013;
private static final int NODE_WINDOW_ID = 7014;
private static final int NODE_WINDOW_TYPE = 7015;
private static final int NODE_SUPPORTS_ACTION_SET_SELECTION = 7016;
private static final int NODE_SUPPORTS_ACTION_SELECT = 7017;
private static final int NODE_LABEL_TEXT = 7018;
private static final int NODE_LABELED_BY = 7019;
private static final int NODE_IS_ACTIONABLE = 7020;
private static final int NODE_IS_ENABLED = 7021;
private static final int NODE_IS_SELECTED = 7022;
private static final int NODE_IS_EXPANDABLE = 7023;
private static final int NODE_IS_COLLAPSIBLE = 7024;
private static final int NODE_PARENT = 7025;
private static final int NODE_VISIBLE_CHILD_COUNT = 7026;
private static final int NODE_SUPPORTS_ACTION_SCROLL_FORWARD = 7027;
private static final int NODE_SUPPORTS_ACTION_SCROLL_BACKWARD = 7028;
private static final int NODE_ACTIONS = 7029;
private static final int NODE_IS_CLICKABLE = 7030;
private static final int NODE_IS_LONG_CLICKABLE = 7031;
private static final int NODE_ACTION_CLICK = 7032;
private static final int NODE_ACTION_LONG_CLICK = 7033;
private static final int NODE_IS_PIN_KEY = 7034;
// Used to show accessibility hints for web and edit texts
private static final int NODE_HINT = 7035;
private static final int NODE_IS_SHOWING_HINT = 7036;
// Variables used for Switch Access
private static final int NODE_IS_SCROLLABLE = 7037;
private static final int NODE_VIEW_ID_TEXT = 7038;
private static final int NODE_SELECTED_PAGE_TITLE = 7039;
private static final int NODE_IS_HEADING = 7040;
// TODO: May need an array variable for visible children.
private static final int NODE_RANGE_INFO_TYPE = 7041;
private static final int NODE_RANGE_CURRENT_VALUE = 7042;
private static final int NODE_TOOLTIP_TEXT = 7043;
private static final int NODE_IS_COLLECTION_ITEM = 7044;
private static final int NODE_IS_CONTENT_INVALID = 7045;
private static final int NODE_ERROR = 7046;
private static final int NODE_PROGRESS_PERCENT = 7047;
private static final int NODE_SELF_MENU_ACTION_IS_AVAILABLE = 7049;
private static final int NODE_SELF_MENU_ACTION_TYPE = 7050;
private static final int NODE_IS_WEB_CONTAINER = 7051;
private static final int NODE_NEEDS_LABEL = 7052;
private static final int NODE_STATE_DESCRIPTION = 7053;
private static final int NODE_IS_WITHIN_ACCESSIBILITY_FOCUS = 7054;
private static final int NODE_IS_KEYBOARD_WINDOW = 7055;
private static final int NODE_CAPTION_TEXT = 7056;
private static final int NODE_ANNOUNCE_DISABLED = 7057;
private final Context mContext;
private final @Nullable ImageContents imageContents;
private final ParseTree.VariableDelegate mParentVariables;
private boolean mOwnsParentVariables; // Should this object cleanup mParentVariables.
private final AccessibilityNodeInfoCompat mNode; // Recycled by this.cleanup().
private final @Role.RoleName int mRole; // Role of mNode.
private boolean mIsRoot; // Is mNode the root/source node for node tree recursion.
private Set<AccessibilityNodeInfoCompat> mVisitedNodes; // Recycled by this.cleanup()
private ArrayList<AccessibilityNodeInfoCompat> mChildNodes; // Recycled by this.cleanup()
private ArrayList<AccessibilityNodeInfoCompat> mChildNodesAscending; // Recycled by this.cleanup()
private AccessibilityNodeInfoCompat mLabelNode; // Recycled by this.cleanup()
private AccessibilityNodeInfoCompat mParentNode; // Recycled by this.cleanup()
// Used to store keyboard Locale.
private final @Nullable Locale mLocale;
// Stores the user preferred locale changed using language switcher.
private @Nullable final Locale mUserPreferredLocale;
@Nullable private final NodeMenuProvider nodeMenuProvider;
/**
* Constructs a NodeVariables, which contains context variables to help generate feedback for an
* accessibility event. Caller must call {@code cleanup()} when done with this object.
*
* @param node The view node for which we are generating feedback. The NodeVariables will recycle
* this node.
*/
public NodeVariables(
Context context,
@Nullable ImageContents imageContents,
@Nullable NodeMenuProvider nodeMenuProvider,
ParseTree.VariableDelegate parent,
AccessibilityNodeInfoCompat node,
@Nullable Locale userPreferredLocale) {
mContext = context;
this.imageContents = imageContents;
mParentVariables = parent;
mNode = node;
mRole = Role.getRole(node);
mIsRoot = true;
mOwnsParentVariables = true;
// Locale captured to wrap ttsOutput for IME input. Needed only for the old versions of Gboard.
// New version wraps the content description and text in the locale of the IME and mLocale will
// be null for it.
mLocale = getLocaleForIME(node, context);
mUserPreferredLocale = userPreferredLocale;
this.nodeMenuProvider = nodeMenuProvider;
}
private static NodeVariables constructForReferredNode(
Context context,
@Nullable ImageContents imageContents,
@Nullable NodeMenuProvider nodeMenuProvider,
ParseTree.VariableDelegate parent,
AccessibilityNodeInfoCompat node,
@Nullable Locale userPreferredLocale) {
NodeVariables instance =
new NodeVariables(
context, imageContents, nodeMenuProvider, parent, node, userPreferredLocale);
instance.mIsRoot = true; // This is a new root for node tree recursion.
instance.mOwnsParentVariables = false; // Not responsible to recycle mParentVariables.
return instance;
}
private static NodeVariables constructForChildNode(
Context context,
@Nullable ImageContents imageContents,
@Nullable NodeMenuProvider nodeMenuProvider,
ParseTree.VariableDelegate parent,
AccessibilityNodeInfoCompat node,
Set<AccessibilityNodeInfoCompat> visitedNodes,
@Nullable Locale userPreferredLocale) {
NodeVariables instance =
new NodeVariables(
context, imageContents, nodeMenuProvider, parent, node, userPreferredLocale);
instance.mIsRoot = false; // Not responsible to recycle mVisitedNodes.
instance.mOwnsParentVariables = false; // Not responsible to recycle mParentVariables.
instance.setVisitedNodes(visitedNodes);
return instance;
}
/**
* Checks if the window type is TYPE_INPUT_METHOD and returns the locale. This only works for the
* old versions of Gboard. The new version wraps the content description and text in the locale of
* the IME and returns null here.
*/
private static @Nullable Locale getLocaleForIME(
AccessibilityNodeInfoCompat node, Context context) {
Locale locale = null;
if (isKeyboardEvent(node)) {
return getKeyboardLocale(context);
}
return locale;
}
private static boolean isKeyboardEvent(AccessibilityNodeInfoCompat node) {
if (node != null) {
AccessibilityWindowInfoCompat window = AccessibilityNodeInfoUtils.getWindow(node);
if (window != null && window.getType() == AccessibilityWindowInfoCompat.TYPE_INPUT_METHOD) {
return true;
}
}
return false;
}
/**
* Returns the locale of the IME. This only works for the old versions of Gboard. The new version
* wraps the content description and text in the locale of the IME and returns an empty string
* when InputMethodSubtype is queried for the locale.
*/
private static @Nullable Locale getKeyboardLocale(Context context) {
Locale locale = null;
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
// dereference of possibly-null reference imm
@SuppressWarnings("nullness:dereference.of.nullable")
InputMethodSubtype ims = imm.getCurrentInputMethodSubtype();
if (ims == null) {
return locale;
}
String localeString = ims.getLocale();
locale = LocaleUtils.parseLocaleString(localeString);
return locale;
}
private void setVisitedNodes(Set<AccessibilityNodeInfoCompat> visitedNodes) {
mVisitedNodes = visitedNodes;
if (mVisitedNodes != null && !mVisitedNodes.contains(mNode)) {
mVisitedNodes.add(AccessibilityNodeInfoUtils.obtain(mNode));
}
}
@Override
public void cleanup() {
AccessibilityNodeInfoUtils.recycleNodes(mNode);
AccessibilityNodeInfoUtils.recycleNodes(mChildNodes);
AccessibilityNodeInfoUtils.recycleNodes(mChildNodesAscending);
AccessibilityNodeInfoUtils.recycleNodes(mLabelNode);
AccessibilityNodeInfoUtils.recycleNodes(mParentNode);
if (mIsRoot) {
AccessibilityNodeInfoUtils.recycleNodes(mVisitedNodes);
}
// Many NodeVariables are spawned from another NodeVariables, and share parent variables.
if (mOwnsParentVariables && mParentVariables != null) {
mParentVariables.cleanup();
}
}
@Override
public boolean getBoolean(int variableId) {
switch (variableId) {
case NODE_CHECKABLE:
return mNode.isCheckable();
case NODE_CHECKED:
return mNode.isChecked();
case NODE_IS_VISIBLE:
return AccessibilityNodeInfoUtils.isVisible(mNode);
case NODE_IS_ACCESSIBILITY_FOCUSABLE:
return AccessibilityNodeInfoUtils.isAccessibilityFocusable(mNode);
case NODE_IS_FOCUSED:
return mNode.isFocused();
case NODE_IS_SHOWING_HINT:
return mNode.isShowingHintText();
case NODE_IS_ACCESSIBILITY_FOCUSED:
return mNode.isAccessibilityFocused();
case NODE_SUPPORTS_ACTION_SET_SELECTION:
return AccessibilityNodeInfoUtils.supportsAction(
mNode, AccessibilityNodeInfoCompat.ACTION_SET_SELECTION);
case NODE_IS_PASSWORD:
return mNode.isPassword();
case NODE_SUPPORTS_ACTION_SELECT:
return AccessibilityNodeInfoUtils.supportsAction(
mNode, AccessibilityNodeInfoCompat.ACTION_SELECT);
case NODE_IS_ACTIONABLE:
return AccessibilityNodeInfoUtils.isActionableForAccessibility(mNode);
case NODE_IS_ENABLED:
return mNode.isEnabled();
case NODE_IS_SELECTED:
return mNode.isSelected();
case NODE_IS_EXPANDABLE:
return AccessibilityNodeInfoUtils.isExpandable(mNode);
case NODE_IS_COLLAPSIBLE:
return AccessibilityNodeInfoUtils.isCollapsible(mNode);
case NODE_SUPPORTS_ACTION_SCROLL_BACKWARD:
return AccessibilityNodeInfoUtils.supportsAction(
mNode, AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
case NODE_SUPPORTS_ACTION_SCROLL_FORWARD:
return AccessibilityNodeInfoUtils.supportsAction(
mNode, AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
case NODE_IS_CLICKABLE:
return AccessibilityNodeInfoUtils.isClickable(mNode);
case NODE_IS_LONG_CLICKABLE:
return AccessibilityNodeInfoUtils.isLongClickable(mNode);
case NODE_IS_SCROLLABLE:
return AccessibilityNodeInfoUtils.isScrollable(mNode);
case NODE_IS_PIN_KEY:
return AccessibilityNodeInfoUtils.isPinKey(mNode);
case NODE_IS_HEADING:
return AccessibilityNodeInfoUtils.isHeading(mNode);
case NODE_IS_COLLECTION_ITEM:
return mNode.getCollectionItemInfo() != null;
case NODE_IS_CONTENT_INVALID:
return mNode.isContentInvalid();
case NODE_IS_WEB_CONTAINER:
return WebInterfaceUtils.isWebContainer(mNode);
case NODE_SELF_MENU_ACTION_IS_AVAILABLE:
{
return nodeMenuProvider != null
&& !nodeMenuProvider.getSelfNodeMenuActionTypes(mNode).isEmpty();
}
case NODE_NEEDS_LABEL:
return imageContents != null && imageContents.needsLabel(mNode);
case NODE_IS_WITHIN_ACCESSIBILITY_FOCUS:
{
return AccessibilityNodeInfoUtils.isSelfOrAncestorFocused(mNode);
}
case NODE_IS_KEYBOARD_WINDOW:
return isKeyboardEvent(mNode);
case NODE_ANNOUNCE_DISABLED:
{
if (BuildVersionUtils.isAtLeastS()) {
return !mNode.isEnabled();
}
return !mNode.isEnabled()
&& (WebInterfaceUtils.hasNativeWebContent(mNode)
|| AccessibilityNodeInfoUtils.isActionableForAccessibility(mNode));
}
default:
return mParentVariables.getBoolean(variableId);
}
}
@Override
public int getInteger(int variableId) {
switch (variableId) {
case NODE_WINDOW_ID:
return mNode.getWindowId();
case NODE_VISIBLE_CHILD_COUNT:
return AccessibilityNodeInfoUtils.countVisibleChildren(mNode);
default:
return mParentVariables.getInteger(variableId);
}
}
@Override
public double getNumber(int variableId) {
switch (variableId) {
case NODE_RANGE_CURRENT_VALUE:
{
RangeInfoCompat rangeInfo = mNode.getRangeInfo();
return (rangeInfo == null) ? 0 : rangeInfo.getCurrent();
}
case NODE_PROGRESS_PERCENT:
return AccessibilityNodeInfoUtils.getProgressPercent(mNode);
default:
return mParentVariables.getNumber(variableId);
}
}
@Override
public @Nullable CharSequence getString(int variableId) {
switch (variableId) {
case NODE_TEXT:
return prepareSpans(AccessibilityNodeInfoUtils.getText(mNode));
case NODE_HINT:
return AccessibilityNodeInfoUtils.getHintText(mNode);
case NODE_ERROR:
return mNode.getError();
case NODE_TOOLTIP_TEXT:
return mNode.getTooltipText();
case NODE_CONTENT_DESCRIPTION:
return prepareSpans(mNode.getContentDescription());
case NODE_ROLE_DESCRIPTION:
return mNode.getRoleDescription();
case NODE_LABEL_TEXT:
return imageContents == null ? "" : imageContents.getLabel(mNode);
case NODE_VIEW_ID_TEXT:
return AccessibilityNodeInfoUtils.getViewIdText(mNode);
case NODE_SELECTED_PAGE_TITLE:
return AccessibilityNodeInfoUtils.getSelectedPageTitle(mNode);
case NODE_SELF_MENU_ACTION_TYPE:
{
String returnString = "";
if (nodeMenuProvider != null) {
List<String> menuTypeList = nodeMenuProvider.getSelfNodeMenuActionTypes(mNode);
returnString = Joiner.on(",").join(menuTypeList);
}
return returnString;
}
case NODE_STATE_DESCRIPTION:
return prepareSpans(AccessibilityNodeInfoUtils.getState(mNode));
case NODE_CAPTION_TEXT:
return imageContents == null ? "" : imageContents.getCaptionResult(mNode);
default:
return mParentVariables.getString(variableId);
}
}
private @Nullable CharSequence prepareSpans(@Nullable CharSequence text) {
// Cleans up the edit text's text if it has just 1 symbol.
// Do not double clean up the password.
if (!mNode.isPassword()) {
text = SpeechCleanupUtils.collapseRepeatedCharactersAndCleanUp(mContext, text);
}
// Wrapping with locale incase of IME input for old versions of GBoard. New version wraps
// the text in the locale of the IME so this is not needed.
if (mLocale != null && text != null) {
return LocaleUtils.wrapWithLocaleSpan(text, mLocale);
}
/**
* Wrap the text with user preferred locale changed using language switcher, with an exception
* for all talkback nodes. As talkback text is always in the system language.
*/
if (PackageManagerUtils.isTalkBackPackage(mNode.getPackageName())) {
return text;
}
// mUserPreferredLocale will take precedence over any LocaleSpan that is attached to the
// text except in case of IMEs.
if (!isKeyboardEvent(mNode) && mUserPreferredLocale != null) {
if (text instanceof Spannable) {
Spannable ss = (Spannable) text;
LocaleSpan[] spans = ss.getSpans(0, text.length(), LocaleSpan.class);
for (LocaleSpan span : spans) {
ss.removeSpan(span);
}
}
return LocaleUtils.wrapWithLocaleSpan(text, mUserPreferredLocale);
}
return text;
}
@Override
public int getEnum(int variableId) {
switch (variableId) {
case NODE_ROLE:
return mRole;
case NODE_LIVE_REGION:
return mNode.getLiveRegion();
case NODE_WINDOW_TYPE:
return AccessibilityNodeInfoUtils.getWindowType(mNode);
case NODE_RANGE_INFO_TYPE:
{
RangeInfoCompat rangeInfo = mNode.getRangeInfo();
return (rangeInfo == null) ? Compositor.RANGE_INFO_UNDEFINED : rangeInfo.getType();
}
default: // fall out
}
return mParentVariables.getEnum(variableId);
}
@Override
public @Nullable VariableDelegate getReference(int variableId) {
switch (variableId) {
case NODE_LABELED_BY:
{
if (mLabelNode == null) {
mLabelNode = mNode.getLabeledBy(); // Recycled by cleanup()
if (mLabelNode == null) {
return null;
}
}
// Create a new variable delegate for the node label.
// Do not use the same visited nodes, because this is not part of a node tree recursion.
// NodeVariables instance will recycle() obtain()ed copy of mLabelNode.
return constructForReferredNode(
mContext,
imageContents,
nodeMenuProvider,
mParentVariables,
AccessibilityNodeInfoUtils.obtain(mLabelNode),
mUserPreferredLocale);
}
case NODE_PARENT:
{
if (mParentNode == null) {
mParentNode = mNode.getParent(); // Recycled by cleanup()
if (mParentNode == null) {
return null;
}
}
// Create a new variable delegate for the node parent.
// Do not use the same visited nodes, because this is not part of a node tree recursion.
// NodeVariables instance will recycle() obtain()ed copy of mParentNode.
return constructForReferredNode(
mContext,
imageContents,
nodeMenuProvider,
mParentVariables,
AccessibilityNodeInfoUtils.obtain(mParentNode),
mUserPreferredLocale);
}
case NODE_ACTION_CLICK:
for (AccessibilityActionCompat action : mNode.getActionList()) {
if (action.getId() == AccessibilityNodeInfoCompat.ACTION_CLICK) {
return new ActionVariables(mContext, this, action);
}
}
return null;
case NODE_ACTION_LONG_CLICK:
for (AccessibilityActionCompat action : mNode.getActionList()) {
if (action.getId() == AccessibilityNodeInfoCompat.ACTION_LONG_CLICK) {
return new ActionVariables(mContext, this, action);
}
}
return null;
default:
return mParentVariables.getReference(variableId);
}
}
@Override
public int getArrayLength(int variableId) {
switch (variableId) {
case NODE_CHILDREN:
collectChildNodes();
return mChildNodes.size();
case NODE_CHILDREN_ASCENDING:
collectChildNodesAscending();
return mChildNodesAscending.size();
case NODE_ACTIONS:
return mNode.getActionList().size();
default: // fall out
}
return mParentVariables.getArrayLength(variableId);
}
@Override
public @Nullable CharSequence getArrayStringElement(int variableId, int index) {
return mParentVariables.getArrayStringElement(variableId, index);
}
/** Caller must call VariableDelegate.cleanup() on returned instance. */
@Override
public @Nullable VariableDelegate getArrayChildElement(int variableId, int index) {
switch (variableId) {
case NODE_CHILDREN:
{
// NodeVariables instance will recycle() obtain()ed copy of child node.
return constructForChildNode(
mContext,
imageContents,
nodeMenuProvider,
mParentVariables,
AccessibilityNodeInfoUtils.obtain(mChildNodes.get(index)),
mVisitedNodes,
mUserPreferredLocale);
}
case NODE_CHILDREN_ASCENDING:
{
// NodeVariables instance will recycle() obtain()ed copy of child node.
return constructForChildNode(
mContext,
imageContents,
nodeMenuProvider,
mParentVariables,
AccessibilityNodeInfoUtils.obtain(mChildNodesAscending.get(index)),
mVisitedNodes,
mUserPreferredLocale);
}
case NODE_ACTIONS:
return new ActionVariables(mContext, this, mNode.getActionList().get(index));
default:
// Do nothing.
}
return mParentVariables.getArrayChildElement(variableId, index);
}
/** Collects child nodes in mChildNodes, to allow random access order and length-finding. */
private void collectChildNodes() {
createVisitedNodes();
// Create new array for children.
if (mChildNodes != null) {
return;
}
int childNodesLength = mNode.getChildCount();
mChildNodes = new ArrayList<>();
// For each unvisited child node... collect a copy.
AccessibilityNodeInfoCompat childNode = null;
try {
for (int childIndex = 0; childIndex < childNodesLength; ++childIndex) {
childNode = mNode.getChild(childIndex); // Must be recycled.
if (childNode != null) {
if (mVisitedNodes.contains(childNode)) {
AccessibilityNodeInfoUtils.recycleNodes(childNode);
childNode = null;
} else {
mChildNodes.add(childNode);
childNode = null;
// VariableDelegate.cleanup() will recycle node created by getChild().
}
} else {
LogUtils.e(TAG, "Node has a null child at index: " + childIndex);
}
}
} finally {
AccessibilityNodeInfoUtils.recycleNodes(childNode);
}
}
/** Collects child nodes in mChildNodesAscending, to allow random access order. */
private void collectChildNodesAscending() {
createVisitedNodes();
// Create new array for children.
if (mChildNodesAscending != null) {
return;
}
mChildNodesAscending = new ArrayList<>();
ReorderedChildrenIterator childIterator =
ReorderedChildrenIterator.createAscendingIterator(mNode);
AccessibilityNodeInfoCompat childNode = null;
try {
while (childIterator.hasNext()) {
childNode = childIterator.next(); // Must be recycled.
if (childNode != null) {
if (mVisitedNodes.contains(childNode)) {
AccessibilityNodeInfoUtils.recycleNodes(childNode);
childNode = null;
} else {
mChildNodesAscending.add(childNode);
childNode = null;
// VariableDelegate will recycle node created by next().
}
} else {
LogUtils.e(TAG, "Node has a null child");
}
}
} finally {
AccessibilityNodeInfoUtils.recycleNodes(childNode);
}
}
/** Creates mVisitedNodes only on demand. */
private void createVisitedNodes() {
if (mIsRoot) {
if (mVisitedNodes != null) {
// Clears visited list for collecting children from root again.
// REFERTO for more details.
AccessibilityNodeInfoUtils.recycleNodes(mVisitedNodes);
}
mVisitedNodes = new HashSet<>();
mVisitedNodes.add(AccessibilityNodeInfoUtils.obtain(mNode));
}
}
static void declareVariables(ParseTree parseTree) {
// Variables.
// Nodes.
parseTree.addEnumVariable("node.role", NODE_ROLE, Compositor.ENUM_ROLE);
parseTree.addStringVariable("node.text", NODE_TEXT);
parseTree.addStringVariable("node.contentDescription", NODE_CONTENT_DESCRIPTION);
parseTree.addStringVariable("node.hint", NODE_HINT);
parseTree.addStringVariable("node.error", NODE_ERROR);
parseTree.addChildArrayVariable("node.children", NODE_CHILDREN);
parseTree.addChildArrayVariable("node.childrenAscending", NODE_CHILDREN_ASCENDING);
parseTree.addChildArrayVariable("node.actions", NODE_ACTIONS);
parseTree.addStringVariable("node.roleDescription", NODE_ROLE_DESCRIPTION);
parseTree.addBooleanVariable("node.isCheckable", NODE_CHECKABLE);
parseTree.addBooleanVariable("node.isChecked", NODE_CHECKED);
parseTree.addBooleanVariable("node.isVisible", NODE_IS_VISIBLE);
parseTree.addBooleanVariable("node.isAccessibilityFocusable", NODE_IS_ACCESSIBILITY_FOCUSABLE);
parseTree.addBooleanVariable("node.isFocused", NODE_IS_FOCUSED);
parseTree.addBooleanVariable("node.isAccessibilityFocused", NODE_IS_ACCESSIBILITY_FOCUSED);
parseTree.addBooleanVariable("node.isShowingHint", NODE_IS_SHOWING_HINT);
parseTree.addBooleanVariable("node.isScrollable", NODE_IS_SCROLLABLE);
parseTree.addEnumVariable("node.liveRegion", NODE_LIVE_REGION, Compositor.ENUM_LIVE_REGION);
parseTree.addBooleanVariable(
"node.supportsActionSetSelection", NODE_SUPPORTS_ACTION_SET_SELECTION);
parseTree.addBooleanVariable("node.isPassword", NODE_IS_PASSWORD);
parseTree.addBooleanVariable("node.isPinKey", NODE_IS_PIN_KEY);
parseTree.addIntegerVariable("node.windowId", NODE_WINDOW_ID);
parseTree.addEnumVariable("node.windowType", NODE_WINDOW_TYPE, Compositor.ENUM_WINDOW_TYPE);
parseTree.addBooleanVariable("node.supportsActionSelect", NODE_SUPPORTS_ACTION_SELECT);
parseTree.addStringVariable("node.labelText", NODE_LABEL_TEXT);
parseTree.addStringVariable("node.viewIdText", NODE_VIEW_ID_TEXT);
parseTree.addStringVariable("node.selectedPageTitle", NODE_SELECTED_PAGE_TITLE);
parseTree.addReferenceVariable("node.labeledBy", NODE_LABELED_BY);
parseTree.addBooleanVariable("node.isActionable", NODE_IS_ACTIONABLE);
parseTree.addBooleanVariable("node.isEnabled", NODE_IS_ENABLED);
parseTree.addBooleanVariable("node.isSelected", NODE_IS_SELECTED);
parseTree.addBooleanVariable("node.isExpandable", NODE_IS_EXPANDABLE);
parseTree.addBooleanVariable("node.isCollapsible", NODE_IS_COLLAPSIBLE);
parseTree.addReferenceVariable("node.parent", NODE_PARENT);
parseTree.addIntegerVariable("node.visibleChildCount", NODE_VISIBLE_CHILD_COUNT);
parseTree.addBooleanVariable(
"node.supportsActionScrollForward", NODE_SUPPORTS_ACTION_SCROLL_FORWARD);
parseTree.addBooleanVariable(
"node.supportsActionScrollBackward", NODE_SUPPORTS_ACTION_SCROLL_BACKWARD);
parseTree.addBooleanVariable("node.isClickable", NODE_IS_CLICKABLE);
parseTree.addBooleanVariable("node.isLongClickable", NODE_IS_LONG_CLICKABLE);
parseTree.addReferenceVariable("node.actionClick", NODE_ACTION_CLICK);
parseTree.addReferenceVariable("node.actionLongClick", NODE_ACTION_LONG_CLICK);
parseTree.addBooleanVariable("node.isHeading", NODE_IS_HEADING);
parseTree.addEnumVariable(
"node.rangeInfoType", NODE_RANGE_INFO_TYPE, Compositor.ENUM_RANGE_INFO_TYPE);
parseTree.addNumberVariable("node.rangeCurrentValue", NODE_RANGE_CURRENT_VALUE);
parseTree.addStringVariable("node.tooltipText", NODE_TOOLTIP_TEXT);
parseTree.addBooleanVariable("node.isCollectionItem", NODE_IS_COLLECTION_ITEM);
parseTree.addBooleanVariable("node.isContentInvalid", NODE_IS_CONTENT_INVALID);
parseTree.addNumberVariable("node.progressPercent", NODE_PROGRESS_PERCENT);
parseTree.addBooleanVariable(
"node.selfMenuActionAvailable", NODE_SELF_MENU_ACTION_IS_AVAILABLE);
parseTree.addStringVariable("node.selfMenuActions", NODE_SELF_MENU_ACTION_TYPE);
parseTree.addBooleanVariable("node.isWebContainer", NODE_IS_WEB_CONTAINER);
parseTree.addBooleanVariable("node.needsLabel", NODE_NEEDS_LABEL);
parseTree.addStringVariable("node.stateDescription", NODE_STATE_DESCRIPTION);
parseTree.addBooleanVariable(
"node.isWithinAccessibilityFocus", NODE_IS_WITHIN_ACCESSIBILITY_FOCUS);
parseTree.addBooleanVariable("node.isKeyboardWindow", NODE_IS_KEYBOARD_WINDOW);
parseTree.addStringVariable("node.captionText", NODE_CAPTION_TEXT);
parseTree.addBooleanVariable("node.announceDisabled", NODE_ANNOUNCE_DISABLED);
}
}
| 42.592141 | 100 | 0.724716 |
110be9027edcf3dc6dfe9f58eca4b05cda3e2944 | 862 | package it.chiarani.diario_diabete.db.persistence;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Single;
import it.chiarani.diario_diabete.db.UserDataSource;
import it.chiarani.diario_diabete.db.persistence.DAO.UserDao;
import it.chiarani.diario_diabete.db.persistence.entities.UserEntity;
/**
* Use room database as data source
*/
public class LocalUserDataSource implements UserDataSource {
private final UserDao mUserDao;
public LocalUserDataSource(UserDao userDao) {
mUserDao = userDao;
}
@Override
public Single<UserEntity> getUser() {
return mUserDao.getUser();
}
@Override
public Completable insertOrUpdateUser(UserEntity user) {
return mUserDao.insert(user);
}
@Override
public void deleteAllUsers() {
mUserDao.deleteAll();
}
}
| 23.944444 | 69 | 0.730858 |
1b5838753f80aa2f0bc352c9406d6266f3529903 | 194 | package com.xnfh.bjhospital.ui.main.recommend;
import com.xnfh.bjhospital.base.BaseModel;
/**
* Created by wangxuewei on 2017/10/19.
*/
public class RecommendModel implements BaseModel {
}
| 17.636364 | 50 | 0.762887 |
1a4fdad78b866e8fd0dea316034405bb6a1b6ea1 | 1,239 | package net.hycube.simulator.log;
public final class LogHelper {
protected static final String HYCUBE_PACKAGE = "net.hycube";
protected static final String USER_LOG_SUFFIX = "log.user";
protected static final String MESSAGES_LOG_SUFFIX = "log.messages";
protected static final String DEV_LOG_SUFFIX = "log.dev";
protected static org.apache.commons.logging.Log userLog = org.apache.commons.logging.LogFactory.getLog(HYCUBE_PACKAGE + "." + USER_LOG_SUFFIX);
protected static org.apache.commons.logging.Log msgLog = org.apache.commons.logging.LogFactory.getLog(HYCUBE_PACKAGE + "." + MESSAGES_LOG_SUFFIX);
protected static org.apache.commons.logging.Log devLog = org.apache.commons.logging.LogFactory.getLog(HYCUBE_PACKAGE + "." + DEV_LOG_SUFFIX);
protected LogHelper() {}
public static org.apache.commons.logging.Log getUserLog() {
return userLog;
}
public static org.apache.commons.logging.Log getMessagesLog() {
return msgLog;
}
public static org.apache.commons.logging.Log getDevLog() {
return devLog;
}
public static org.apache.commons.logging.Log getDevLog(Class<?> clazz) {
return org.apache.commons.logging.LogFactory.getLog(HYCUBE_PACKAGE + "." + DEV_LOG_SUFFIX + "." + clazz.getName());
}
}
| 36.441176 | 147 | 0.762712 |
948e56f562efbfb22f6905c8f10983d9ee76875c | 1,048 | package cn.com.yunweizhan.medium;
public class Solution983 {
private int[] days, costs;
private Integer[] memo;
private int[] durations = new int[]{1, 7, 30};
public int mincostTickets(int[] days, int[] costs) {
this.days = days;
this.costs = costs;
memo = new Integer[days.length];
return dp(0);
}
private int dp(int i) {
if (i >= memo.length)
return 0;
if (memo[i] != null)
return memo[i];
memo[i] = Integer.MAX_VALUE;
int j = i +1;
for (int k = 0; k < 3; k++) {
while (j < days.length && (days[j] < days[i] + durations[k])) {
j++;
}
memo[i] = Math.min(memo[i], dp(j) + costs[k]);
}
return memo[i];
}
public static void main(String[] args) {
Solution983 solution983 = new Solution983();
int[] days = {1,2,3,4,5,6,7,8,9,10,30,31}, costs = {2, 7, 15};
System.out.println(solution983.mincostTickets(days, costs));
}
}
| 26.2 | 75 | 0.505725 |
0422ecac7dac568d76d6b84ab4dff4f179cc0919 | 3,415 | package com.oxygenxml.translate.plugin;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import ro.sync.ecss.extensions.api.AuthorDocumentController;
import ro.sync.ecss.extensions.api.content.TextContentIterator;
import ro.sync.exml.editor.EditorPageConstants;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.editor.WSEditor;
import ro.sync.exml.workspace.api.editor.page.WSTextBasedEditorPage;
import ro.sync.exml.workspace.api.editor.page.author.WSAuthorEditorPage;
import ro.sync.exml.workspace.api.standalone.ui.OKCancelDialog;
/**
*
* @author Badoi Mircea
*
*/
@SuppressWarnings("serial")
public class TranslateToLanguageAction extends AbstractAction {
private PluginWorkspace pluginWorkspaceAccess;
private String languageCode;
private WSTextBasedEditorPage textPage;
/**
*
* @param pluginWorkspaceAccess Provides access to plugin workspace methods.
* @param textPage The text page form Oxygen Editor.
* @param languageCode language shorthand (ro, en, fr )
* @param languageName language full name.
*/
public TranslateToLanguageAction(PluginWorkspace pluginWorkspaceAccess, WSTextBasedEditorPage textPage,
String languageCode, String languageName) {
super(languageName);
this.pluginWorkspaceAccess = pluginWorkspaceAccess;
this.textPage = textPage;
this.languageCode = languageCode;
}
/**
* Swing action
*/
@Override
public void actionPerformed(ActionEvent e) {
String pattern = PatternGenerator.randomPatternDelimiter(1000, 9999);
WSEditor editorAccess = textPage.getParentEditor();
if (EditorPageConstants.PAGE_AUTHOR.equals(editorAccess.getCurrentPageID())) {
StringBuilder textSelectedTransformed = new StringBuilder();
WSAuthorEditorPage authorPage = (WSAuthorEditorPage) editorAccess.getCurrentPage();
AuthorDocumentController controller = authorPage.getDocumentController();
TextContentIterator documentIterator = controller.getTextContentIterator(authorPage.getSelectionStart(),
authorPage.getSelectionEnd());
ArrayList<SegmentInfo> whiteSpaces = new ArrayList<SegmentInfo>();
whiteSpaces = ReplaceWordsUtil.transformSelectedText(documentIterator, textSelectedTransformed, pattern);
if(whiteSpaces.size() <= 1) {
browse(textPage.getSelectedText());
} else {
browse(textSelectedTransformed.toString());
ReplaceDialogBox replaceDialog = new ReplaceDialogBox();
replaceDialog.setVisible(true);
if (replaceDialog.getResult() == OKCancelDialog.RESULT_OK && !replaceDialog.getText().trim().equals("")) {
ReplaceWordsUtil.replaceText(controller, authorPage.getSelectionStart(),
authorPage.getSelectionEnd(), replaceDialog.getText(), pattern, whiteSpaces);
}
}
} else {
browse(textPage.getSelectedText());
}
Languages.increasePriorityLanguage(pluginWorkspaceAccess.getOptionsStorage(), languageCode);
}
/**
* Browse selected text
*
* @param selectedText
*/
private void browse(String selectedText) {
try {
String toBrowse = "https://translate.google.com/#view=home&op=translate&sl=auto&tl=" + languageCode
+ "&text=" + pluginWorkspaceAccess.getUtilAccess().correctURL(selectedText);
Desktop.getDesktop().browse(new URL(toBrowse).toURI());
} catch (Exception ex) {
}
}
}
| 33.811881 | 109 | 0.764568 |
f2387f576c571587a53bad5c9b651561de789674 | 454 | package com.newhopemail.ware.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.newhopemail.common.utils.PageUtils;
import com.newhopemail.ware.entity.PurchaseDetailEntity;
import java.util.Map;
/**
*
*
* @author zao
* @email [email protected]
* @date 2021-05-09 02:28:30
*/
public interface PurchaseDetailService extends IService<PurchaseDetailEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| 21.619048 | 79 | 0.770925 |
71ccb0953b0ddcc96c81053e13a3257c994b4139 | 945 | package io.github.mivek.model.trend.validity;
import io.github.mivek.internationalization.Messages;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class ValidityTest {
@Test
public void testToString() {
Validity sut = new Validity();
sut.setStartDay(10);
sut.setStartHour(15);
sut.setEndDay(12);
sut.setEndHour(16);
String desc = sut.toString();
assertThat(desc, containsString(Messages.getInstance().getString("ToString.start.day.month") + "=10"));
assertThat(desc, containsString(Messages.getInstance().getString("ToString.start.hour.day") + "=15"));
assertThat(desc, containsString(Messages.getInstance().getString("ToString.end.day.month") + "=12"));
assertThat(desc, containsString(Messages.getInstance().getString("ToString.end.hour.day") + "=16"));
}
}
| 36.346154 | 111 | 0.696296 |
db7d98f0a8c74c3575ec103104600f8d71a25a81 | 568 | package cz.tacr.elza.repository;
import cz.tacr.elza.domain.ArrFund;
import cz.tacr.elza.domain.ArrRequest;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author Martin Šlapa
* @since 08.12.2016
*/
public interface RequestRepositoryCustom {
List<ArrRequest> findRequests(ArrFund fund, ArrRequest.State state, ArrRequest.ClassType type, final String description, final LocalDateTime fromDate, final LocalDateTime toDate, final String subType);
boolean setState(ArrRequest request, ArrRequest.State oldState, ArrRequest.State newState);
}
| 29.894737 | 205 | 0.790493 |
8df37a6a878aec9b656789a01d55c20987fa80e1 | 2,556 | package com.techsol.cedc.METEFLA.googlevision;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.barcode.Barcode;
public class BarcodeTrackerFactory implements MultiProcessor.Factory<Barcode> {
private GraphicTracker.DetectorListener mDetectorListener;
private CameraOverlay mCameraOverlay;
public BarcodeTrackerFactory(CameraOverlay overlay, GraphicTracker.DetectorListener detectorListener) {
mCameraOverlay = overlay;
mDetectorListener = detectorListener;
}
@Override
public Tracker<Barcode> create(Barcode barcode) {
BarcodeGraphic graphic = new BarcodeGraphic(mCameraOverlay);
GraphicTracker graphicTracker = new GraphicTracker(mCameraOverlay, graphic);
if(mDetectorListener != null) graphicTracker.setDetectorListener(mDetectorListener);
return graphicTracker;
}
}
class BarcodeGraphic extends CameraOverlay.Graphic {
private int mId;
private Paint mRectPaint;
private volatile Barcode mBarcode;
BarcodeGraphic(CameraOverlay overlay) {
super(overlay);
final int selectedColor = Color.GREEN;
mRectPaint = new Paint();
mRectPaint.setColor(selectedColor);
mRectPaint.setStyle(Paint.Style.STROKE);
mRectPaint.setStrokeWidth(4.0f);
}
public int getId() {
return mId;
}
public void setId(int id) {
this.mId = id;
}
public Barcode getBarcode() {
return mBarcode;
}
/**
* Updates the barcode instance from the detection of the most recent frame. Invalidates the
* relevant portions of the overlay to trigger a redraw.
*/
void updateItem(Barcode barcode) {
mBarcode = barcode;
postInvalidate();
}
/**
* Draws the barcode annotations for position, size, and raw value on the supplied canvas.
*/
@Override
public void draw(Canvas canvas) {
Barcode barcode = mBarcode;
if (barcode == null) {
return;
}
// Draws the bounding box around the barcode.
RectF rect = new RectF(barcode.getBoundingBox());
rect.left = translateX(rect.left);
rect.top = translateY(rect.top);
rect.right = translateX(rect.right);
rect.bottom = translateY(rect.bottom);
canvas.drawRect(rect, mRectPaint);
}
}
| 29.37931 | 107 | 0.68662 |
c618b33b2e208fbae4aff262a7f2f704ddf92586 | 3,297 | package com.plusl.xybookkeepdemo.utils;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.text.Editable;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import com.plusl.xybookkeepdemo.R;
/**
* @Author LJH
* @create 2021/12/2 15:22
*/
public class KeyBoardUtils {
private final Keyboard k1; //自定义键盘
private KeyboardView keyboardView;
private EditText editText;
public interface OnEnsureListener{
public void onEnsure();
}
OnEnsureListener onEnsureListener;
public void setOnEnsureListener(OnEnsureListener onEnsureListener) {
this.onEnsureListener = onEnsureListener;
}
public KeyBoardUtils(KeyboardView keyboardView, EditText editText) {
this.keyboardView = keyboardView;
this.editText = editText;
this.editText.setInputType(InputType.TYPE_NULL); //取消弹出系统键盘
k1 = new Keyboard(this.editText.getContext(), R.xml.soft_keyboard);
this.keyboardView.setKeyboard(k1); //设置要显示键盘的样式
this.keyboardView.setEnabled(true);
this.keyboardView.setPreviewEnabled(false);
this.keyboardView.setOnKeyboardActionListener(listener); //设置键盘按钮被点击了的监听
}
KeyboardView.OnKeyboardActionListener listener = new KeyboardView.OnKeyboardActionListener() {
@Override
public void onPress(int primaryCode) {
}
@Override
public void onRelease(int primaryCode) {
}
@Override
public void onKey(int primaryCode, int[] keyCodes) {
Editable editable = editText.getText();
int start = editText.getSelectionStart();
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE: //点击了删除键
if (editable!=null &&editable.length()>0) {
if (start>0) {
editable.delete(start-1,start);
}
}
break;
case Keyboard.KEYCODE_CANCEL: //点击了清零
editable.clear();
break;
case Keyboard.KEYCODE_DONE: //点击了完成
onEnsureListener.onEnsure(); //通过接口回调的方法,当点击确定时,可以调用这个方法
break;
default: //其他数字直接插入
editable.insert(start,Character.toString((char)primaryCode));
break;
}
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeDown() {
}
@Override
public void swipeUp() {
}
};
// 显示键盘
public void showKeyboard(){
int visibility = keyboardView.getVisibility();
if (visibility == View.INVISIBLE ||visibility==View.GONE) {
keyboardView.setVisibility(View.VISIBLE);
}
}
// 隐藏键盘
public void hideKeyboard(){
int visibility = keyboardView.getVisibility();
if (visibility== View.VISIBLE||visibility==View.INVISIBLE) {
keyboardView.setVisibility(View.GONE);
}
}
}
| 30.813084 | 98 | 0.593873 |
3b2dd9e6d2d5ad93b5da032727faeeaeee208e94 | 8,062 | /*******************************************************************************
* Copyright 2012 EMBL-EBI, Hinxton outstation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package uk.ac.ebi.embl.flatfile.writer.genbank;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import uk.ac.ebi.embl.api.entry.EntryFactory;
import uk.ac.ebi.embl.api.entry.Text;
import uk.ac.ebi.embl.api.entry.feature.Feature;
import uk.ac.ebi.embl.api.entry.feature.FeatureFactory;
import uk.ac.ebi.embl.api.entry.location.LocationFactory;
import uk.ac.ebi.embl.api.entry.qualifier.QualifierFactory;
import uk.ac.ebi.embl.api.entry.reference.Article;
import uk.ac.ebi.embl.api.entry.reference.Reference;
import uk.ac.ebi.embl.api.entry.reference.ReferenceFactory;
import uk.ac.ebi.embl.api.entry.sequence.SequenceFactory;
import uk.ac.ebi.embl.api.entry.sequence.Sequence.Topology;
import uk.ac.ebi.embl.api.validation.Severity;
import uk.ac.ebi.embl.api.validation.ValidationResult;
import uk.ac.ebi.embl.flatfile.FlatFileUtils;
import uk.ac.ebi.embl.flatfile.reader.genbank.AuthorsReader;
import uk.ac.ebi.embl.flatfile.reader.genbank.GenbankLineReader;
import uk.ac.ebi.embl.flatfile.writer.genbank.GenbankEntryWriter;
public class GenbankEntryWriterTest extends GenbankWriterTest {
public void testWrite_Entry() throws IOException {
SequenceFactory sequenceFactory = new SequenceFactory();
entry.setSequence(sequenceFactory.createSequenceByte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
entry.setPrimaryAccession("DP000153");
entry.setLastUpdated(FlatFileUtils.getDay("10-SEP-1998"));
entry.getSequence().setVersion(1);
entry.getSequence().setTopology(Topology.LINEAR);
entry.getSequence().setMoleculeType("genomic RNA");
entry.getSequence().setAccession("DP000153");
entry.setDataClass("CON");
entry.setDivision("MAM");
entry.setDescription(new Text("Cloning and characterization of a cDNA encoding a novel subtype of rat thyrotropin-releasing hormone receptor."));
entry.setComment(new Text("Cloning\n and characterization\n of a cDNA encoding a novel subtype of rat\n thyrotropin-releasing hormone receptor"));
ReferenceFactory referenceFactory = new ReferenceFactory();
Article article = referenceFactory.createArticle(
"Cloning and characterization of a cDNA encoding a novel subtype of rat thyrotropin-releasing hormone receptor",
"J. Biol. Chem.");
article.setVolume("273");
article.setIssue("48");
article.setFirstPage("32281");
article.setLastPage("32287");
article.setYear(FlatFileUtils.getDay("10-SEP-1998"));
GenbankLineReader lineReader = new GenbankLineReader();
lineReader.getCache().setPublication(article);
lineReader.setReader(new BufferedReader(new StringReader(
"RA Antonellis,A., Ayele,K., Benjamin,B., Blakesley,R.W., Young,A., Green,E.D.")));
lineReader.readLine();
ValidationResult result = (new AuthorsReader(lineReader)).read(entry);
assertEquals(0, result.count(Severity.ERROR));
article.setConsortium("Google consortium");
Reference reference = referenceFactory.createReference(article, 1);
reference.setComment("reference comment");
entry.addReference(reference);
EntryFactory entryFactory = new EntryFactory();
entry.addAssembly(entryFactory.createAssembly("AC004528", 1, 18665l,
19090l, true, 1l, 426l));
entry.addAssembly(entryFactory.createAssembly("AC004529", 6, 45665l,
98790l, true, 6l, 546l));
entry.addAssembly(entryFactory.createAssembly("AC004528", 1, 18665l,
19090l, true, 1l, 426l));
entry.addAssembly(entryFactory.createAssembly("AC004529", 6, 45665l,
98790l, true, 6l, 546l));
FeatureFactory featureFactory = new FeatureFactory();
Feature feature = featureFactory.createCdsFeature();
LocationFactory locationFactory = new LocationFactory();
feature.getLocations().addLocation(
locationFactory.createLocalRange(3514l, 4041l, false));
QualifierFactory qualifierFactory = new QualifierFactory();
feature.addQualifier(qualifierFactory.createQualifier("product",
"hypothetical protein"));
feature.addQualifier(qualifierFactory.createQualifier("note", "ORF 5"));
feature.addQualifier(qualifierFactory.createQualifier("db_xref",
"InterPro:IPR001964"));
feature.addQualifier(qualifierFactory.createQualifier("db_xref",
"UniProtKB/Swiss-Prot:P09511"));
feature.addQualifier(qualifierFactory.createQualifier("protein_id",
"CAA31466.1"));
feature.addQualifier(qualifierFactory.createQualifier("translation",
"MEEDDHAGKHDALSALSQWLWSKPLGQHNADLDDDEEVTTGQEELFLPEEQVRARHLFSQKTISREVPAEQSRSGRVYQTARHSLMECSRPTMSIKSQWSFWSSSPKPLPKIPVPSLTSWTHTVNSTPFPQLSTSSGSQSPGKGRLQRLTSTERNGTTLPRTNSGSSTKAMVLHR"));
entry.addFeature(feature);
StringWriter writer = new StringWriter();
assertTrue(new GenbankEntryWriter(entry).write(writer));
//System.out.print(writer.toString());
assertEquals(
"LOCUS DP000153 122 bp RNA linear CON 10-SEP-1998\n"+
"DEFINITION Cloning and characterization of a cDNA encoding a novel subtype of\n"+
" rat thyrotropin-releasing hormone receptor.\n"+
"ACCESSION DP000153\n"+
"VERSION DP000153.1\n" +
"KEYWORDS .\n"+
"REFERENCE 1\n"+
" AUTHORS RA Antonellis,A., Ayele,K., Benjamin,B., Blakesley,R.W., Young,A.\n" +
" and Green,E.D.\n" +
" CONSRTM Google consortium\n"+
" TITLE Cloning and characterization of a cDNA encoding a novel subtype of\n"+
" rat thyrotropin-releasing hormone receptor\n"+
" JOURNAL J. Biol. Chem. 273(48),32281-32287(1998)\n"+
" REMARK reference comment\n"+
"COMMENT Cloning\n"+
" and characterization\n"+
" of a cDNA encoding a novel subtype of rat\n"+
" thyrotropin-releasing hormone receptor\n"+
"PRIMARY TPA_SPAN PRIMARY_IDENTIFIER PRIMARY_SPAN COMP\n"+
" 1-426 AC004528.1 18665-19090 c\n"+
" 6-546 AC004529.6 45665-98790 c\n"+
" 1-426 AC004528.1 18665-19090 c\n"+
" 6-546 AC004529.6 45665-98790 c\n"+
"FEATURES Location/Qualifiers\n"+
" CDS 3514..4041\n"+
" /product=\"hypothetical protein\"\n"+
" /note=\"ORF 5\"\n"+
" /db_xref=\"InterPro:IPR001964\"\n"+
" /db_xref=\"UniProtKB/Swiss-Prot:P09511\"\n"+
" /protein_id=\"CAA31466.1\"\n"+
" /translation=\"MEEDDHAGKHDALSALSQWLWSKPLGQHNADLDDDEEVTTGQEE\n" +
" LFLPEEQVRARHLFSQKTISREVPAEQSRSGRVYQTARHSLMECSRPTMSIKSQWSFW\n" +
" SSSPKPLPKIPVPSLTSWTHTVNSTPFPQLSTSSGSQSPGKGRLQRLTSTERNGTTLP\n" +
" RTNSGSSTKAMVLHR\"\n" +
"ORIGIN\n"+
" 1 aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa\n"+
" 61 aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa\n"+
" 121 aa\n"+
"//\n",
writer.toString());
}
}
| 52.69281 | 193 | 0.680724 |
c3ad5ddf5381e15dd6e0e3e2c96aa3a63f9812fc | 291 | package com.microsoft.conference.management.domain.Repositories;
import com.microsoft.conference.management.domain.Models.ConferenceSlugIndex;
public interface IConferenceSlugIndexRepository {
void add(ConferenceSlugIndex index);
ConferenceSlugIndex FindSlugIndex(String slug);
}
| 29.1 | 77 | 0.838488 |
148b2e092b6f6125d6dace3f18e5f15f698035ce | 799 | package com.jn.langx.text.placeholder;
import com.jn.langx.text.PropertySource;
import com.jn.langx.util.Preconditions;
public class PropertySourcePlaceholderParser implements PlaceholderParser {
private PropertySource propertySource;
public PropertySourcePlaceholderParser() {
}
public PropertySourcePlaceholderParser(PropertySource propertySource) {
setPropertySource(propertySource);
}
public PropertySource getPropertySource() {
return propertySource;
}
public void setPropertySource(PropertySource propertySource) {
Preconditions.checkNotNull(propertySource);
this.propertySource = propertySource;
}
@Override
public String parse(String variable) {
return propertySource.getProperty(variable);
}
}
| 25.774194 | 75 | 0.747184 |
f3baf5f27b2bc9a88bcf2da5f628a386d2c91bc6 | 326 | package vn.fpt.fsoft.stu.cloudgateway.services;
import vn.fpt.fsoft.stu.cloudgateway.domain.EC2;
import java.util.List;
public interface EC2Services {
public List<EC2> getAllEC2InstanceInRegion(String accessKey, String secretKey, String region);
public List<EC2> getAllEC2Instance(String accessKey, String secretKey);
}
| 27.166667 | 95 | 0.809816 |
55676d466c39d9869b5c74619f4364a3787cc517 | 573 | package designPattern.creativion.singleton;
/**
* 描述: 懒汉模式,单例实例在第一次使用的时候进行创建,这个类是线程安全的,但是这个写法不推荐
*
* @author WuYanchang
* @date 2021/5/11 15:01
*/
public class SingletonExample3 {
private SingletonExample3() {
}
private static SingletonExample3 instance = null;
public static synchronized SingletonExample3 getInstance() {
if (instance == null) {
instance = new SingletonExample3();
}
return instance;
}
public void showMessage() {
System.out.println("SingletonExample3 Hello World!");
}
}
| 20.464286 | 64 | 0.657941 |
617dbde828273cb02b81e3e3b399a578a40f2e7d | 2,090 | package br.com.zup.breno.mercadolivre.produto.pergunta;
import br.com.zup.breno.mercadolivre.produto.Produto;
import br.com.zup.breno.mercadolivre.produto.opiniao.Opiniao;
import br.com.zup.breno.mercadolivre.produto.opiniao.OpiniaoResponse;
import br.com.zup.breno.mercadolivre.usuario.Usuario;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Entity
@Table(name = "perguntas")
public class Pergunta {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String titulo;
@NotNull @ManyToOne
private Usuario usuario;
@NotNull @ManyToOne
private Produto produto;
private LocalDateTime instanteDeCricao = LocalDateTime.now();
@Deprecated
public Pergunta() {
}
/**
* @param titulo não pode ser nulo.
* @param usuario não pode ser nulo.
* @param produto não pode ser nulo.
*/
public Pergunta(String titulo, Usuario usuario, Produto produto) {
this.titulo = titulo;
this.usuario = usuario;
this.produto = produto;
}
public static List<String> toList(Long produtoId, EntityManager entityManager) {
Query query = entityManager.createQuery("select p from Pergunta p where produto_id = :id");
query.setParameter("id", produtoId);
List<Pergunta> perguntas = query.getResultList();
if (perguntas == null) {
return null;
}
return perguntas.stream()
.map(pergunta -> pergunta.getTitulo())
.collect(Collectors.toList());
}
public String getTitulo() {
return titulo;
}
public String getEmailUsuario() {
return usuario.getEmail();
}
public String getNomeProduto() {
return produto.getNome();
}
public String getEmailDonoProduto() {
return produto.getUsuarioEmail();
}
}
| 27.866667 | 100 | 0.649282 |
9bb94609d90ab517887c13279671992a235f8606 | 441 | package org.jsets.shiro.demo.mapper;
import java.util.List;
import org.jsets.shiro.demo.domain.entity.UserRoleEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 用户角色关联Mapper
*
* @author wangjie (https://github.com/wj596)
* @date 2016年9月15日
*/
public interface UserRoleMapper extends BaseMapper<UserRoleEntity> {
int deleteByUser(String userId);
List<String> selectUserRoles(String account);
}
| 24.5 | 69 | 0.743764 |
7c2424fb4486e8d22bb49e5861da0ee1a77949de | 9,129 | package com.bptracker;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.bptracker.util.Utils;
import java.io.IOException;
import java.util.List;
import io.particle.android.sdk.cloud.ParticleCloud;
import io.particle.android.sdk.cloud.ParticleCloudException;
import io.particle.android.sdk.cloud.ParticleCloudSDK;
import io.particle.android.sdk.cloud.ParticleDevice;
import io.particle.android.sdk.utils.Async;
import io.particle.android.sdk.utils.TLog;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_log.d("onCreate called");
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (TextView)findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login_button || id == EditorInfo.IME_NULL) {
onLoginClick(textView);
return true;
}
return false;
}
});
Button loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
onLoginClick(view);
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void onLoginClick(final View view) {
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !Utils.isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!Utils.isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgressBar(true);
executeAsyncLoginTask(email, password);
}
}
private void executeAsyncLoginTask(final String email, final String password ) {
Async.executeAsync( ParticleCloudSDK.getCloud(), new Async.ApiWork<ParticleCloud, Void>() {
private void setLoginErrorMessage(String errorMsg){
TextView v = (TextView) findViewById(R.id.login_failed_message);
String m = getString(R.string.login_failed_msg, errorMsg);
v.setText(errorMsg == null ? "" : m);
}
@Override
public Void callApi(ParticleCloud cloud) throws ParticleCloudException, IOException {
_log.d("Logging in to particle cloud");
setLoginErrorMessage("");
cloud.logIn(email, password);
List<ParticleDevice> devices = cloud.getDevices();
_log.d("Number of devices: " + devices.size());
return null;
}
@Override
public void onSuccess(Void result) {
showProgressBar(false);
ParticleCloud cloud = ParticleCloudSDK.getCloud();
_log.d("Login successful. user: " + cloud.getLoggedInUsername()
+ " token:" + cloud.getAccessToken());
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
@Override
public void onFailure(ParticleCloudException e) {
_log.d("Login failure: " + e.getBestMessage() +
" (" + e.getServerErrorMsg() + ")");
showProgressBar(false);
setLoginErrorMessage(e.getBestMessage());
}
});
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgressBar(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
private static final TLog _log = TLog.get(LoginActivity.class);
// UI references.
private TextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
}
// private ParticleDevice mDevice;
//cloud.getDevices();
//mDevice = cloud.getDevice("3a001e001447343339383037");
//Toaster.l(LoginActivity.this, e.getBestMessage());
// e.printStackTrace();
/*
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
private void attemptLogin() {
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
}
}
*/
| 29.353698 | 99 | 0.623179 |
e38536337deb718750c8d7fb9e3ec292a7d40f36 | 1,533 | package incendius.game.items;
import incendius.Constants;
import incendius.game.players.Player;
/**
*
* @author ArrowzFtw
*/
public class BankSearch {
public static int orderItems(Player c) {
for (int i = 0; i < c.getInstance().bankArray.length; i++) {
if (c.getInstance().bankArray[i] == null) {
return i;
}
}
return -1;
}
public static void clearItems(Player c) {
for (int i = 0; i < c.getInstance().bankArray.length; i++) {
if (c.getInstance().bankArray[i] != null) {
c.getInstance().bankArray[i] = null;
}
}
}
/*
* Handles text input
*
*/
public static void inputText(Player c, String text) {
int matches = 0;
clearItems(c);
c.getInstance().bankText = text;
for (int i = 0; i < Constants.BANK_SIZE; i++) {
/*
* New item variable is opened due to loop
*/
GameItem bank = new GameItem(c.getInstance().bankItems[i], c.getInstance().bankItemsN[i]);
if (bank.id == 0 || bank.id == -1) {
continue;
}
if (orderItems(c) == -1) {
continue;
}
/*
* Creates a Item bankArray of items
*
*/
if (text == null) {
System.out.println("Text is null: " + text);
return;
}
c.getItems();
String name = c.getItems().getItemName(bank.id).toLowerCase();
text = text.toLowerCase();
if (name.contains(text)) {
c.getInstance().bankArray[orderItems(c)] = bank;
matches += 1;
}
}
c.sendMessage("Item matches found @whi@" + matches);
c.getPA().sendItemOnInterface(5382, c.getInstance().bankArray);
}
}
| 21 | 93 | 0.606001 |
567b17d2a1e242ec11a65b391fe921d80abc6d1e | 21,273 | package com.instructure.soseedy;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.12.0)",
comments = "Source: echo.proto")
public final class EchoGrpc {
private EchoGrpc() {}
public static final String SERVICE_NAME = "echo.Echo";
// Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
@java.lang.Deprecated // Use {@link #getGetMethod()} instead.
public static final io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> METHOD_GET = getGetMethodHelper();
private static volatile io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getGetMethod;
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getGetMethod() {
return getGetMethodHelper();
}
private static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getGetMethodHelper() {
io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse> getGetMethod;
if ((getGetMethod = EchoGrpc.getGetMethod) == null) {
synchronized (EchoGrpc.class) {
if ((getGetMethod = EchoGrpc.getGetMethod) == null) {
EchoGrpc.getGetMethod = getGetMethod =
io.grpc.MethodDescriptor.<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"echo.Echo", "Get"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoResponse.getDefaultInstance()))
.setSchemaDescriptor(new EchoMethodDescriptorSupplier("Get"))
.build();
}
}
}
return getGetMethod;
}
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
@java.lang.Deprecated // Use {@link #getExpandMethod()} instead.
public static final io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> METHOD_EXPAND = getExpandMethodHelper();
private static volatile io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getExpandMethod;
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getExpandMethod() {
return getExpandMethodHelper();
}
private static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getExpandMethodHelper() {
io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse> getExpandMethod;
if ((getExpandMethod = EchoGrpc.getExpandMethod) == null) {
synchronized (EchoGrpc.class) {
if ((getExpandMethod = EchoGrpc.getExpandMethod) == null) {
EchoGrpc.getExpandMethod = getExpandMethod =
io.grpc.MethodDescriptor.<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING)
.setFullMethodName(generateFullMethodName(
"echo.Echo", "Expand"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoResponse.getDefaultInstance()))
.setSchemaDescriptor(new EchoMethodDescriptorSupplier("Expand"))
.build();
}
}
}
return getExpandMethod;
}
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
@java.lang.Deprecated // Use {@link #getCollectMethod()} instead.
public static final io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> METHOD_COLLECT = getCollectMethodHelper();
private static volatile io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getCollectMethod;
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getCollectMethod() {
return getCollectMethodHelper();
}
private static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getCollectMethodHelper() {
io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse> getCollectMethod;
if ((getCollectMethod = EchoGrpc.getCollectMethod) == null) {
synchronized (EchoGrpc.class) {
if ((getCollectMethod = EchoGrpc.getCollectMethod) == null) {
EchoGrpc.getCollectMethod = getCollectMethod =
io.grpc.MethodDescriptor.<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.CLIENT_STREAMING)
.setFullMethodName(generateFullMethodName(
"echo.Echo", "Collect"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoResponse.getDefaultInstance()))
.setSchemaDescriptor(new EchoMethodDescriptorSupplier("Collect"))
.build();
}
}
}
return getCollectMethod;
}
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
@java.lang.Deprecated // Use {@link #getUpdateMethod()} instead.
public static final io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> METHOD_UPDATE = getUpdateMethodHelper();
private static volatile io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getUpdateMethod;
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getUpdateMethod() {
return getUpdateMethodHelper();
}
private static io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse> getUpdateMethodHelper() {
io.grpc.MethodDescriptor<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse> getUpdateMethod;
if ((getUpdateMethod = EchoGrpc.getUpdateMethod) == null) {
synchronized (EchoGrpc.class) {
if ((getUpdateMethod = EchoGrpc.getUpdateMethod) == null) {
EchoGrpc.getUpdateMethod = getUpdateMethod =
io.grpc.MethodDescriptor.<com.instructure.soseedy.EchoRequest, com.instructure.soseedy.EchoResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
.setFullMethodName(generateFullMethodName(
"echo.Echo", "Update"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.instructure.soseedy.EchoResponse.getDefaultInstance()))
.setSchemaDescriptor(new EchoMethodDescriptorSupplier("Update"))
.build();
}
}
}
return getUpdateMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static EchoStub newStub(io.grpc.Channel channel) {
return new EchoStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static EchoBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new EchoBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static EchoFutureStub newFutureStub(
io.grpc.Channel channel) {
return new EchoFutureStub(channel);
}
/**
*/
public static abstract class EchoImplBase implements io.grpc.BindableService {
/**
* <pre>
* Immediately returns an echo of a request.
* </pre>
*/
public void get(com.instructure.soseedy.EchoRequest request,
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetMethodHelper(), responseObserver);
}
/**
* <pre>
* Splits a request into words and returns each word in a stream of messages.
* </pre>
*/
public void expand(com.instructure.soseedy.EchoRequest request,
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
asyncUnimplementedUnaryCall(getExpandMethodHelper(), responseObserver);
}
/**
* <pre>
* Collects a stream of messages and returns them concatenated when the caller closes.
* </pre>
*/
public io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoRequest> collect(
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getCollectMethodHelper(), responseObserver);
}
/**
* <pre>
* Streams back messages as they are received in an input stream.
* </pre>
*/
public io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoRequest> update(
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
return asyncUnimplementedStreamingCall(getUpdateMethodHelper(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getGetMethodHelper(),
asyncUnaryCall(
new MethodHandlers<
com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse>(
this, METHODID_GET)))
.addMethod(
getExpandMethodHelper(),
asyncServerStreamingCall(
new MethodHandlers<
com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse>(
this, METHODID_EXPAND)))
.addMethod(
getCollectMethodHelper(),
asyncClientStreamingCall(
new MethodHandlers<
com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse>(
this, METHODID_COLLECT)))
.addMethod(
getUpdateMethodHelper(),
asyncBidiStreamingCall(
new MethodHandlers<
com.instructure.soseedy.EchoRequest,
com.instructure.soseedy.EchoResponse>(
this, METHODID_UPDATE)))
.build();
}
}
/**
*/
public static final class EchoStub extends io.grpc.stub.AbstractStub<EchoStub> {
private EchoStub(io.grpc.Channel channel) {
super(channel);
}
private EchoStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected EchoStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new EchoStub(channel, callOptions);
}
/**
* <pre>
* Immediately returns an echo of a request.
* </pre>
*/
public void get(com.instructure.soseedy.EchoRequest request,
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getGetMethodHelper(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Splits a request into words and returns each word in a stream of messages.
* </pre>
*/
public void expand(com.instructure.soseedy.EchoRequest request,
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
asyncServerStreamingCall(
getChannel().newCall(getExpandMethodHelper(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Collects a stream of messages and returns them concatenated when the caller closes.
* </pre>
*/
public io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoRequest> collect(
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
return asyncClientStreamingCall(
getChannel().newCall(getCollectMethodHelper(), getCallOptions()), responseObserver);
}
/**
* <pre>
* Streams back messages as they are received in an input stream.
* </pre>
*/
public io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoRequest> update(
io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse> responseObserver) {
return asyncBidiStreamingCall(
getChannel().newCall(getUpdateMethodHelper(), getCallOptions()), responseObserver);
}
}
/**
*/
public static final class EchoBlockingStub extends io.grpc.stub.AbstractStub<EchoBlockingStub> {
private EchoBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private EchoBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected EchoBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new EchoBlockingStub(channel, callOptions);
}
/**
* <pre>
* Immediately returns an echo of a request.
* </pre>
*/
public com.instructure.soseedy.EchoResponse get(com.instructure.soseedy.EchoRequest request) {
return blockingUnaryCall(
getChannel(), getGetMethodHelper(), getCallOptions(), request);
}
/**
* <pre>
* Splits a request into words and returns each word in a stream of messages.
* </pre>
*/
public java.util.Iterator<com.instructure.soseedy.EchoResponse> expand(
com.instructure.soseedy.EchoRequest request) {
return blockingServerStreamingCall(
getChannel(), getExpandMethodHelper(), getCallOptions(), request);
}
}
/**
*/
public static final class EchoFutureStub extends io.grpc.stub.AbstractStub<EchoFutureStub> {
private EchoFutureStub(io.grpc.Channel channel) {
super(channel);
}
private EchoFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected EchoFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new EchoFutureStub(channel, callOptions);
}
/**
* <pre>
* Immediately returns an echo of a request.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.instructure.soseedy.EchoResponse> get(
com.instructure.soseedy.EchoRequest request) {
return futureUnaryCall(
getChannel().newCall(getGetMethodHelper(), getCallOptions()), request);
}
}
private static final int METHODID_GET = 0;
private static final int METHODID_EXPAND = 1;
private static final int METHODID_COLLECT = 2;
private static final int METHODID_UPDATE = 3;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final EchoImplBase serviceImpl;
private final int methodId;
MethodHandlers(EchoImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_GET:
serviceImpl.get((com.instructure.soseedy.EchoRequest) request,
(io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse>) responseObserver);
break;
case METHODID_EXPAND:
serviceImpl.expand((com.instructure.soseedy.EchoRequest) request,
(io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_COLLECT:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.collect(
(io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse>) responseObserver);
case METHODID_UPDATE:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.update(
(io.grpc.stub.StreamObserver<com.instructure.soseedy.EchoResponse>) responseObserver);
default:
throw new AssertionError();
}
}
}
private static abstract class EchoBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
EchoBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.instructure.soseedy.EchoOuterClass.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Echo");
}
}
private static final class EchoFileDescriptorSupplier
extends EchoBaseDescriptorSupplier {
EchoFileDescriptorSupplier() {}
}
private static final class EchoMethodDescriptorSupplier
extends EchoBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
EchoMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (EchoGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new EchoFileDescriptorSupplier())
.addMethod(getGetMethodHelper())
.addMethod(getExpandMethodHelper())
.addMethod(getCollectMethodHelper())
.addMethod(getUpdateMethodHelper())
.build();
}
}
}
return result;
}
}
| 40.831094 | 126 | 0.699478 |
f06f8c1ecbf03fa0f065e1d29a928f55127a3878 | 2,189 | package com.techhounds.lib.hid;
import edu.wpi.first.wpilibj.GenericHID;
public class DPadButton extends JoystickButton {
protected boolean isEightDirectional;
protected int direction;
public interface Direction {
int UP = 20, UP_RIGHT = 21, RIGHT = 22, DOWN_RIGHT = 23,
DOWN = 24, DOWN_LEFT = 25, LEFT = 26, UP_LEFT = 27;
}
public DPadButton(GenericHID joystick, int direction) {
this(joystick, direction, false);
}
public DPadButton(GenericHID joystick, int direction, boolean isEightDirectional) {
super(joystick);
this.isEightDirectional = isEightDirectional;
this.direction = direction;
}
@Override
public boolean get() {
if(off)
return false;
if(!isDPADButton(direction))
return super.get();
int angle = joystick.getPOV();
if(!isEightDirectional) {
if (direction == Direction.LEFT) {
return angle == 270 || angle == 315 || angle == 225;
} else if (direction == Direction.RIGHT) {
return angle == 90 || angle == 45 || angle== 135;
} else if (direction == Direction.UP) {
return angle == 0 || angle == 45 || angle == 315;
} else if (direction == Direction.DOWN) {
return angle == 180 || angle == 135 || angle == 225;
} else {
return false;
}
} else {
if(direction == Direction.UP){
return angle == 0;
}else if(direction == Direction.UP_LEFT){
return angle == 45;
}else if(direction == Direction.LEFT){
return angle == 90;
}else if(direction == Direction.DOWN_LEFT){
return angle == 135;
}else if(direction == Direction.DOWN){
return angle == 180;
}else if(direction == Direction.DOWN_RIGHT){
return angle == 225;
}else if(direction == Direction.RIGHT){
return angle == 270;
}else if(direction == Direction.UP_RIGHT){
return angle == 315;
}else{
return false;
}
}
}
public static boolean isDPADButton(int buttonID) {
return !(buttonID < 20 || buttonID > 27);
}
}
| 29.186667 | 87 | 0.573321 |
7611ae5d4c406e3f17703b9a20910599dae974d2 | 90,894 | /*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.beans.JavaBean;
import java.beans.BeanProperty;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.Transient;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.accessibility.*;
/**
* A component that combines a button or editable field and a drop-down list.
* The user can select a value from the drop-down list, which appears at the
* user's request. If you make the combo box editable, then the combo box
* includes an editable field into which the user can type a value.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* <p>
* See <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html">How to Use Combo Boxes</a>
* in <a href="https://docs.oracle.com/javase/tutorial/"><em>The Java Tutorial</em></a>
* for further information.
*
* @see ComboBoxModel
* @see DefaultComboBoxModel
*
* @param <E> the type of the elements of this combo box
*
* @author Arnaud Weber
* @author Mark Davidson
* @since 1.2
*/
@JavaBean(defaultProperty = "UI", description = "A combination of a text field and a drop-down list.")
@SwingContainer(false)
@SuppressWarnings("serial") // Same-version serialization only
public class JComboBox<E> extends JComponent
implements ItemSelectable,ListDataListener,ActionListener, Accessible {
/**
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ComboBoxUI";
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getModel
* @see #setModel
*/
protected ComboBoxModel<E> dataModel;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getRenderer
* @see #setRenderer
*/
protected ListCellRenderer<? super E> renderer;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getEditor
* @see #setEditor
*/
protected ComboBoxEditor editor;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #getMaximumRowCount
* @see #setMaximumRowCount
*/
protected int maximumRowCount = 8;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #isEditable
* @see #setEditable
*/
protected boolean isEditable = false;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #setKeySelectionManager
* @see #getKeySelectionManager
*/
protected KeySelectionManager keySelectionManager = null;
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #setActionCommand
* @see #getActionCommand
*/
protected String actionCommand = "comboBoxChanged";
/**
* This protected field is implementation specific. Do not access directly
* or override. Use the accessor methods instead.
*
* @see #setLightWeightPopupEnabled
* @see #isLightWeightPopupEnabled
*/
protected boolean lightWeightPopupEnabled = JPopupMenu.getDefaultLightWeightPopupEnabled();
/**
* This protected field is implementation specific. Do not access directly
* or override.
*/
protected Object selectedItemReminder = null;
private E prototypeDisplayValue;
// Flag to ensure that infinite loops do not occur with ActionEvents.
private boolean firingActionEvent = false;
// Flag to ensure the we don't get multiple ActionEvents on item selection.
private boolean selectingItem = false;
// Flag to indicate UI update is in progress
private transient boolean updateInProgress;
/**
* Creates a <code>JComboBox</code> that takes its items from an
* existing <code>ComboBoxModel</code>. Since the
* <code>ComboBoxModel</code> is provided, a combo box created using
* this constructor does not create a default combo box model and
* may impact how the insert, remove and add methods behave.
*
* @param aModel the <code>ComboBoxModel</code> that provides the
* displayed list of items
* @see DefaultComboBoxModel
*/
public JComboBox(ComboBoxModel<E> aModel) {
super();
setModel(aModel);
init();
}
/**
* Creates a <code>JComboBox</code> that contains the elements
* in the specified array. By default the first item in the array
* (and therefore the data model) becomes selected.
*
* @param items an array of objects to insert into the combo box
* @see DefaultComboBoxModel
*/
public JComboBox(E[] items) {
super();
setModel(new DefaultComboBoxModel<E>(items));
init();
}
/**
* Creates a <code>JComboBox</code> that contains the elements
* in the specified Vector. By default the first item in the vector
* (and therefore the data model) becomes selected.
*
* @param items an array of vectors to insert into the combo box
* @see DefaultComboBoxModel
*/
public JComboBox(Vector<E> items) {
super();
setModel(new DefaultComboBoxModel<E>(items));
init();
}
/**
* Creates a <code>JComboBox</code> with a default data model.
* The default data model is an empty list of objects.
* Use <code>addItem</code> to add items. By default the first item
* in the data model becomes selected.
*
* @see DefaultComboBoxModel
*/
public JComboBox() {
super();
setModel(new DefaultComboBoxModel<E>());
init();
}
private void init() {
installAncestorListener();
setUIProperty("opaque",true);
updateUI();
}
/**
* Registers ancestor listener so that it will receive
* {@code AncestorEvents} when it or any of its ancestors
* move or are made visible or invisible.
* Events are also sent when the component or its ancestors are added
* or removed from the containment hierarchy.
*/
protected void installAncestorListener() {
addAncestorListener(new AncestorListener(){
public void ancestorAdded(AncestorEvent event){ hidePopup();}
public void ancestorRemoved(AncestorEvent event){ hidePopup();}
public void ancestorMoved(AncestorEvent event){
if (event.getSource() != JComboBox.this)
hidePopup();
}});
}
/**
* Sets the L&F object that renders this component.
*
* @param ui the <code>ComboBoxUI</code> L&F object
* @see UIDefaults#getUI
*/
@BeanProperty(hidden = true, visualUpdate = true, description
= "The UI object that implements the Component's LookAndFeel.")
public void setUI(ComboBoxUI ui) {
super.setUI(ui);
}
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
public void updateUI() {
if (!updateInProgress) {
updateInProgress = true;
try {
setUI((ComboBoxUI)UIManager.getUI(this));
ListCellRenderer<? super E> renderer = getRenderer();
if (renderer instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component)renderer);
}
} finally {
updateInProgress = false;
}
}
}
/**
* Returns the name of the L&F class that renders this component.
*
* @return the string "ComboBoxUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
@BeanProperty(bound = false)
public String getUIClassID() {
return uiClassID;
}
/**
* Returns the L&F object that renders this component.
*
* @return the ComboBoxUI object that renders this component
*/
public ComboBoxUI getUI() {
return(ComboBoxUI)ui;
}
/**
* Sets the data model that the <code>JComboBox</code> uses to obtain
* the list of items.
*
* @param aModel the <code>ComboBoxModel</code> that provides the
* displayed list of items
*/
@BeanProperty(description
= "Model that the combo box uses to get data to display.")
public void setModel(ComboBoxModel<E> aModel) {
ComboBoxModel<E> oldModel = dataModel;
if (oldModel != null) {
oldModel.removeListDataListener(this);
}
dataModel = aModel;
dataModel.addListDataListener(this);
// set the current selected item.
selectedItemReminder = dataModel.getSelectedItem();
firePropertyChange( "model", oldModel, dataModel);
}
/**
* Returns the data model currently used by the <code>JComboBox</code>.
*
* @return the <code>ComboBoxModel</code> that provides the displayed
* list of items
*/
public ComboBoxModel<E> getModel() {
return dataModel;
}
/*
* Properties
*/
/**
* Sets the <code>lightWeightPopupEnabled</code> property, which
* provides a hint as to whether or not a lightweight
* <code>Component</code> should be used to contain the
* <code>JComboBox</code>, versus a heavyweight
* <code>Component</code> such as a <code>Panel</code>
* or a <code>Window</code>. The decision of lightweight
* versus heavyweight is ultimately up to the
* <code>JComboBox</code>. Lightweight windows are more
* efficient than heavyweight windows, but lightweight
* and heavyweight components do not mix well in a GUI.
* If your application mixes lightweight and heavyweight
* components, you should disable lightweight popups.
* The default value for the <code>lightWeightPopupEnabled</code>
* property is <code>true</code>, unless otherwise specified
* by the look and feel. Some look and feels always use
* heavyweight popups, no matter what the value of this property.
* <p>
* See the article <a href="http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html">Mixing Heavy and Light Components</a>
* This method fires a property changed event.
*
* @param aFlag if <code>true</code>, lightweight popups are desired
*/
@BeanProperty(expert = true, description
= "Set to <code>false</code> to require heavyweight popups.")
public void setLightWeightPopupEnabled(boolean aFlag) {
boolean oldFlag = lightWeightPopupEnabled;
lightWeightPopupEnabled = aFlag;
firePropertyChange("lightWeightPopupEnabled", oldFlag, lightWeightPopupEnabled);
}
/**
* Gets the value of the <code>lightWeightPopupEnabled</code>
* property.
*
* @return the value of the <code>lightWeightPopupEnabled</code>
* property
* @see #setLightWeightPopupEnabled
*/
public boolean isLightWeightPopupEnabled() {
return lightWeightPopupEnabled;
}
/**
* Determines whether the <code>JComboBox</code> field is editable.
* An editable <code>JComboBox</code> allows the user to type into the
* field or selected an item from the list to initialize the field,
* after which it can be edited. (The editing affects only the field,
* the list item remains intact.) A non editable <code>JComboBox</code>
* displays the selected item in the field,
* but the selection cannot be modified.
*
* @param aFlag a boolean value, where true indicates that the
* field is editable
*/
@BeanProperty(preferred = true, description
= "If true, the user can type a new value in the combo box.")
public void setEditable(boolean aFlag) {
boolean oldFlag = isEditable;
isEditable = aFlag;
firePropertyChange( "editable", oldFlag, isEditable );
}
/**
* Returns true if the <code>JComboBox</code> is editable.
* By default, a combo box is not editable.
*
* @return true if the <code>JComboBox</code> is editable, else false
*/
public boolean isEditable() {
return isEditable;
}
/**
* Sets the maximum number of rows the <code>JComboBox</code> displays.
* If the number of objects in the model is greater than count,
* the combo box uses a scrollbar.
*
* @param count an integer specifying the maximum number of items to
* display in the list before using a scrollbar
*/
@BeanProperty(preferred = true, description
= "The maximum number of rows the popup should have")
public void setMaximumRowCount(int count) {
int oldCount = maximumRowCount;
maximumRowCount = count;
firePropertyChange( "maximumRowCount", oldCount, maximumRowCount );
}
/**
* Returns the maximum number of items the combo box can display
* without a scrollbar
*
* @return an integer specifying the maximum number of items that are
* displayed in the list before using a scrollbar
*/
public int getMaximumRowCount() {
return maximumRowCount;
}
/**
* Sets the renderer that paints the list items and the item selected from the list in
* the JComboBox field. The renderer is used if the JComboBox is not
* editable. If it is editable, the editor is used to render and edit
* the selected item.
* <p>
* The default renderer displays a string or an icon.
* Other renderers can handle graphic images and composite items.
* <p>
* To display the selected item,
* <code>aRenderer.getListCellRendererComponent</code>
* is called, passing the list object and an index of -1.
*
* @param aRenderer the <code>ListCellRenderer</code> that
* displays the selected item
* @see #setEditor
*/
@BeanProperty(expert = true, description
= "The renderer that paints the item selected in the list.")
public void setRenderer(ListCellRenderer<? super E> aRenderer) {
ListCellRenderer<? super E> oldRenderer = renderer;
renderer = aRenderer;
firePropertyChange( "renderer", oldRenderer, renderer );
invalidate();
}
/**
* Returns the renderer used to display the selected item in the
* <code>JComboBox</code> field.
*
* @return the <code>ListCellRenderer</code> that displays
* the selected item.
*/
public ListCellRenderer<? super E> getRenderer() {
return renderer;
}
/**
* Sets the editor used to paint and edit the selected item in the
* <code>JComboBox</code> field. The editor is used only if the
* receiving <code>JComboBox</code> is editable. If not editable,
* the combo box uses the renderer to paint the selected item.
*
* @param anEditor the <code>ComboBoxEditor</code> that
* displays the selected item
* @see #setRenderer
*/
@BeanProperty(expert = true, description
= "The editor that combo box uses to edit the current value")
public void setEditor(ComboBoxEditor anEditor) {
ComboBoxEditor oldEditor = editor;
if ( editor != null ) {
editor.removeActionListener(this);
}
editor = anEditor;
if ( editor != null ) {
editor.addActionListener(this);
}
firePropertyChange( "editor", oldEditor, editor );
}
/**
* Returns the editor used to paint and edit the selected item in the
* <code>JComboBox</code> field.
*
* @return the <code>ComboBoxEditor</code> that displays the selected item
*/
public ComboBoxEditor getEditor() {
return editor;
}
//
// Selection
//
/**
* Sets the selected item in the combo box display area to the object in
* the argument.
* If <code>anObject</code> is in the list, the display area shows
* <code>anObject</code> selected.
* <p>
* If <code>anObject</code> is <i>not</i> in the list and the combo box is
* uneditable, it will not change the current selection. For editable
* combo boxes, the selection will change to <code>anObject</code>.
* <p>
* If this constitutes a change in the selected item,
* <code>ItemListener</code>s added to the combo box will be notified with
* one or two <code>ItemEvent</code>s.
* If there is a current selected item, an <code>ItemEvent</code> will be
* fired and the state change will be <code>ItemEvent.DESELECTED</code>.
* If <code>anObject</code> is in the list and is not currently selected
* then an <code>ItemEvent</code> will be fired and the state change will
* be <code>ItemEvent.SELECTED</code>.
* <p>
* <code>ActionListener</code>s added to the combo box will be notified
* with an <code>ActionEvent</code> when this method is called.
*
* @param anObject the list object to select; use <code>null</code> to
clear the selection
*/
@BeanProperty(bound = false, preferred = true, description
= "Sets the selected item in the JComboBox.")
public void setSelectedItem(Object anObject) {
Object oldSelection = selectedItemReminder;
Object objectToSelect = anObject;
if (oldSelection == null || !oldSelection.equals(anObject)) {
if (anObject != null && !isEditable()) {
// For non editable combo boxes, an invalid selection
// will be rejected.
boolean found = false;
for (int i = 0; i < dataModel.getSize(); i++) {
E element = dataModel.getElementAt(i);
if (anObject.equals(element)) {
found = true;
objectToSelect = element;
break;
}
}
if (!found) {
return;
}
getEditor().setItem(anObject);
}
// Must toggle the state of this flag since this method
// call may result in ListDataEvents being fired.
selectingItem = true;
dataModel.setSelectedItem(objectToSelect);
selectingItem = false;
if (selectedItemReminder != dataModel.getSelectedItem()) {
// in case a users implementation of ComboBoxModel
// doesn't fire a ListDataEvent when the selection
// changes.
selectedItemChanged();
}
}
fireActionEvent();
}
/**
* Returns the current selected item.
* <p>
* If the combo box is editable, then this value may not have been added
* to the combo box with <code>addItem</code>, <code>insertItemAt</code>
* or the data constructors.
*
* @return the current selected Object
* @see #setSelectedItem
*/
public Object getSelectedItem() {
return dataModel.getSelectedItem();
}
/**
* Selects the item at index <code>anIndex</code>.
*
* @param anIndex an integer specifying the list item to select,
* where 0 specifies the first item in the list and -1 indicates no selection
* @exception IllegalArgumentException if <code>anIndex</code> < -1 or
* <code>anIndex</code> is greater than or equal to size
*/
@BeanProperty(bound = false, preferred = true, description
= "The item at index is selected.")
public void setSelectedIndex(int anIndex) {
int size = dataModel.getSize();
if ( anIndex == -1 ) {
setSelectedItem( null );
} else if ( anIndex < -1 || anIndex >= size ) {
throw new IllegalArgumentException("setSelectedIndex: " + anIndex + " out of bounds");
} else {
setSelectedItem(dataModel.getElementAt(anIndex));
}
}
/**
* Returns the first item in the list that matches the given item.
* The result is not always defined if the <code>JComboBox</code>
* allows selected items that are not in the list.
* Returns -1 if there is no selected item or if the user specified
* an item which is not in the list.
* @return an integer specifying the currently selected list item,
* where 0 specifies
* the first item in the list;
* or -1 if no item is selected or if
* the currently selected item is not in the list
*/
@Transient
public int getSelectedIndex() {
Object sObject = dataModel.getSelectedItem();
int i,c;
E obj;
for ( i=0,c=dataModel.getSize();i<c;i++ ) {
obj = dataModel.getElementAt(i);
if ( obj != null && obj.equals(sObject) )
return i;
}
return -1;
}
/**
* Returns the "prototypical display" value - an Object used
* for the calculation of the display height and width.
*
* @return the value of the <code>prototypeDisplayValue</code> property
* @see #setPrototypeDisplayValue
* @since 1.4
*/
public E getPrototypeDisplayValue() {
return prototypeDisplayValue;
}
/**
* Sets the prototype display value used to calculate the size of the display
* for the UI portion.
* <p>
* If a prototype display value is specified, the preferred size of
* the combo box is calculated by configuring the renderer with the
* prototype display value and obtaining its preferred size. Specifying
* the preferred display value is often useful when the combo box will be
* displaying large amounts of data. If no prototype display value has
* been specified, the renderer must be configured for each value from
* the model and its preferred size obtained, which can be
* relatively expensive.
*
* @param prototypeDisplayValue the prototype display value
* @see #getPrototypeDisplayValue
* @since 1.4
*/
@BeanProperty(visualUpdate = true, description
= "The display prototype value, used to compute display width and height.")
public void setPrototypeDisplayValue(E prototypeDisplayValue) {
Object oldValue = this.prototypeDisplayValue;
this.prototypeDisplayValue = prototypeDisplayValue;
firePropertyChange("prototypeDisplayValue", oldValue, prototypeDisplayValue);
}
/**
* Adds an item to the item list.
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
* <p>
* <strong>Warning:</strong>
* Focus and keyboard navigation problems may arise if you add duplicate
* String objects. A workaround is to add new objects instead of String
* objects and make sure that the toString() method is defined.
* For example:
* <pre>
* comboBox.addItem(makeObj("Item 1"));
* comboBox.addItem(makeObj("Item 1"));
* ...
* private Object makeObj(final String item) {
* return new Object() { public String toString() { return item; } };
* }
* </pre>
*
* @param item the item to add to the list
* @see MutableComboBoxModel
*/
public void addItem(E item) {
checkMutableComboBoxModel();
((MutableComboBoxModel<E>)dataModel).addElement(item);
}
/**
* Inserts an item into the item list at a given index.
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
*
* @param item the item to add to the list
* @param index an integer specifying the position at which
* to add the item
* @see MutableComboBoxModel
*/
public void insertItemAt(E item, int index) {
checkMutableComboBoxModel();
((MutableComboBoxModel<E>)dataModel).insertElementAt(item,index);
}
/**
* Removes an item from the item list.
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
*
* @param anObject the object to remove from the item list
* @see MutableComboBoxModel
*/
public void removeItem(Object anObject) {
checkMutableComboBoxModel();
((MutableComboBoxModel)dataModel).removeElement(anObject);
}
/**
* Removes the item at <code>anIndex</code>
* This method works only if the <code>JComboBox</code> uses a
* mutable data model.
*
* @param anIndex an int specifying the index of the item to remove,
* where 0
* indicates the first item in the list
* @see MutableComboBoxModel
*/
public void removeItemAt(int anIndex) {
checkMutableComboBoxModel();
((MutableComboBoxModel<E>)dataModel).removeElementAt( anIndex );
}
/**
* Removes all items from the item list.
*/
public void removeAllItems() {
checkMutableComboBoxModel();
MutableComboBoxModel<E> model = (MutableComboBoxModel<E>)dataModel;
int size = model.getSize();
if ( model instanceof DefaultComboBoxModel ) {
((DefaultComboBoxModel)model).removeAllElements();
}
else {
for ( int i = 0; i < size; ++i ) {
E element = model.getElementAt( 0 );
model.removeElement( element );
}
}
selectedItemReminder = null;
if (isEditable()) {
editor.setItem(null);
}
}
/**
* Checks that the <code>dataModel</code> is an instance of
* <code>MutableComboBoxModel</code>. If not, it throws an exception.
* @exception RuntimeException if <code>dataModel</code> is not an
* instance of <code>MutableComboBoxModel</code>.
*/
void checkMutableComboBoxModel() {
if ( !(dataModel instanceof MutableComboBoxModel) )
throw new RuntimeException("Cannot use this method with a non-Mutable data model.");
}
/**
* Causes the combo box to display its popup window.
* @see #setPopupVisible
*/
public void showPopup() {
setPopupVisible(true);
}
/**
* Causes the combo box to close its popup window.
* @see #setPopupVisible
*/
public void hidePopup() {
setPopupVisible(false);
}
/**
* Sets the visibility of the popup.
*
* @param v if {@code true} shows the popup, otherwise, hides the popup.
*/
public void setPopupVisible(boolean v) {
getUI().setPopupVisible(this, v);
}
/**
* Determines the visibility of the popup.
*
* @return true if the popup is visible, otherwise returns false
*/
public boolean isPopupVisible() {
return getUI().isPopupVisible(this);
}
/** Selection **/
/**
* Adds an <code>ItemListener</code>.
* <p>
* <code>aListener</code> will receive one or two <code>ItemEvent</code>s when
* the selected item changes.
*
* @param aListener the <code>ItemListener</code> that is to be notified
* @see #setSelectedItem
*/
public void addItemListener(ItemListener aListener) {
listenerList.add(ItemListener.class,aListener);
}
/** Removes an <code>ItemListener</code>.
*
* @param aListener the <code>ItemListener</code> to remove
*/
public void removeItemListener(ItemListener aListener) {
listenerList.remove(ItemListener.class,aListener);
}
/**
* Returns an array of all the <code>ItemListener</code>s added
* to this JComboBox with addItemListener().
*
* @return all of the <code>ItemListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
@BeanProperty(bound = false)
public ItemListener[] getItemListeners() {
return listenerList.getListeners(ItemListener.class);
}
/**
* Adds an <code>ActionListener</code>.
* <p>
* The <code>ActionListener</code> will receive an <code>ActionEvent</code>
* when a selection has been made. If the combo box is editable, then
* an <code>ActionEvent</code> will be fired when editing has stopped.
*
* @param l the <code>ActionListener</code> that is to be notified
* @see #setSelectedItem
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class,l);
}
/** Removes an <code>ActionListener</code>.
*
* @param l the <code>ActionListener</code> to remove
*/
public void removeActionListener(ActionListener l) {
if ((l != null) && (getAction() == l)) {
setAction(null);
} else {
listenerList.remove(ActionListener.class, l);
}
}
/**
* Returns an array of all the <code>ActionListener</code>s added
* to this JComboBox with addActionListener().
*
* @return all of the <code>ActionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
@BeanProperty(bound = false)
public ActionListener[] getActionListeners() {
return listenerList.getListeners(ActionListener.class);
}
/**
* Adds a <code>PopupMenu</code> listener which will listen to notification
* messages from the popup portion of the combo box.
* <p>
* For all standard look and feels shipped with Java, the popup list
* portion of combo box is implemented as a <code>JPopupMenu</code>.
* A custom look and feel may not implement it this way and will
* therefore not receive the notification.
*
* @param l the <code>PopupMenuListener</code> to add
* @since 1.4
*/
public void addPopupMenuListener(PopupMenuListener l) {
listenerList.add(PopupMenuListener.class,l);
}
/**
* Removes a <code>PopupMenuListener</code>.
*
* @param l the <code>PopupMenuListener</code> to remove
* @see #addPopupMenuListener
* @since 1.4
*/
public void removePopupMenuListener(PopupMenuListener l) {
listenerList.remove(PopupMenuListener.class,l);
}
/**
* Returns an array of all the <code>PopupMenuListener</code>s added
* to this JComboBox with addPopupMenuListener().
*
* @return all of the <code>PopupMenuListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
@BeanProperty(bound = false)
public PopupMenuListener[] getPopupMenuListeners() {
return listenerList.getListeners(PopupMenuListener.class);
}
/**
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box will become visible.
* <p>
* This method is public but should not be called by anything other than
* the UI delegate.
* @see #addPopupMenuListener
* @since 1.4
*/
public void firePopupMenuWillBecomeVisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeVisible(e);
}
}
}
/**
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box has become invisible.
* <p>
* This method is public but should not be called by anything other than
* the UI delegate.
* @see #addPopupMenuListener
* @since 1.4
*/
public void firePopupMenuWillBecomeInvisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuWillBecomeInvisible(e);
}
}
}
/**
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box has been canceled.
* <p>
* This method is public but should not be called by anything other than
* the UI delegate.
* @see #addPopupMenuListener
* @since 1.4
*/
public void firePopupMenuCanceled() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e=null;
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener)listeners[i+1]).popupMenuCanceled(e);
}
}
}
/**
* Sets the action command that should be included in the event
* sent to action listeners.
*
* @param aCommand a string containing the "command" that is sent
* to action listeners; the same listener can then
* do different things depending on the command it
* receives
*/
public void setActionCommand(String aCommand) {
actionCommand = aCommand;
}
/**
* Returns the action command that is included in the event sent to
* action listeners.
*
* @return the string containing the "command" that is sent
* to action listeners.
*/
public String getActionCommand() {
return actionCommand;
}
private Action action;
private PropertyChangeListener actionPropertyChangeListener;
/**
* Sets the <code>Action</code> for the <code>ActionEvent</code> source.
* The new <code>Action</code> replaces any previously set
* <code>Action</code> but does not affect <code>ActionListeners</code>
* independently added with <code>addActionListener</code>.
* If the <code>Action</code> is already a registered
* <code>ActionListener</code> for the <code>ActionEvent</code> source,
* it is not re-registered.
* <p>
* Setting the <code>Action</code> results in immediately changing
* all the properties described in <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a>.
* Subsequently, the combobox's properties are automatically updated
* as the <code>Action</code>'s properties change.
* <p>
* This method uses three other methods to set
* and help track the <code>Action</code>'s property values.
* It uses the <code>configurePropertiesFromAction</code> method
* to immediately change the combobox's properties.
* To track changes in the <code>Action</code>'s property values,
* this method registers the <code>PropertyChangeListener</code>
* returned by <code>createActionPropertyChangeListener</code>. The
* default {@code PropertyChangeListener} invokes the
* {@code actionPropertyChanged} method when a property in the
* {@code Action} changes.
*
* @param a the <code>Action</code> for the <code>JComboBox</code>,
* or <code>null</code>.
* @since 1.3
* @see Action
* @see #getAction
* @see #configurePropertiesFromAction
* @see #createActionPropertyChangeListener
* @see #actionPropertyChanged
*/
@BeanProperty(visualUpdate = true, description
= "the Action instance connected with this ActionEvent source")
public void setAction(Action a) {
Action oldValue = getAction();
if (action==null || !action.equals(a)) {
action = a;
if (oldValue!=null) {
removeActionListener(oldValue);
oldValue.removePropertyChangeListener(actionPropertyChangeListener);
actionPropertyChangeListener = null;
}
configurePropertiesFromAction(action);
if (action!=null) {
// Don't add if it is already a listener
if (!isListener(ActionListener.class, action)) {
addActionListener(action);
}
// Reverse linkage:
actionPropertyChangeListener = createActionPropertyChangeListener(action);
action.addPropertyChangeListener(actionPropertyChangeListener);
}
firePropertyChange("action", oldValue, action);
}
}
private boolean isListener(Class<?> c, ActionListener a) {
boolean isListener = false;
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==c && listeners[i+1]==a) {
isListener=true;
}
}
return isListener;
}
/**
* Returns the currently set <code>Action</code> for this
* <code>ActionEvent</code> source, or <code>null</code> if no
* <code>Action</code> is set.
*
* @return the <code>Action</code> for this <code>ActionEvent</code>
* source; or <code>null</code>
* @since 1.3
* @see Action
* @see #setAction
*/
public Action getAction() {
return action;
}
/**
* Sets the properties on this combobox to match those in the specified
* <code>Action</code>. Refer to <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for more
* details as to which properties this sets.
*
* @param a the <code>Action</code> from which to get the properties,
* or <code>null</code>
* @since 1.3
* @see Action
* @see #setAction
*/
protected void configurePropertiesFromAction(Action a) {
AbstractAction.setEnabledFromAction(this, a);
AbstractAction.setToolTipTextFromAction(this, a);
setActionCommandFromAction(a);
}
/**
* Creates and returns a <code>PropertyChangeListener</code> that is
* responsible for listening for changes from the specified
* <code>Action</code> and updating the appropriate properties.
* <p>
* <b>Warning:</b> If you subclass this do not create an anonymous
* inner class. If you do the lifetime of the combobox will be tied to
* that of the <code>Action</code>.
*
* @param a the combobox's action
* @return the {@code PropertyChangeListener}
* @since 1.3
* @see Action
* @see #setAction
*/
protected PropertyChangeListener createActionPropertyChangeListener(Action a) {
return new ComboBoxActionPropertyChangeListener(this, a);
}
/**
* Updates the combobox's state in response to property changes in
* associated action. This method is invoked from the
* {@code PropertyChangeListener} returned from
* {@code createActionPropertyChangeListener}. Subclasses do not normally
* need to invoke this. Subclasses that support additional {@code Action}
* properties should override this and
* {@code configurePropertiesFromAction}.
* <p>
* Refer to the table at <a href="Action.html#buttonActions">
* Swing Components Supporting <code>Action</code></a> for a list of
* the properties this method sets.
*
* @param action the <code>Action</code> associated with this combobox
* @param propertyName the name of the property that changed
* @since 1.6
* @see Action
* @see #configurePropertiesFromAction
*/
protected void actionPropertyChanged(Action action, String propertyName) {
if (propertyName == Action.ACTION_COMMAND_KEY) {
setActionCommandFromAction(action);
} else if (propertyName == "enabled") {
AbstractAction.setEnabledFromAction(this, action);
} else if (Action.SHORT_DESCRIPTION == propertyName) {
AbstractAction.setToolTipTextFromAction(this, action);
}
}
private void setActionCommandFromAction(Action a) {
setActionCommand((a != null) ?
(String)a.getValue(Action.ACTION_COMMAND_KEY) :
null);
}
private static class ComboBoxActionPropertyChangeListener
extends ActionPropertyChangeListener<JComboBox<?>> {
ComboBoxActionPropertyChangeListener(JComboBox<?> b, Action a) {
super(b, a);
}
protected void actionPropertyChanged(JComboBox<?> cb,
Action action,
PropertyChangeEvent e) {
if (AbstractAction.shouldReconfigure(e)) {
cb.configurePropertiesFromAction(action);
} else {
cb.actionPropertyChanged(action, e.getPropertyName());
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type.
* @param e the event of interest
*
* @see EventListenerList
*/
protected void fireItemStateChanged(ItemEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for ( int i = listeners.length-2; i>=0; i-=2 ) {
if ( listeners[i]==ItemListener.class ) {
// Lazily create the event:
// if (changeEvent == null)
// changeEvent = new ChangeEvent(this);
((ItemListener)listeners[i+1]).itemStateChanged(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @see EventListenerList
*/
@SuppressWarnings("deprecation")
protected void fireActionEvent() {
if (!firingActionEvent) {
// Set flag to ensure that an infinite loop is not created
firingActionEvent = true;
ActionEvent e = null;
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
long mostRecentEventTime = EventQueue.getMostRecentEventTime();
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
try {
// Process the listeners last to first, notifying
// those that are interested in this event
for ( int i = listeners.length-2; i>=0; i-=2 ) {
if ( listeners[i]==ActionListener.class ) {
// Lazily create the event:
if ( e == null )
e = new ActionEvent(this,ActionEvent.ACTION_PERFORMED,
getActionCommand(),
mostRecentEventTime, modifiers);
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
} finally {
firingActionEvent = false;
}
}
}
/**
* This protected method is implementation specific. Do not access directly
* or override.
*/
protected void selectedItemChanged() {
if (selectedItemReminder != null ) {
fireItemStateChanged(new ItemEvent(this,ItemEvent.ITEM_STATE_CHANGED,
selectedItemReminder,
ItemEvent.DESELECTED));
}
// set the new selected item.
selectedItemReminder = dataModel.getSelectedItem();
if (selectedItemReminder != null ) {
fireItemStateChanged(new ItemEvent(this,ItemEvent.ITEM_STATE_CHANGED,
selectedItemReminder,
ItemEvent.SELECTED));
}
}
/**
* Returns an array containing the selected item.
* This method is implemented for compatibility with
* <code>ItemSelectable</code>.
*
* @return an array of <code>Objects</code> containing one
* element -- the selected item
*/
@BeanProperty(bound = false)
public Object[] getSelectedObjects() {
Object selectedObject = getSelectedItem();
if ( selectedObject == null )
return new Object[0];
else {
Object[] result = new Object[1];
result[0] = selectedObject;
return result;
}
}
/**
* This method is public as an implementation side effect.
* do not call or override.
*/
public void actionPerformed(ActionEvent e) {
setPopupVisible(false);
getModel().setSelectedItem(getEditor().getItem());
String oldCommand = getActionCommand();
setActionCommand("comboBoxEdited");
fireActionEvent();
setActionCommand(oldCommand);
}
/**
* This method is public as an implementation side effect.
* do not call or override.
*/
public void contentsChanged(ListDataEvent e) {
Object oldSelection = selectedItemReminder;
Object newSelection = dataModel.getSelectedItem();
if (oldSelection == null || !oldSelection.equals(newSelection)) {
selectedItemChanged();
if (!selectingItem) {
fireActionEvent();
}
}
}
/**
* This method is public as an implementation side effect.
* do not call or override.
*/
public void intervalAdded(ListDataEvent e) {
if (selectedItemReminder != dataModel.getSelectedItem()) {
selectedItemChanged();
}
}
/**
* This method is public as an implementation side effect.
* do not call or override.
*/
public void intervalRemoved(ListDataEvent e) {
contentsChanged(e);
}
/**
* Selects the list item that corresponds to the specified keyboard
* character and returns true, if there is an item corresponding
* to that character. Otherwise, returns false.
*
* @param keyChar a char, typically this is a keyboard key
* typed by the user
* @return {@code true} if there is an item corresponding to that character.
* Otherwise, returns {@code false}.
*/
public boolean selectWithKeyChar(char keyChar) {
int index;
if ( keySelectionManager == null )
keySelectionManager = createDefaultKeySelectionManager();
index = keySelectionManager.selectionForKey(keyChar,getModel());
if ( index != -1 ) {
setSelectedIndex(index);
return true;
}
else
return false;
}
/**
* Enables the combo box so that items can be selected. When the
* combo box is disabled, items cannot be selected and values
* cannot be typed into its field (if it is editable).
*
* @param b a boolean value, where true enables the component and
* false disables it
*/
@BeanProperty(preferred = true, description
= "The enabled state of the component.")
public void setEnabled(boolean b) {
super.setEnabled(b);
firePropertyChange( "enabled", !isEnabled(), isEnabled() );
}
/**
* Initializes the editor with the specified item.
*
* @param anEditor the <code>ComboBoxEditor</code> that displays
* the list item in the
* combo box field and allows it to be edited
* @param anItem the object to display and edit in the field
*/
public void configureEditor(ComboBoxEditor anEditor, Object anItem) {
anEditor.setItem(anItem);
}
/**
* Handles <code>KeyEvent</code>s, looking for the Tab key.
* If the Tab key is found, the popup window is closed.
*
* @param e the <code>KeyEvent</code> containing the keyboard
* key that was pressed
*/
public void processKeyEvent(KeyEvent e) {
if ( e.getKeyCode() == KeyEvent.VK_TAB ) {
hidePopup();
}
super.processKeyEvent(e);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (super.processKeyBinding(ks, e, condition, pressed)) {
return true;
}
if (!isEditable() || condition != WHEN_FOCUSED || getEditor() == null
|| !Boolean.TRUE.equals(getClientProperty("JComboBox.isTableCellEditor"))) {
return false;
}
Component editorComponent = getEditor().getEditorComponent();
if (editorComponent instanceof JComponent) {
JComponent component = (JComponent) editorComponent;
return component.processKeyBinding(ks, e, WHEN_FOCUSED, pressed);
}
return false;
}
/**
* Sets the object that translates a keyboard character into a list
* selection. Typically, the first selection with a matching first
* character becomes the selected item.
*
* @param aManager a key selection manager
*/
@BeanProperty(bound = false, expert = true, description
= "The objects that changes the selection when a key is pressed.")
public void setKeySelectionManager(KeySelectionManager aManager) {
keySelectionManager = aManager;
}
/**
* Returns the list's key-selection manager.
*
* @return the <code>KeySelectionManager</code> currently in use
*/
public KeySelectionManager getKeySelectionManager() {
return keySelectionManager;
}
/* Accessing the model */
/**
* Returns the number of items in the list.
*
* @return an integer equal to the number of items in the list
*/
@BeanProperty(bound = false)
public int getItemCount() {
return dataModel.getSize();
}
/**
* Returns the list item at the specified index. If <code>index</code>
* is out of range (less than zero or greater than or equal to size)
* it will return <code>null</code>.
*
* @param index an integer indicating the list position, where the first
* item starts at zero
* @return the item at that list position; or
* <code>null</code> if out of range
*/
public E getItemAt(int index) {
return dataModel.getElementAt(index);
}
/**
* Returns an instance of the default key-selection manager.
*
* @return the <code>KeySelectionManager</code> currently used by the list
* @see #setKeySelectionManager
*/
protected KeySelectionManager createDefaultKeySelectionManager() {
return new DefaultKeySelectionManager();
}
/**
* The interface that defines a <code>KeySelectionManager</code>.
* To qualify as a <code>KeySelectionManager</code>,
* the class needs to implement the method
* that identifies the list index given a character and the
* combo box data model.
*/
public interface KeySelectionManager {
/** Given <code>aKey</code> and the model, returns the row
* that should become selected. Return -1 if no match was
* found.
*
* @param aKey a char value, usually indicating a keyboard key that
* was pressed
* @param aModel a ComboBoxModel -- the component's data model, containing
* the list of selectable items
* @return an int equal to the selected row, where 0 is the
* first item and -1 is none.
*/
int selectionForKey(char aKey,ComboBoxModel<?> aModel);
}
class DefaultKeySelectionManager implements KeySelectionManager, Serializable {
public int selectionForKey(char aKey,ComboBoxModel<?> aModel) {
int i,c;
int currentSelection = -1;
Object selectedItem = aModel.getSelectedItem();
String v;
String pattern;
if ( selectedItem != null ) {
for ( i=0,c=aModel.getSize();i<c;i++ ) {
if ( selectedItem == aModel.getElementAt(i) ) {
currentSelection = i;
break;
}
}
}
pattern = ("" + aKey).toLowerCase();
aKey = pattern.charAt(0);
for ( i = ++currentSelection, c = aModel.getSize() ; i < c ; i++ ) {
Object elem = aModel.getElementAt(i);
if (elem != null && elem.toString() != null) {
v = elem.toString().toLowerCase();
if ( v.length() > 0 && v.charAt(0) == aKey )
return i;
}
}
for ( i = 0 ; i < currentSelection ; i ++ ) {
Object elem = aModel.getElementAt(i);
if (elem != null && elem.toString() != null) {
v = elem.toString().toLowerCase();
if ( v.length() > 0 && v.charAt(0) == aKey )
return i;
}
}
return -1;
}
}
/**
* See <code>readObject</code> and <code>writeObject</code> in
* <code>JComponent</code> for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/**
* Returns a string representation of this <code>JComboBox</code>.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JComboBox</code>
*/
protected String paramString() {
String selectedItemReminderString = (selectedItemReminder != null ?
selectedItemReminder.toString() :
"");
String isEditableString = (isEditable ? "true" : "false");
String lightWeightPopupEnabledString = (lightWeightPopupEnabled ?
"true" : "false");
return super.paramString() +
",isEditable=" + isEditableString +
",lightWeightPopupEnabled=" + lightWeightPopupEnabledString +
",maximumRowCount=" + maximumRowCount +
",selectedItemReminder=" + selectedItemReminderString;
}
///////////////////
// Accessibility support
///////////////////
/**
* Gets the AccessibleContext associated with this JComboBox.
* For combo boxes, the AccessibleContext takes the form of an
* AccessibleJComboBox.
* A new AccessibleJComboBox instance is created if necessary.
*
* @return an AccessibleJComboBox that serves as the
* AccessibleContext of this JComboBox
*/
@BeanProperty(bound = false)
public AccessibleContext getAccessibleContext() {
if ( accessibleContext == null ) {
accessibleContext = new AccessibleJComboBox();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* <code>JComboBox</code> class. It provides an implementation of the
* Java Accessibility API appropriate to Combo Box user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial") // Same-version serialization only
protected class AccessibleJComboBox extends AccessibleJComponent
implements AccessibleAction, AccessibleSelection {
private JList<?> popupList; // combo box popup list
private Accessible previousSelectedAccessible = null;
/**
* Returns an AccessibleJComboBox instance
* @since 1.4
*/
public AccessibleJComboBox() {
// set the combo box editor's accessible name and description
JComboBox.this.addPropertyChangeListener(new AccessibleJComboBoxPropertyChangeListener());
setEditorNameAndDescription();
// Get the popup list
Accessible a = getUI().getAccessibleChild(JComboBox.this, 0);
if (a instanceof javax.swing.plaf.basic.ComboPopup) {
// Listen for changes to the popup menu selection.
popupList = ((javax.swing.plaf.basic.ComboPopup)a).getList();
popupList.addListSelectionListener(
new AccessibleJComboBoxListSelectionListener());
}
// Listen for popup menu show/hide events
JComboBox.this.addPopupMenuListener(
new AccessibleJComboBoxPopupMenuListener());
}
/*
* JComboBox PropertyChangeListener
*/
private class AccessibleJComboBoxPropertyChangeListener
implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName() == "editor") {
// set the combo box editor's accessible name
// and description
setEditorNameAndDescription();
}
}
}
/*
* Sets the combo box editor's accessible name and descripton
*/
private void setEditorNameAndDescription() {
ComboBoxEditor editor = JComboBox.this.getEditor();
if (editor != null) {
Component comp = editor.getEditorComponent();
if (comp instanceof Accessible) {
AccessibleContext ac = comp.getAccessibleContext();
if (ac != null) { // may be null
ac.setAccessibleName(getAccessibleName());
ac.setAccessibleDescription(getAccessibleDescription());
}
}
}
}
/*
* Listener for combo box popup menu
* TIGER - 4669379 4894434
*/
private class AccessibleJComboBoxPopupMenuListener
implements PopupMenuListener {
/**
* This method is called before the popup menu becomes visible
*/
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// save the initial selection
if (popupList == null) {
return;
}
int selectedIndex = popupList.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
previousSelectedAccessible =
popupList.getAccessibleContext().getAccessibleChild(selectedIndex);
}
/**
* This method is called before the popup menu becomes invisible
* Note that a JPopupMenu can become invisible any time
*/
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// ignore
}
/**
* This method is called when the popup menu is canceled
*/
public void popupMenuCanceled(PopupMenuEvent e) {
// ignore
}
}
/*
* Handles changes to the popup list selection.
* TIGER - 4669379 4894434 4933143
*/
private class AccessibleJComboBoxListSelectionListener
implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (popupList == null) {
return;
}
// Get the selected popup list item.
int selectedIndex = popupList.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
Accessible selectedAccessible =
popupList.getAccessibleContext().getAccessibleChild(selectedIndex);
if (selectedAccessible == null) {
return;
}
// Fire a FOCUSED lost PropertyChangeEvent for the
// previously selected list item.
PropertyChangeEvent pce;
if (previousSelectedAccessible != null) {
pce = new PropertyChangeEvent(previousSelectedAccessible,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.FOCUSED, null);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
}
// Fire a FOCUSED gained PropertyChangeEvent for the
// currently selected list item.
pce = new PropertyChangeEvent(selectedAccessible,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.FOCUSED);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
// Fire the ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY event
// for the combo box.
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
previousSelectedAccessible, selectedAccessible);
// Save the previous selection.
previousSelectedAccessible = selectedAccessible;
}
}
/**
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
// Always delegate to the UI if it exists
if (ui != null) {
return ui.getAccessibleChildrenCount(JComboBox.this);
} else {
return super.getAccessibleChildrenCount();
}
}
/**
* Returns the nth Accessible child of the object.
* The child at index zero represents the popup.
* If the combo box is editable, the child at index one
* represents the editor.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
// Always delegate to the UI if it exists
if (ui != null) {
return ui.getAccessibleChild(JComboBox.this, i);
} else {
return super.getAccessibleChild(i);
}
}
/**
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.COMBO_BOX;
}
/**
* Gets the state set of this object. The AccessibleStateSet of
* an object is composed of a set of unique AccessibleStates.
* A change in the AccessibleStateSet of an object will cause a
* PropertyChangeEvent to be fired for the ACCESSIBLE_STATE_PROPERTY
* property.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleStateSet
* @see AccessibleState
* @see #addPropertyChangeListener
*
*/
public AccessibleStateSet getAccessibleStateSet() {
// TIGER - 4489748
AccessibleStateSet ass = super.getAccessibleStateSet();
if (ass == null) {
ass = new AccessibleStateSet();
}
if (JComboBox.this.isPopupVisible()) {
ass.add(AccessibleState.EXPANDED);
} else {
ass.add(AccessibleState.COLLAPSED);
}
return ass;
}
/**
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/**
* Return a description of the specified action of the object.
*
* @param i zero-based index of the actions
*/
public String getAccessibleActionDescription(int i) {
if (i == 0) {
return UIManager.getString("ComboBox.togglePopupText");
}
else {
return null;
}
}
/**
* Returns the number of Actions available in this object. The
* default behavior of a combo box is to have one action.
*
* @return 1, the number of Actions in this object
*/
public int getAccessibleActionCount() {
return 1;
}
/**
* Perform the specified Action on the object
*
* @param i zero-based index of actions
* @return true if the action was performed; else false.
*/
public boolean doAccessibleAction(int i) {
if (i == 0) {
setPopupVisible(!isPopupVisible());
return true;
}
else {
return false;
}
}
/**
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/**
* Returns the number of Accessible children currently selected.
* If no children are selected, the return value will be 0.
*
* @return the number of items currently selected.
* @since 1.3
*/
public int getAccessibleSelectionCount() {
Object o = JComboBox.this.getSelectedItem();
if (o != null) {
return 1;
} else {
return 0;
}
}
/**
* Returns an Accessible representing the specified selected child
* in the popup. If there isn't a selection, or there are
* fewer children selected than the integer passed in, the return
* value will be null.
* <p>Note that the index represents the i-th selected child, which
* is different from the i-th child.
*
* @param i the zero-based index of selected children
* @return the i-th selected child
* @see #getAccessibleSelectionCount
* @since 1.3
*/
public Accessible getAccessibleSelection(int i) {
// Get the popup
Accessible a =
JComboBox.this.getUI().getAccessibleChild(JComboBox.this, 0);
if (a != null &&
a instanceof javax.swing.plaf.basic.ComboPopup) {
// get the popup list
JList<?> list = ((javax.swing.plaf.basic.ComboPopup)a).getList();
// return the i-th selection in the popup list
AccessibleContext ac = list.getAccessibleContext();
if (ac != null) {
AccessibleSelection as = ac.getAccessibleSelection();
if (as != null) {
return as.getAccessibleSelection(i);
}
}
}
return null;
}
/**
* Determines if the current child of this object is selected.
*
* @return true if the current child of this object is selected;
* else false
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
* @since 1.3
*/
public boolean isAccessibleChildSelected(int i) {
return JComboBox.this.getSelectedIndex() == i;
}
/**
* Adds the specified Accessible child of the object to the object's
* selection. If the object supports multiple selections,
* the specified child is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified child is already selected, this method has no effect.
*
* @param i the zero-based index of the child
* @see AccessibleContext#getAccessibleChild
* @since 1.3
*/
public void addAccessibleSelection(int i) {
// TIGER - 4856195
clearAccessibleSelection();
JComboBox.this.setSelectedIndex(i);
}
/**
* Removes the specified child of the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of the child
* @see AccessibleContext#getAccessibleChild
* @since 1.3
*/
public void removeAccessibleSelection(int i) {
if (JComboBox.this.getSelectedIndex() == i) {
clearAccessibleSelection();
}
}
/**
* Clears the selection in the object, so that no children in the
* object are selected.
* @since 1.3
*/
public void clearAccessibleSelection() {
JComboBox.this.setSelectedIndex(-1);
}
/**
* Causes every child of the object to be selected
* if the object supports multiple selections.
* @since 1.3
*/
public void selectAllAccessibleSelection() {
// do nothing since multiple selection is not supported
}
// public Accessible getAccessibleAt(Point p) {
// Accessible a = getAccessibleChild(1);
// if ( a != null ) {
// return a; // the editor
// }
// else {
// return getAccessibleChild(0); // the list
// }
// }
private EditorAccessibleContext editorAccessibleContext = null;
private class AccessibleEditor implements Accessible {
public AccessibleContext getAccessibleContext() {
if (editorAccessibleContext == null) {
Component c = JComboBox.this.getEditor().getEditorComponent();
if (c instanceof Accessible) {
editorAccessibleContext =
new EditorAccessibleContext((Accessible)c);
}
}
return editorAccessibleContext;
}
}
/*
* Wrapper class for the AccessibleContext implemented by the
* combo box editor. Delegates all method calls except
* getAccessibleIndexInParent to the editor. The
* getAccessibleIndexInParent method returns the selected
* index in the combo box.
*/
private class EditorAccessibleContext extends AccessibleContext {
private AccessibleContext ac;
private EditorAccessibleContext() {
}
/*
* @param a the AccessibleContext implemented by the
* combo box editor
*/
EditorAccessibleContext(Accessible a) {
this.ac = a.getAccessibleContext();
}
/**
* Gets the accessibleName property of this object. The accessibleName
* property of an object is a localized String that designates the purpose
* of the object. For example, the accessibleName property of a label
* or button might be the text of the label or button itself. In the
* case of an object that doesn't display its name, the accessibleName
* should still be set. For example, in the case of a text field used
* to enter the name of a city, the accessibleName for the en_US locale
* could be 'city.'
*
* @return the localized name of the object; null if this
* object does not have a name
*
* @see #setAccessibleName
*/
public String getAccessibleName() {
return ac.getAccessibleName();
}
/**
* Sets the localized accessible name of this object. Changing the
* name will cause a PropertyChangeEvent to be fired for the
* ACCESSIBLE_NAME_PROPERTY property.
*
* @param s the new localized name of the object.
*
* @see #getAccessibleName
* @see #addPropertyChangeListener
*/
@BeanProperty(preferred = true, description
= "Sets the accessible name for the component.")
public void setAccessibleName(String s) {
ac.setAccessibleName(s);
}
/**
* Gets the accessibleDescription property of this object. The
* accessibleDescription property of this object is a short localized
* phrase describing the purpose of the object. For example, in the
* case of a 'Cancel' button, the accessibleDescription could be
* 'Ignore changes and close dialog box.'
*
* @return the localized description of the object; null if
* this object does not have a description
*
* @see #setAccessibleDescription
*/
public String getAccessibleDescription() {
return ac.getAccessibleDescription();
}
/**
* Sets the accessible description of this object. Changing the
* name will cause a PropertyChangeEvent to be fired for the
* ACCESSIBLE_DESCRIPTION_PROPERTY property.
*
* @param s the new localized description of the object
*
* @see #setAccessibleName
* @see #addPropertyChangeListener
*/
@BeanProperty(preferred = true, description
= "Sets the accessible description for the component.")
public void setAccessibleDescription(String s) {
ac.setAccessibleDescription(s);
}
/**
* Gets the role of this object. The role of the object is the generic
* purpose or use of the class of this object. For example, the role
* of a push button is AccessibleRole.PUSH_BUTTON. The roles in
* AccessibleRole are provided so component developers can pick from
* a set of predefined roles. This enables assistive technologies to
* provide a consistent interface to various tweaked subclasses of
* components (e.g., use AccessibleRole.PUSH_BUTTON for all components
* that act like a push button) as well as distinguish between subclasses
* that behave differently (e.g., AccessibleRole.CHECK_BOX for check boxes
* and AccessibleRole.RADIO_BUTTON for radio buttons).
* <p>Note that the AccessibleRole class is also extensible, so
* custom component developers can define their own AccessibleRole's
* if the set of predefined roles is inadequate.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return ac.getAccessibleRole();
}
/**
* Gets the state set of this object. The AccessibleStateSet of an object
* is composed of a set of unique AccessibleStates. A change in the
* AccessibleStateSet of an object will cause a PropertyChangeEvent to
* be fired for the ACCESSIBLE_STATE_PROPERTY property.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleStateSet
* @see AccessibleState
* @see #addPropertyChangeListener
*/
public AccessibleStateSet getAccessibleStateSet() {
return ac.getAccessibleStateSet();
}
/**
* Gets the Accessible parent of this object.
*
* @return the Accessible parent of this object; null if this
* object does not have an Accessible parent
*/
public Accessible getAccessibleParent() {
return ac.getAccessibleParent();
}
/**
* Sets the Accessible parent of this object. This is meant to be used
* only in the situations where the actual component's parent should
* not be treated as the component's accessible parent and is a method
* that should only be called by the parent of the accessible child.
*
* @param a - Accessible to be set as the parent
*/
public void setAccessibleParent(Accessible a) {
ac.setAccessibleParent(a);
}
/**
* Gets the 0-based index of this object in its accessible parent.
*
* @return the 0-based index of this object in its parent; -1 if this
* object does not have an accessible parent.
*
* @see #getAccessibleParent
* @see #getAccessibleChildrenCount
* @see #getAccessibleChild
*/
public int getAccessibleIndexInParent() {
return JComboBox.this.getSelectedIndex();
}
/**
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
return ac.getAccessibleChildrenCount();
}
/**
* Returns the specified Accessible child of the object. The Accessible
* children of an Accessible object are zero-based, so the first child
* of an Accessible child is at index 0, the second child is at index 1,
* and so on.
*
* @param i zero-based index of child
* @return the Accessible child of the object
* @see #getAccessibleChildrenCount
*/
public Accessible getAccessibleChild(int i) {
return ac.getAccessibleChild(i);
}
/**
* Gets the locale of the component. If the component does not have a
* locale, then the locale of its parent is returned.
*
* @return this component's locale. If this component does not have
* a locale, the locale of its parent is returned.
*
* @exception IllegalComponentStateException
* If the Component does not have its own locale and has not yet been
* added to a containment hierarchy such that the locale can be
* determined from the containing parent.
*/
public Locale getLocale() throws IllegalComponentStateException {
return ac.getLocale();
}
/**
* Adds a PropertyChangeListener to the listener list.
* The listener is registered for all Accessible properties and will
* be called when those properties change.
*
* @see #ACCESSIBLE_NAME_PROPERTY
* @see #ACCESSIBLE_DESCRIPTION_PROPERTY
* @see #ACCESSIBLE_STATE_PROPERTY
* @see #ACCESSIBLE_VALUE_PROPERTY
* @see #ACCESSIBLE_SELECTION_PROPERTY
* @see #ACCESSIBLE_TEXT_PROPERTY
* @see #ACCESSIBLE_VISIBLE_DATA_PROPERTY
*
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
ac.addPropertyChangeListener(listener);
}
/**
* Removes a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
ac.removePropertyChangeListener(listener);
}
/**
* Gets the AccessibleAction associated with this object that supports
* one or more actions.
*
* @return AccessibleAction if supported by object; else return null
* @see AccessibleAction
*/
public AccessibleAction getAccessibleAction() {
return ac.getAccessibleAction();
}
/**
* Gets the AccessibleComponent associated with this object that has a
* graphical representation.
*
* @return AccessibleComponent if supported by object; else return null
* @see AccessibleComponent
*/
public AccessibleComponent getAccessibleComponent() {
return ac.getAccessibleComponent();
}
/**
* Gets the AccessibleSelection associated with this object which allows its
* Accessible children to be selected.
*
* @return AccessibleSelection if supported by object; else return null
* @see AccessibleSelection
*/
public AccessibleSelection getAccessibleSelection() {
return ac.getAccessibleSelection();
}
/**
* Gets the AccessibleText associated with this object presenting
* text on the display.
*
* @return AccessibleText if supported by object; else return null
* @see AccessibleText
*/
public AccessibleText getAccessibleText() {
return ac.getAccessibleText();
}
/**
* Gets the AccessibleEditableText associated with this object
* presenting editable text on the display.
*
* @return AccessibleEditableText if supported by object; else return null
* @see AccessibleEditableText
*/
public AccessibleEditableText getAccessibleEditableText() {
return ac.getAccessibleEditableText();
}
/**
* Gets the AccessibleValue associated with this object that supports a
* Numerical value.
*
* @return AccessibleValue if supported by object; else return null
* @see AccessibleValue
*/
public AccessibleValue getAccessibleValue() {
return ac.getAccessibleValue();
}
/**
* Gets the AccessibleIcons associated with an object that has
* one or more associated icons
*
* @return an array of AccessibleIcon if supported by object;
* otherwise return null
* @see AccessibleIcon
*/
public AccessibleIcon [] getAccessibleIcon() {
return ac.getAccessibleIcon();
}
/**
* Gets the AccessibleRelationSet associated with an object
*
* @return an AccessibleRelationSet if supported by object;
* otherwise return null
* @see AccessibleRelationSet
*/
public AccessibleRelationSet getAccessibleRelationSet() {
return ac.getAccessibleRelationSet();
}
/**
* Gets the AccessibleTable associated with an object
*
* @return an AccessibleTable if supported by object;
* otherwise return null
* @see AccessibleTable
*/
public AccessibleTable getAccessibleTable() {
return ac.getAccessibleTable();
}
/**
* Support for reporting bound property changes. If oldValue and
* newValue are not equal and the PropertyChangeEvent listener list
* is not empty, then fire a PropertyChange event to each listener.
* In general, this is for use by the Accessible objects themselves
* and should not be called by an application program.
* @param propertyName The programmatic name of the property that
* was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @see java.beans.PropertyChangeSupport
* @see #addPropertyChangeListener
* @see #removePropertyChangeListener
* @see #ACCESSIBLE_NAME_PROPERTY
* @see #ACCESSIBLE_DESCRIPTION_PROPERTY
* @see #ACCESSIBLE_STATE_PROPERTY
* @see #ACCESSIBLE_VALUE_PROPERTY
* @see #ACCESSIBLE_SELECTION_PROPERTY
* @see #ACCESSIBLE_TEXT_PROPERTY
* @see #ACCESSIBLE_VISIBLE_DATA_PROPERTY
*/
public void firePropertyChange(String propertyName,
Object oldValue,
Object newValue) {
ac.firePropertyChange(propertyName, oldValue, newValue);
}
}
} // innerclass AccessibleJComboBox
}
| 37.251639 | 148 | 0.591931 |
c6cac62c8e8c502e71092390f4a362d5342745e4 | 5,027 | package com.ccreanga.webserver.ioutil;
import java.io.*;
import java.net.Socket;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Stack;
public class IOUtil {
/**
* RFC 7320 - 6.6. Tear-down
*
* @param socket
*/
public static void closeSocketPreventingReset(Socket socket) {
try {
socket.shutdownOutput();
InputStream in = socket.getInputStream();
int counter = 16000;//todo - try to find the best value
while ((in.read() != -1) && (counter-- > 0)) ;
socket.close();
} catch (IOException e) {/**ignore**/}
}
public static void closeSilent(Closeable closeable) {
try {
if (closeable != null)
closeable.close();
} catch (IOException e) {/**ignore**/}
}
public static String getIp(Socket socket) {
return socket.getRemoteSocketAddress().toString();
}
public static long copy(InputStream from, OutputStream to, int bufferSize) throws IOException {
return copy(from, to, -1, -1, bufferSize, null);
}
public static long copy(InputStream from, OutputStream to) throws IOException {
return copy(from, to, -1, -1);
}
public static long copy(InputStream from, OutputStream to, long inputOffset, long length) throws IOException {
return copy(from, to, inputOffset, length, 8 * 1024, null);
}
public static long copy(InputStream from, OutputStream to, long inputOffset, long length, int bufferSize, MessageDigest md) throws IOException {
byte[] buffer = new byte[bufferSize];
if (inputOffset > 0) {
long skipped = from.skip(inputOffset);
if (skipped != inputOffset) {
throw new EOFException("Bytes to skip: " + inputOffset + " actual: " + skipped);
}
}
if (length == 0) {
return 0;
}
final int bufferLength = buffer.length;
int bytesToRead = bufferLength;
if (length > 0 && length < bufferLength) {
bytesToRead = (int) length;
}
int read;
long totalRead = 0;
while (bytesToRead > 0 && -1 != (read = from.read(buffer, 0, bytesToRead))) {
to.write(buffer, 0, read);
if (md != null)
md.update(buffer, 0, read);
totalRead += read;
if (length > 0) {
bytesToRead = (int) Math.min(length - totalRead, bufferLength);
}
}
return totalRead;
}
public static LocalDateTime modifiedDateAsUTC(File file) {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(file.lastModified()), ZoneId.of("UTC")).toLocalDateTime();
}
public static String extractParentResource(File file, File root) {
File traverse = file.getParentFile();
StringBuilder sb = new StringBuilder();
sb.append("/");
Stack<String> stack = new Stack<>();
while (!traverse.equals(root)) {
stack.push(traverse.getName());
traverse = traverse.getParentFile();
}
while (!stack.empty()) {
String next = stack.pop();
sb.append(next).append("/");
}
return sb.toString();
}
public static String readToken(InputStream in, int delim,
String enc, int maxLength) throws IOException {
int buflen = maxLength < 256 ? maxLength : 256; // start with less
byte[] buf = new byte[buflen];
int count = 0;
int c;
while ((c = in.read()) != -1 && c != delim) {
if (count == buflen) { // expand buffer
if (count == maxLength)
throw new LineTooLongException("token too large (" + count + ")");
buflen = maxLength < 2 * buflen ? maxLength : 2 * buflen;
byte[] expanded = new byte[buflen];
System.arraycopy(buf, 0, expanded, 0, count);
buf = expanded;
}
buf[count++] = (byte) c;
}
if (c == -1 && delim != -1)
throw new EOFException("unexpected end of stream");
return new String(buf, 0, count, enc);
}
public static String readLine(InputStream in) throws IOException {
return readLine(in, Integer.MAX_VALUE);
}
public static String readLine(InputStream in, int maxLength) throws IOException {
String s = readToken(in, '\n', "ISO8859_1", maxLength);
return s.length() > 0 && s.charAt(s.length() - 1) == '\r' ?
s.substring(0, s.length() - 1) :
s;
}
public static String getFileExtension(String fullName) {
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
}
| 34.197279 | 148 | 0.565745 |
f044674d23a8c015047a6870b652aa46152eec36 | 553 | package de.fraunhofer.iosb.ilt.fisabackend.service.mapper;
import de.fraunhofer.iosb.ilt.fisabackend.service.tree.FisaTreeNode;
/**
* A mapper applies a defined action on a {@link FisaTreeNode}.
* The action is defined by implementations of this interface.
*/
public interface Mapper extends MappingResolver {
/**
* Applies an action on the tree node.
*
* @param treeNode the node to apply on.
* @param arguments optional arguments that can be applied.
*/
void apply(FisaTreeNode treeNode, String... arguments);
}
| 29.105263 | 68 | 0.717902 |
6f6a325f66555ad0ab9d76da616d9b4c7e305f8b | 1,252 | package net.java.pathfinder.health;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.health.Health;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
/**
*
* @author Ondrej Mihalyi
*/
@Health
@ApplicationScoped
public class ServiceActiveHealthCheck implements HealthCheck {
@Inject
@ConfigProperty(name = "ServiceActiveHealthCheck.timeToBecomeInactiveInSeconds", defaultValue = "10")
int limitForInactivityInSeconds;
@Inject
LastResponseFilter lastResponseFilter;
@Override
public HealthCheckResponse call() {
long inactiveForMillis = System.currentTimeMillis() - lastResponseFilter.getLastResponseCompletedTimeMillis();
boolean isUp = (inactiveForMillis <= limitForInactivityInSeconds * 1000);
return HealthCheckResponse.named("inactivity")
.withData("last-response-timestamp", lastResponseFilter.getLastResponseCompletedTimeMillis())
.withData("last-active-before-seconds", inactiveForMillis / 1000)
.state(isUp)
.build();
}
}
| 34.777778 | 119 | 0.742812 |
1e7243451ef57aae20d334c6be7a41ac3fe4fac0 | 1,182 | import java.util.HashMap;
import java.util.Scanner;
public class A805 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long a = input.nextLong();
long b = input.nextLong();
input.close();
int[] primes = { 2, 3, 5, 7, 11 };
HashMap<Integer, Integer> lst = new HashMap<Integer, Integer>();
if (b - a >= 3) {
System.out.println(2);
}else if(b == a){
System.out.println(a);
}
else {
for (long i = a; i <= b; i++) {
for (int j = 0; j < 5; j++) {
if (i % primes[j] == 0) {
if (lst.containsKey(primes[j])) {
lst.put(primes[j], lst.get(primes[j]) + 1);
} else {
lst.put(primes[j], 1);
}
}
}
}
int max = 2;
for (int x : lst.keySet()) {
if (lst.get(max) < lst.get(x)) {
max = x;
}
}
System.out.println(max);
}
}
} | 31.105263 | 72 | 0.374788 |
36a1610593a19c6c947f6e3c47cbb40d89d4169f | 2,575 | package com.example.DemoGraphQL;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = DemoGraphQlApplicationTests.Config.class)
@EnableAutoConfiguration
@EnableConfigurationProperties(MyProperties.class)
public class DemoGraphQlApplicationTests {
@Autowired
MyProperties properties;
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DataSource dataSource;
static class Config {}
@Autowired
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {
assertNotNull(restTemplate);
assertNotNull(jdbcTemplate);
assertNotNull(dataSource);
}
@Test
public void h2Connection() throws SQLException {
try (Connection conn = dataSource.getConnection()) { //DriverManager.getConnection("jdbc:h2:~/test", "sa", "")) {
assertNotNull(conn);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT 1");
assertThat(rs).isNotNull();
}
}
@Test
public void h2Version() {
String actualVersion = jdbcTemplate.queryForObject("SELECT `VALUE` FROM INFORMATION_SCHEMA.SETTINGS WHERE NAME = 'CREATE_BUILD'", String.class);
String expectedVersion = properties.getH2()
.getVersion();
assertThat(expectedVersion).endsWith("." + actualVersion); // the db must be created with the same h2 version in our build
}
@Test
public void artifactProperty() throws IOException {
assertThat(properties.getArtifactId()).isEqualTo("DemoGraphQL");
}
}
| 35.273973 | 152 | 0.741748 |
5e4aca0ca5e62c5471b3b95eaf0fad36fb971b3d | 1,289 | package space.zhupeng.easycamera;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by zhupeng on 2017/9/12.
*/
public class CameraInvocationHandler implements InvocationHandler {
private CameraApi mDelegate;
private CheckPermissionListener mCheckListener;
private CameraInvocationHandler(CheckPermissionListener listener) {
this.mCheckListener = listener;
}
public static CameraInvocationHandler of(CheckPermissionListener listener) {
return new CameraInvocationHandler(listener);
}
/**
* 绑定委托对象并返回一个代理类
*
* @param delegate
* @return
*/
public CameraApi bind(CameraApi delegate) {
this.mDelegate = delegate;
return (CameraApi) Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
boolean isGranted = mCheckListener.isPermissionGranted();
if (proxy instanceof CameraApi) {
if (!isGranted) {
// ((CameraApi) proxy).requestPermission();
}
}
return method.invoke(mDelegate, args);
}
}
| 28.021739 | 131 | 0.683476 |
6ae16c7f073e7caed7e840f24eaf529fe1faa95a | 1,978 | package com.jungdam.comment.dto.bundle;
import com.jungdam.comment.domain.vo.Content;
import com.jungdam.comment.dto.request.CreateCommentRequest;
public class CreateCommentBundle {
private final Long memberId;
private final Long albumId;
private final Long diaryId;
private final Content content;
public CreateCommentBundle(Long memberId, Long albumId, Long diaryId,
CreateCommentRequest request) {
this.memberId = memberId;
this.albumId = albumId;
this.diaryId = diaryId;
this.content = new Content(request.getCommentContent());
}
public static CreateCommentBundleBuilder builder() {
return new CreateCommentBundleBuilder();
}
public Long getMemberId() {
return memberId;
}
public Long getAlbumId() {
return albumId;
}
public Long getDiaryId() {
return diaryId;
}
public Content getContent() {
return content;
}
public static class CreateCommentBundleBuilder {
private Long memberId;
private Long albumId;
private Long diaryId;
private CreateCommentRequest request;
private CreateCommentBundleBuilder() {
}
public CreateCommentBundleBuilder memberId(final Long memberId) {
this.memberId = memberId;
return this;
}
public CreateCommentBundleBuilder albumId(final Long albumId) {
this.albumId = albumId;
return this;
}
public CreateCommentBundleBuilder diaryId(final Long diaryId) {
this.diaryId = diaryId;
return this;
}
public CreateCommentBundleBuilder request(final CreateCommentRequest request) {
this.request = request;
return this;
}
public CreateCommentBundle build() {
return new CreateCommentBundle(this.memberId, this.albumId, this.diaryId, this.request);
}
}
} | 26.026316 | 100 | 0.644085 |
b9aef60ce55a9b020d76055974f1c4ba82a4454e | 639 | package com.tapu.urlshortenerapp.service;
import com.tapu.urlshortenerapp.dto.UrlDTO;
import com.tapu.urlshortenerapp.dto.UrlResponseDTO;
import com.tapu.urlshortenerapp.model.Url;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface UrlService {
Url generateShortLink(UrlDTO urlDto, Long id);
Url getEncodedUrl(String url);
Url saveUrl(Url urlToRet);
List<String> findShortLinkByUserId(Long userId);
List<String> findShortLinkByUserIdAndId(Long userId, Long urlId);
void deleteById(Long userId, Long urlId);
UrlResponseDTO setResponseDetails(Url url);
}
| 21.3 | 69 | 0.776213 |
9e642c358253702aa76c46ae283285ba526540f4 | 344 | package ox.softeng.metadatacatalogue.restapi.services;
import ox.softeng.metadatacatalogue.domain.core.Form;
import javax.ws.rs.Path;
import ox.softeng.metadatacatalogue.domain.core.CatalogueItem;
@Path("/form")
public class FormService extends DataModelService {
public static Class<? extends CatalogueItem> type = Form.class;
}
| 19.111111 | 64 | 0.787791 |
6e73124d6339067f24313ca4b6c72236d5677428 | 719 | package com.design.service.impl;
import java.util.List;
import com.design.dao.CourseDAO;
import com.design.pojo.Course;
import com.design.service.CourseManager;
public class CourseManagerImpl implements CourseManager {
private CourseDAO courseDAO;
public CourseDAO getCourseDAO() {
return courseDAO;
}
public void setCourseDAO(CourseDAO courseDAO) {
this.courseDAO = courseDAO;
}
public void delete(String id) {
courseDAO.delete(id);
}
public Course getCourse(String name) {
return courseDAO.getCourse(name);
}
public List getCourses() {
return courseDAO.getCourses();
}
public void save(Course c) {
courseDAO.save(c);
}
public void upDate(Course c) {
courseDAO.upDate(c);
}
}
| 17.119048 | 57 | 0.738526 |
78c7857352f6fab93d0f44fb15fe073bb2c47dc1 | 1,821 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.normalization.java.impl;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.SortedSet;
public class AnnotationMember extends Member implements Comparable<AnnotationMember> {
private final SortedSet<AnnotationValue<?>> values = Sets.newTreeSet();
private final boolean visible;
public AnnotationMember(String name, boolean visible) {
super(name);
this.visible = visible;
}
public SortedSet<AnnotationValue<?>> getValues() {
return ImmutableSortedSet.copyOf(values);
}
public void addValue(AnnotationValue<?> value) {
values.add(value);
}
public void addValues(Collection<AnnotationValue<?>> values) {
this.values.addAll(values);
}
public boolean isVisible() {
return visible;
}
protected ComparisonChain compare(AnnotationMember o) {
return super.compare(o)
.compareFalseFirst(visible, o.visible);
}
@Override
public int compareTo(AnnotationMember o) {
return compare(o).result();
}
}
| 29.370968 | 86 | 0.711148 |
4b5b13c59a6da7a510be4d0bc7ff27565ac6e58f | 23,905 | /**********************************************************************
*
* Prolog+CG : Prolog with conceptual graphs
*
* Copyright (C) 2000-2005 Adil Kabbaj
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*
* Website
* =======
*
* Prolog+CG has a website here:
*
* http://prologpluscg.sourceforge.net/
*
*
* Contact
* =======
*
* Please DO NOT send email to Prof. Kabbaj. Instead, all
* correspondence regarding Prolog+CG should be sent to the current
* maintainter:
*
* Ulrik Petersen <ulrikp{t-a}users{dot}sourceforge{|dot|}net
*
* (Email obfuscated to foil spammers).
*
*
* NO SUPPORT
* ==========
*
* Note that NEITHER Prof. KABBAJ NOR ULRIK PETERSEN WILL GIVE
* SUPPORT! No support is available.
*
* If you need help in using Prolog+CG, please check out the resources
* available at:
*
* http://prologpluscg.sourceforge.net/docs.html
*
* That page points to ample resources for learning Prolog+CG.
*
*
* Bugreports
* ==========
*
* Notwithstanding the lack of support, the maintainer will gladly
* receive bugreports and bugfixes. Please feel free to send such
* bulletins to the address given above.
*
*
*/
package PrologPlusCG.prolog;
import java.util.*;
import PrologPlusCG.cg.CG;
import PrologPlusCG.cg.Concept;
import PrologPlusCG.cg.Relation;
public class Printer implements DataTypes {
int indVar = 0;
private String printedString = "";
public String alternatePrintString = "";
private PPCGEnv env;
public Printer(PPCGEnv myenv) {
env = myenv;
}
void flush() {
String printedString = getPrintedString();
env.io.appendToConsole(printedString);
clearPrintedString();
}
/** afin d'eviter l'impression + fois d'une meme relation, on
maintient une liste des relations dont on prevoit leur
impression. Si on les rencontres par apres lors de l'impression
imbriquee, ses relations ne seront pas considerees. Par ailleurs
et lors de l'impression d'un concept C, si une de ses relations
est a ignorer car son impression est deja prevue par rapport a un
autre concept, alors C sera reimprime et il faut donc lui associer
un referent s'il n'en a pas ***/
public void printCG(CG aCG, int level, Vector<Concept> vctConcsVisite,
Vector<Relation> vctImprPrevuRels) {
// 1. Chercher s'il y a un concept qui n'a pas d'entrees
boolean bFound = false;
Concept conc = null;
for (int listIndex1 = 0;
listIndex1 < aCG.m_vctConcepts.size() && !bFound;
++listIndex1) {
conc = aCG.m_vctConcepts.get(listIndex1);
if (conc.m_vctIncomingRelations.isEmpty()) {
bFound = true;
}
}
// 2. S'il n'y en a pas, on commence avec n'importe quel concept; le premier
if (bFound) {
printCGRelations(conc, aCG, level, vctConcsVisite, vctImprPrevuRels);
} else {
printCGRelations((Concept) aCG.m_vctConcepts.get(0), aCG,
level, vctConcsVisite, vctImprPrevuRels);
}
aCG.removeSpecialIdent();
}
public void printCGRelations(Concept conc, CG aCG, int level,
Vector<Concept> vctConcsVisite, Vector<Relation> vctImprPrevuRels) {
vctConcsVisite.addElement(conc);
int numberOfChars = printConcept(conc, true, level, vctImprPrevuRels);
if ((conc.m_vctIncomingRelations.size() + conc.m_vctOutgoingRelations.size()) > 1) {
printToConsole(" -\n");
copyRelations(conc.m_vctOutgoingRelations, vctImprPrevuRels); // On prevoit l'impression de ses relations
copyRelations(conc.m_vctIncomingRelations, vctImprPrevuRels); // ... les entrs/sorts
// true == relSorts
printRelations(conc.m_vctOutgoingRelations,
true, aCG, level, numberOfChars,
vctConcsVisite, vctImprPrevuRels);
if ((conc.m_vctOutgoingRelations.size() > 0) && (conc.m_vctIncomingRelations.size() > 0)) {
printToConsole(",\n");
}
// false == relEntrs
printRelations(conc.m_vctIncomingRelations, false,
aCG, level, numberOfChars,
vctConcsVisite, vctImprPrevuRels);
} else if (!conc.m_vctIncomingRelations.isEmpty()) {
printRelation(conc.m_vctIncomingRelations.get(0),
false, aCG,
level, vctConcsVisite, vctImprPrevuRels);
} else if (!conc.m_vctOutgoingRelations.isEmpty()) {
printRelation(conc.m_vctOutgoingRelations.get(0),
true, aCG,
level, vctConcsVisite, vctImprPrevuRels);
}
}
public void copyRelations(Vector<Relation> vctRels, Vector<Relation> vctImprPrevuRels) {
if (vctRels.isEmpty()) {
return;
}
Relation rel;
for (int listIndex1 = 0;
listIndex1 < vctRels.size();
listIndex1++) {
rel = vctRels.get(listIndex1);
vctImprPrevuRels.addElement(rel);
}
}
// ImprimeRels recoit la liste des relations a imprimer, les relations a ignorer
// ont ete deja enleve de la liste ...
public void printRelations(Vector<Relation> vctRels,
boolean Direction,
CG aCG, int level, int Decalage, Vector<Concept> vctConcsVisite,
Vector<Relation> vctImprPrevuRels) {
if (vctRels.isEmpty()) {
return;
}
Relation rel = vctRels.get(0);
printSpaces(Decalage);
printRelation(rel, Direction, aCG, level, vctConcsVisite, vctImprPrevuRels);
for (int listIndex = 0;
listIndex < vctRels.size();
++listIndex) {
rel = vctRels.get(listIndex);
printToConsole(",\n");
printSpaces(Decalage);
printRelation(rel, Direction, aCG, level, vctConcsVisite,
vctImprPrevuRels);
}
}
public void printRelation(Relation rel, boolean estRelSort, CG unGC, int niv,
Vector<Concept> vctConcsVisite, Vector<Relation> vctImprPrevuRels) {
String DelOuv = null;
String DelFerm = null;
Concept conc = null;
if (estRelSort) {
DelOuv = "-";
DelFerm = "->";
conc = rel.m_concDestination;
} else {
DelOuv = "<-";
DelFerm = "-";
conc = rel.m_concSource;
}
printToConsole(DelOuv);
printPrologData(rel.m_pdRelationName, niv);
printToConsole(DelFerm);
if (vctConcsVisite.contains(conc)) {
printConcept(conc, false, niv, vctImprPrevuRels);
} else {
printCGConcept(rel, estRelSort, conc, unGC, niv, vctConcsVisite,
vctImprPrevuRels);
}
}
public void printCGConcept(Relation rel, boolean estRelSort, Concept conc,
CG unGC, int niv, Vector<Concept> vctConcsVisite, Vector<Relation> vctImprPrevuRels) {
vctConcsVisite.addElement(conc);
if (!estRelSort) { // rel est donc une relation en sortie pour conc
// On enleve rel de m_vctOutgoingRelations (on le remettra apres)
conc.m_vctOutgoingRelations.removeElement(rel);
} else {
conc.m_vctIncomingRelations.removeElement(rel);
}
// true == impression complete; tous les champs
int nbreCars = printConcept(conc, true, niv, vctImprPrevuRels);
Vector<Relation> vctRelEntrsAImpr = new Vector<Relation>();
relationsToPrint(conc.m_vctIncomingRelations, vctRelEntrsAImpr, vctImprPrevuRels);
Vector<Relation> vctRelSortsAImpr = new Vector<Relation>();
relationsToPrint(conc.m_vctOutgoingRelations, vctRelSortsAImpr, vctImprPrevuRels);
if ((vctRelEntrsAImpr.size() + vctRelSortsAImpr.size()) > 1) {
printToConsole(" -\n");
printRelations(vctRelSortsAImpr, true, unGC, niv, nbreCars,
vctConcsVisite, vctImprPrevuRels);
if ((vctRelSortsAImpr.size() > 0) && (vctRelEntrsAImpr.size() > 0)) {
printToConsole(",\n");
}
printRelations(vctRelEntrsAImpr, false, unGC, niv, nbreCars,
vctConcsVisite, vctImprPrevuRels);
printToConsole(";");
} else if (!vctRelEntrsAImpr.isEmpty()) {
printRelation(vctRelEntrsAImpr.get(0), false, unGC,
niv, vctConcsVisite, vctImprPrevuRels);
} else if (!vctRelSortsAImpr.isEmpty()) {
printRelation(vctRelSortsAImpr.get(0), true, unGC,
niv, vctConcsVisite, vctImprPrevuRels);
}
vctRelEntrsAImpr.clear();
vctRelSortsAImpr.clear();
if (!estRelSort) {
conc.m_vctOutgoingRelations.addElement(rel); // On remet rel dans m_vctOutgoingRelations
} else {
conc.m_vctIncomingRelations.addElement(rel);
}
}
public void relationsToPrint(Vector<Relation> vctInitRels, Vector<Relation> vctRelsAImpr,
Vector<Relation> vctImprPrevuRels) {
Relation rel;
for (int listIndex1 = 0;
listIndex1 < vctInitRels.size();
++listIndex1) {
rel = vctInitRels.get(listIndex1);
if (!vctImprPrevuRels.contains(rel)) {
vctRelsAImpr.addElement(rel);
vctImprPrevuRels.addElement(rel);
}
}
}
String createReferenceSpecification() {
indVar++;
return "*" + String.valueOf(indVar);
}
public int printConcept(Concept conc, boolean premiereFois, int niv,
Vector<Relation> vctImprPrevuRels) {
if (conc.m_pdType == null) {
printPrologData(conc.m_pdReferent, niv);
} else {
printToConsole("[");
printPrologData(conc.m_pdType, niv);
boolean trouve = false;
if (premiereFois && (conc.m_pdReferent == null) &&
(vctImprPrevuRels != null)) {
Relation rel;
for (int listIndex1 = 0;
listIndex1 < conc.m_vctIncomingRelations.size() && !trouve;
++listIndex1) {
rel = conc.m_vctIncomingRelations.get(listIndex1);
if (vctImprPrevuRels.contains(rel)) {
trouve = true;
}
}
for (int listIndex2 = 0;
listIndex2 < conc.m_vctOutgoingRelations.size() && !trouve;
++listIndex2) {
rel = conc.m_vctOutgoingRelations.get(listIndex2);
if (vctImprPrevuRels.contains(rel)) {
trouve = true;
}
}
if (trouve) { // Creer un referent pour ce concept
conc.m_pdReferent = new PrologData(uIdentSpecial, createReferenceSpecification());
}
}
if (conc.m_pdReferent != null) {
printToConsole(" : ");
printPrologData(conc.m_pdReferent, niv);
}
if (premiereFois && (conc.m_pdValue != null)) {
printToConsole(" = ");
printPrologData(conc.m_pdValue, niv);
}
printToConsole("]");
}
return numberOfCharsOnCurrentLine(); // On determine le nbre de car de la ligne courante
}
void printSpaces(int nbreBlancs) {
StringBuffer s = new StringBuffer("");
for (int i = 0; i <= nbreBlancs; i++)
s.append(' ');
printToConsole(s.toString());
}
/*********
Universal > Person, Action.
Person > Man, Woman.
Action > Eat, Work.
[Man]-agnt->[Work].
[Woman]-agnt->[Work].
******************************/
int numberOfCharsOnCurrentLine() {
String myString;
if (env.bWriteToDebugTree || env.bWriteToToolTip) {
System.out.println("UP100: env.bWriteToDebugTree || env.bWriteToToolTip");
myString = alternatePrintString;
} else {
myString = printedString;
}
int nLastIndexOfNewline = myString.lastIndexOf('\n');
if (nLastIndexOfNewline == -1) {
return myString.length();
} else {
return myString.length() - nLastIndexOfNewline;
}
}
public void printTerm(PrologTerm pTerme) {
printTerm(pTerme, -1);
}
public void printTerm(PrologTerm pTerm, int level) {
printPrologData((PrologData) pTerm.get(0), level);
int IndDernier = pTerm.size() - 1;
if (IndDernier >= 1) {
printToConsole("(");
printPrologData((PrologData) pTerm.elementAt(1), level);
for (int i = 2; i <= IndDernier; i++) {
printToConsole(", ");
printPrologData((PrologData) pTerm.elementAt(i), level);
}
printToConsole(")");
}
}
public void printSet(PrologList pLstPrlg, int niv) {
printToConsole("{");
int nbreElems = pLstPrlg.size();
int indElemCour = 0;
try {
printPrologData((PrologData) pLstPrlg.get(indElemCour), niv);
indElemCour++;
} catch (ArrayIndexOutOfBoundsException aiobex) {
// This could possibly happen
}
while (indElemCour < nbreElems) {
printToConsole(", ");
printPrologData((PrologData) pLstPrlg.get(indElemCour), niv);
indElemCour++;
}
printToConsole("}");
}
public void printList(PrologList pLstPrlg, int niv) {
printToConsole("(");
int nbreElems = pLstPrlg.size();
//int indLstElem = pLstPrlg.size() - 1;
int indElemCour = 0;
if (nbreElems > 0) {
printPrologData((PrologData) pLstPrlg.elementAt(indElemCour), niv);
indElemCour++;
}
while (indElemCour < nbreElems) {
//ImprimeDon((PrologData) pLstPrlg.elementAt(indElemCour), niv);
//indElemCour++;
//if (indElemCour < nbreElems) {
if ((((PrologData) pLstPrlg.elementAt(indElemCour)).typeOfData == uVarList) &&
(niv != -1)) {
PrologDataIndexPair contr = env.unification.valueFromUnifStack((PrologData) pLstPrlg.elementAt(
indElemCour), niv);
if (contr.pData == null) {
printToConsole("|FREE");
indElemCour = nbreElems;
} else {
// EcrireConsole(", ");
pLstPrlg = (PrologList) contr.pData.data;
nbreElems = pLstPrlg.size();
indElemCour = 0;
niv = contr.index;
if (nbreElems > 0) {
printToConsole(", ");
printPrologData((PrologData) pLstPrlg.elementAt(indElemCour),
niv);
indElemCour++;
}
}
contr = null;
} else {
if (((PrologData) pLstPrlg.elementAt(indElemCour)).typeOfData == uVarList) {
printToConsole("|");
} else {
printToConsole(", ");
}
printPrologData((PrologData) pLstPrlg.elementAt(indElemCour), niv);
indElemCour++;
}
// };
}
printToConsole(")");
}
public void printPrologData(PrologData pDon, int niv) {
printPrologData(pDon, niv, false);
}
// Version that strips '"' from uString if last parameter is true.
// Note that this does work recursively for variables and variable
// lists, but not for terms, lists, CGs, concepts, or any other
// type. Thus when pDon is a variable containing a string, the
// string will have its '"' stripped if last parameter is true.
// However, if pDon is a term or a list, or any other
// non-variable, non-string type, the last parameter is not
// carried over recursively.
public void printPrologData(PrologData pDon, int niv, boolean uChaineShouldBeStrippedOfQuotations) {
if (pDon == null) {
printToConsole("FREE"); // le cas ou la variable est free; aucune donnee ne lui est associee
} else {
switch (pDon.typeOfData) {
case uNumber:
printToConsole(((Number) pDon.data).toString());
break;
case uBoolean:
printToConsole(((Boolean) pDon.data).toString());
break;
case uIdentSpecial:
case uIdentifier:
case uPeriod:
case uComma:
case uSemicolon:
case uExclamationMark:
case uQuestionMark:
printToConsole((String) pDon.data);
break;
case uString:
if (uChaineShouldBeStrippedOfQuotations) {
// Get string from PrologData
String s = ((String) pDon.data);
// Remove beginning and ending '"' and write the result
if (s.length() >= 2
&& s.charAt(0) == '"' && s.charAt(s.length()-1) == '"') {
printToConsole(s.substring(1, s.length()-1));
} else {
printToConsole(s);
}
// Delete s;
s = null;
} else{
printToConsole((String) pDon.data);
}
//if (niv == -1) EcrireConsole('"' + ((String) pDon.Don) + '"'); // Les " sont deja dans la chaine, on aurait une double
//else EcrireConsole((String) pDon.Don);
break;
case uVariable:
case uVarList:
if (niv == -1) {
printToConsole((String) pDon.data);
/*
} else if (env.bWriteToDebugTree) {
String s = (String) pDon.data;
printToConsole(s + "/" + niv);
s = null;
*/
} else {
PrologDataIndexPair contr = env.unification.valueFromUnifStack(pDon, niv);
if (contr.pData != null) {
printPrologData(contr.pData, contr.index, uChaineShouldBeStrippedOfQuotations);
} else {
printToConsole((String) pDon.data);
}
contr = null;
}
break;
case uTerm:
printTerm((PrologTerm) pDon.data, niv);
break;
case uConcept:
printConcept((Concept) pDon.data, true, niv, null);
break;
case uCG: {
Vector<Concept> vctConcsVisite = new Vector<Concept>();
Vector<Relation> vctImprPrevuRels = new Vector<Relation>();
printCG((CG) pDon.data, niv, vctConcsVisite, vctImprPrevuRels);
vctConcsVisite.clear();
vctConcsVisite = null;
vctImprPrevuRels.clear();
vctImprPrevuRels = null;
}
break;
case uList:
printList((PrologList) pDon.data, niv);
break;
case uSet:
printSet((PrologList) pDon.data, niv);
break;
case uObject:
printToConsole(pDon.data.toString());
}
}
}
public void printPrologProgram() {
Set<String> keys = env.program.keySet();
for (String key : keys) {
RuleVector value = env.program.get(key);
printRules(value, key);
printToConsole("\n");
}
}
public void printRules(RuleVector pRegles, String cle) {
for (int listIndex = 0;
listIndex < pRegles.size();
++listIndex) {
printRule(pRegles.get(listIndex), cle);
}
}
public void printRule(PrologRule pRegle, String cle) {
if (cle.startsWith(env.compile.valSysGEN)) {
PrologTerm unTrmTmp = (PrologTerm) pRegle.getAt(0).getAt(1).data;
printGoal(unTrmTmp);
} else {
printGoal((PrologTerm) pRegle.get(0));
}
if (pRegle.size() > 1) {
if (cle.equals(env.compile.valSysSP)) {
printToConsole(" > ");
printTail(pRegle);
} else if (cle.equals(env.compile.valSysINST)) {
printToConsole(" = ");
printTail(pRegle);
} else if (cle.startsWith(env.compile.valSysGEN)) {
printToConsole(" <- ");
printGoal((PrologTerm) pRegle.getAt(1).getAt(1).data);
} else {
printToConsole(" :- ");
printTail(pRegle);
}
}
printToConsole(".\n");
}
public void printTail(PrologRule pRegle) {
int AvDernier = pRegle.size() - 2;
for (int i = 1; i <= AvDernier; i++) {
printGoal((PrologTerm) pRegle.elementAt(i));
printToConsole(", ");
}
printGoal((PrologTerm) pRegle.elementAt(AvDernier + 1));
}
public void printGoal(PrologTerm pTerme) {
indVar = 0;
PrologData donIdTerm = (PrologData) pTerme.get(0);
if ((donIdTerm.typeOfData == uVariable) || (donIdTerm.typeOfData == uCG)) {
printPrologData(donIdTerm, -1);
} else if ((donIdTerm.typeOfData == uIdentifier) &&
((String) donIdTerm.data).startsWith(env.compile.valSysCleBtCp)) {
printPrologData((PrologData) pTerme.elementAt(1), -1);
printToConsole("::");
printPrologData((PrologData) pTerme.elementAt(2), -1);
} else {
printTerm(pTerme, -1);
}
}
public void printToConsole(String s) {
if (env.bWriteToDebugTree || env.bWriteToToolTip) {
alternatePrintString += s;
} else {
printedString += s;
}
}
// new method to get what is printed
public String getPrintedString() {
return printedString;
}
// new method to clear what was printed
public void clearPrintedString() {
printedString = "";
}
void writeOrRecordResult(boolean resolutionWithInterface) {
clearPrintedString();
if (resolutionWithInterface) {
writeResult();
} else {
recordResult();
}
}
void writeResult() {
printToConsole("{");
UnificationRecord recUnif = (UnificationRecord) env.unification.Unif_Stack.get(0); // Les variables au niveau 0
// il faut imprimer les variables par l'ordre inverse de leur insertion dans la table
if (recUnif.isEmpty()) {
printToConsole("}\n");
} else {
String sVar;
String sDerVar = env.compile.vctVariableIdentifiersInQuery.lastElement();
env.compile.vctVariableIdentifiersInQuery.removeElementAt(env.compile.vctVariableIdentifiersInQuery.size() -
1);
VariableIndexPairList pCLContr;
for (int listIndex1 = 0;
listIndex1 < env.compile.vctVariableIdentifiersInQuery.size();
++listIndex1) {
sVar = env.compile.vctVariableIdentifiersInQuery.get(listIndex1);
printToConsole(sVar + "=");
pCLContr = (VariableIndexPairList) recUnif.get(sVar);
indVar = 0;
if ((pCLContr != null) && (pCLContr.ValInd != null)) {
printPrologData(pCLContr.ValInd.pData,
pCLContr.ValInd.index);
} else {
printPrologData(null, 0);
}
printToConsole(", ");
}
// Imprimer le dernier elem a part afin de ne pas ecrire la virgule apres
env.compile.vctVariableIdentifiersInQuery.addElement(sDerVar); // Remettre le dernier elem pour une autre impression !
printToConsole(sDerVar + "=");
pCLContr = (VariableIndexPairList) recUnif.get(sDerVar);
indVar = 0;
if ((pCLContr != null) && (pCLContr.ValInd != null)) {
printPrologData(pCLContr.ValInd.pData,
pCLContr.ValInd.index);
} else {
printPrologData(null, 0);
}
sVar = sDerVar = null;
pCLContr = null;
printToConsole("}\n");
}
flush();
recUnif = null;
}
void recordResult() {
UnificationRecord recUnif = (UnificationRecord) env.unification.Unif_Stack.get(0); // Les variables au niveau 0
if (!recUnif.isEmpty()) {
Hashtable<String, String > hashResult = new Hashtable<String, String>();
String strVar;
VariableIndexPairList pCLContr;
for (int listIndex1 = 0;
listIndex1 < env.compile.vctVariableIdentifiersInQuery.size();
++listIndex1) {
strVar = env.compile.vctVariableIdentifiersInQuery.get(listIndex1);
pCLContr = (VariableIndexPairList) recUnif.get(strVar);
indVar = 0;
String sValue = null;
if ((pCLContr != null) && (pCLContr.ValInd != null) &&
env.bConvResultToString) {
alternatePrintString = "";
clearPrintedString();
printPrologData(pCLContr.ValInd.pData,
pCLContr.ValInd.index); // Ecriture dans alternatePrintString
sValue = alternatePrintString;
alternatePrintString = "";
clearPrintedString();
hashResult.put(strVar, sValue);
} else if ((pCLContr != null) && (pCLContr.ValInd != null)) {
// Creer une forme instanciee de la donnee, similaire a assertTerm
alternatePrintString = "";
clearPrintedString();
printPrologData(pCLContr.ValInd.pData,
pCLContr.ValInd.index); // Ecriture dans alternatePrintString
Vector<String> unVct = null;
try {
unVct = env.compile.compileAlternatePrintString(alternatePrintString);
} catch (CompileException cpExc) {
// This could possibly happen
}
alternatePrintString = "";
clearPrintedString();
hashResult.put(strVar, unVct.toString());
} else {
sValue = "FREE";
hashResult.put(strVar, sValue);
}
}
strVar = null;
pCLContr = null;
env.vctResult.addElement(hashResult);
}
recUnif = null;
}
}
| 28.594498 | 125 | 0.639364 |
fe022dad7c6d090d24cadf9da3a09c3a92b9765f | 2,607 | /*
* 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.security.management.wildfly.properties;
import java.security.NoSuchAlgorithmException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.commons.config.ConfigProperties;
import org.wildfly.security.sasl.util.UsernamePasswordHashUtil;
/**
* <p>Base class for JBoss Wildfly security management when using realms based on properties files.</p>
* <p>Based on JBoss Wildfly controller client API & Util classes.</p>
* @since 0.8.0
*/
public abstract class BaseWildflyPropertiesManager {
public static final String DEFAULT_REALM = "ApplicationRealm";
private static final Logger LOG = LoggerFactory.getLogger(BaseWildflyPropertiesManager.class);
protected String realm = DEFAULT_REALM;
protected static String generateHashPassword(final String username,
final String realm,
final String password) {
String result = null;
try {
result = new UsernamePasswordHashUtil().generateHashedHexURP(
username,
realm,
password.toCharArray());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result;
}
protected static boolean isConfigPropertySet(ConfigProperties.ConfigProperty property) {
if (property == null) {
return false;
}
String value = property.getValue();
return !isEmpty(value);
}
protected static boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
protected void loadConfig(final ConfigProperties config) {
final ConfigProperties.ConfigProperty realm = config.get("org.uberfire.ext.security.management.wildfly.properties.realm",
DEFAULT_REALM);
this.realm = realm.getValue();
}
}
| 37.242857 | 129 | 0.655926 |
5757330cb8cbe5cd863dc1b1bb3ec5221621a754 | 3,928 | package com.sdl.webapp.common.controller;
import com.google.common.collect.Lists;
import com.sdl.webapp.common.api.WebRequestContext;
import com.sdl.webapp.common.api.content.ContentProvider;
import com.sdl.webapp.common.api.content.ContentProviderException;
import com.sdl.webapp.common.api.localization.Localization;
import com.sdl.webapp.common.api.model.EntityModel;
import com.sdl.webapp.common.api.model.ViewModel;
import com.sdl.webapp.common.api.model.entity.AbstractEntityModel;
import com.sdl.webapp.common.api.model.entity.DynamicList;
import com.sdl.webapp.common.controller.exception.InternalServerErrorException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ListControllerTest {
@Mock
private WebRequestContext webRequestContext;
@Mock
private ContentProvider contentProvider;
@InjectMocks
private ListController listController;
@Test
public void shouldOnlyEnrichDynamicLists() throws Exception {
//given
TestEntity model = new TestEntity();
//when
ViewModel viewModel = listController.enrichModel(model, null);
//then
assertSame(model, viewModel);
}
@Test
public void shouldCallPopulateDynamicList() throws Exception {
//given
String id = "id";
DynamicList testList = mock(DynamicList.class);
doCallRealMethod().when(testList).setStart(anyInt());
doCallRealMethod().when(testList).getStart();
when(testList.getId()).thenReturn(id);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("id", id);
request.setParameter("start", "5");
//when
listController.enrichModel(testList, request);
//then
ArgumentCaptor<DynamicList> captor = ArgumentCaptor.forClass(DynamicList.class);
verify(contentProvider).populateDynamicList(captor.capture(), any());
assertEquals("Start is set", 5, captor.getValue().getStart());
}
@Test
public void shouldNotDoubleCallPopulateDynamicList() throws Exception {
//given
DynamicList dynamicList = mock(DynamicList.class);
List<? extends EntityModel> list = Lists.newArrayList(new TestEntity());
doReturn(list).when(dynamicList).getQueryResults();
//when
ViewModel viewModel = listController.enrichModel(dynamicList, null);
//then
assertSame(dynamicList, viewModel);
verify(contentProvider, never()).populateDynamicList(any(DynamicList.class), any());
}
@Test(expected = InternalServerErrorException.class)
public void shouldHandleContentProviderException() throws Exception {
//given
DynamicList testList = mock(DynamicList.class);
doThrow(ContentProviderException.class)
.when(contentProvider).populateDynamicList(any(DynamicList.class), any());
//when
listController.enrichModel(testList, new MockHttpServletRequest());
//then
verify(contentProvider).populateDynamicList(any(DynamicList.class), any(Localization.class));
}
private static class TestEntity extends AbstractEntityModel {
}
} | 34.761062 | 101 | 0.73447 |
d56d058e8dda857257985524a7edbe5290526d60 | 9,434 | /*
* Copyright 2013 Ali Ok (aliokATapacheDOTorg)
*
* 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.trnltk.morphology.contextless.parser;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.trnltk.common.specification.Specification;
import org.trnltk.common.specification.Specifications;
import org.trnltk.model.letter.TurkishSequence;
import org.trnltk.model.lexicon.PrimaryPos;
import org.trnltk.model.morpheme.MorphemeContainer;
import org.trnltk.model.suffix.Suffix;
import org.trnltk.model.suffix.SuffixForm;
import org.trnltk.morphology.morphotactics.SuffixGraph;
import org.trnltk.morphology.morphotactics.SuffixGraphState;
import java.util.LinkedList;
import java.util.List;
import static org.trnltk.morphology.morphotactics.suffixformspecifications.SuffixFormSpecifications.rootHasPrimaryPos;
import static org.trnltk.morphology.morphotactics.suffixformspecifications.SuffixFormSpecifications.rootHasProgressiveVowelDrop;
/**
* Applies mandatory transitions for a {@link MorphemeContainer}.
* <p/>
* Mandatory transitions are transitions which need to be applied when a root for a word is found and it is a valid root
* if following suffix and suffix form are specified ones.
* <p/>
* One example is progressive suffix for some verbs. For example, root "at" of dictionary entry "atamak" is only valid
* if suffixForm "Iyor" of suffix "Progressive" follows. That results in a partial surface of "atıyor".
* Root "at" is not valid for other suffixes (e.g. "atacak" -> not valid, "atayacak" -> valid).
*/
public class MandatoryTransitionApplier {
private final Logger logger = Logger.getLogger(MandatoryTransitionApplier.class);
private final SuffixGraph suffixGraph;
private final SuffixApplier suffixApplier;
private final LinkedList<MandatoryTransitionRule> mandatoryTransitionRules = new LinkedList<MandatoryTransitionRule>();
public MandatoryTransitionApplier(final SuffixGraph suffixGraph, final SuffixApplier suffixApplier) {
this.suffixGraph = suffixGraph;
this.suffixApplier = suffixApplier;
this.createRules();
}
public List<MorphemeContainer> applyMandatoryTransitionsToMorphemeContainers(final List<MorphemeContainer> morphemeContainers, final TurkishSequence input) {
final List<MorphemeContainer> newMorphemeContainers = new LinkedList<MorphemeContainer>();
for (MorphemeContainer morphemeContainer : morphemeContainers) {
MorphemeContainer newMorhpemeContainer = morphemeContainer;
for (MandatoryTransitionRule mandatoryTransitionRule : this.mandatoryTransitionRules) {
if (!mandatoryTransitionRule.getCondition().isSatisfiedBy(newMorhpemeContainer))
continue;
if (!mandatoryTransitionRule.getSourceState().equals(newMorhpemeContainer.getLastState()))
continue;
for (MandatoryTransitionRuleStep mandatoryTransitionRuleStep : mandatoryTransitionRule.getMandatoryTransitionRuleSteps()) {
newMorhpemeContainer = applyRequiredTransitionRuleStepToMorphemeContainer(newMorhpemeContainer, mandatoryTransitionRuleStep, input);
if (newMorhpemeContainer == null)
break;
}
if (newMorhpemeContainer == null)
break;
}
if (newMorhpemeContainer != null)
newMorphemeContainers.add(newMorhpemeContainer);
}
return newMorphemeContainers;
}
private void createRules() {
// English translation to following code fragment:
// if root has PrimaryPos Verb and root has progressive vowel drop
// and its state is VERB_ROOT
// add positive suffix, and then progressive suffix
final MandatoryTransitionRule progressiveVowelDropRule = new RequiredTransitionRuleBuilder(this.suffixGraph)
.condition(
Specifications.and(
rootHasPrimaryPos(PrimaryPos.Verb),
rootHasProgressiveVowelDrop()
)
)
.sourceState("VERB_ROOT")
.step("Pos", "", "VERB_WITH_POLARITY")
.step("Prog", "Iyor", "VERB_WITH_TENSE")
.build();
// more rules can be added
this.mandatoryTransitionRules.add(progressiveVowelDropRule);
}
private MorphemeContainer applyRequiredTransitionRuleStepToMorphemeContainer(final MorphemeContainer morphemeContainer, MandatoryTransitionRuleStep mandatoryTransitionRuleStep, TurkishSequence input) {
final SuffixForm suffixForm = mandatoryTransitionRuleStep.getSuffixForm();
final Suffix suffix = suffixForm.getSuffix();
if (!this.suffixApplier.transitionAllowedForSuffix(morphemeContainer, suffix))
throw new IllegalStateException(String.format("There is a matching mandatory transition rule, but suffix \"%s\" cannot be applied to %s", suffix, morphemeContainer));
final MorphemeContainer newMorphemeContainer = this.suffixApplier.trySuffixForm(morphemeContainer, suffixForm, mandatoryTransitionRuleStep.getTargetState(), input);
if (newMorphemeContainer == null) {
if (logger.isDebugEnabled())
logger.debug(String.format("There is a matching mandatory transition rule, but suffix form \"%s\" cannot be applied to %s", suffixForm, morphemeContainer));
return null;
} else {
return newMorphemeContainer;
}
}
private static class RequiredTransitionRuleBuilder {
private final SuffixGraph suffixGraph;
private Specification<MorphemeContainer> condition;
private SuffixGraphState sourceState;
private LinkedList<MandatoryTransitionRuleStep> steps = new LinkedList<MandatoryTransitionRuleStep>();
private RequiredTransitionRuleBuilder(final SuffixGraph suffixGraph) {
this.suffixGraph = suffixGraph;
}
public RequiredTransitionRuleBuilder condition(Specification<MorphemeContainer> condition) {
this.condition = condition;
return this;
}
public RequiredTransitionRuleBuilder sourceState(String sourceStateName) {
this.sourceState = this.suffixGraph.getSuffixGraphState(sourceStateName);
Validate.notNull(this.sourceState);
return this;
}
public RequiredTransitionRuleBuilder step(String suffixName, String suffixFormStr, String targetStateName) {
final SuffixForm suffixForm = this.suffixGraph.getSuffixForm(suffixName, suffixFormStr);
final SuffixGraphState targetState = this.suffixGraph.getSuffixGraphState(targetStateName);
Validate.notNull(suffixForm);
Validate.notNull(targetState);
this.steps.add(new MandatoryTransitionRuleStep(suffixForm, targetState));
return this;
}
public MandatoryTransitionRule build() {
Validate.notNull(this.sourceState);
Validate.notNull(this.condition);
Validate.notEmpty(this.steps);
return new MandatoryTransitionRule(condition, sourceState, steps);
}
}
private static class MandatoryTransitionRule {
private Specification<MorphemeContainer> condition;
private SuffixGraphState sourceState;
private List<MandatoryTransitionRuleStep> mandatoryTransitionRuleSteps;
private MandatoryTransitionRule(Specification<MorphemeContainer> condition, SuffixGraphState sourceState,
List<MandatoryTransitionRuleStep> mandatoryTransitionRuleSteps) {
Validate.notEmpty(mandatoryTransitionRuleSteps);
this.condition = condition;
this.sourceState = sourceState;
this.mandatoryTransitionRuleSteps = mandatoryTransitionRuleSteps;
}
public SuffixGraphState getSourceState() {
return sourceState;
}
public Specification<MorphemeContainer> getCondition() {
return condition;
}
public List<MandatoryTransitionRuleStep> getMandatoryTransitionRuleSteps() {
return mandatoryTransitionRuleSteps;
}
}
private static class MandatoryTransitionRuleStep {
private final SuffixForm suffixForm;
private final SuffixGraphState targetState;
private MandatoryTransitionRuleStep(SuffixForm suffixForm, SuffixGraphState targetState) {
this.suffixForm = suffixForm;
this.targetState = targetState;
}
public SuffixForm getSuffixForm() {
return suffixForm;
}
public SuffixGraphState getTargetState() {
return targetState;
}
}
} | 43.87907 | 205 | 0.702883 |
950ddf3fff807e8b30c17e0d5848ec1951deefd0 | 10,669 | package org.orman.mapper;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.orman.exception.FeatureNotImplementedException;
import org.orman.mapper.annotation.ManyToMany;
import org.orman.mapper.annotation.ManyToOne;
import org.orman.mapper.annotation.OneToMany;
import org.orman.mapper.exception.FieldNotFoundException;
import org.orman.sql.Query;
import org.orman.util.logging.Log;
/**
* This is a {@link List} implementation which is designed for managing @
* {@link ManyToOne} fields. It will manage ManyToOne relationship therefore it
* can keep entity list (which is on @{@link ManyToOne} holding class) and the
* entity (holds @{@link OneToMany} field) synchronized, provides consistency of
* data.
*
* <p>
* It also manages LAZY LOADING mechanism for retrieved entities. {@link LoadingPolicy}
* </p>
*
* <p>
* <u>CAUTION:</u> It is compulsory if you are managing a @{@link ManyToOne}
* field.
* </p>
*
* @param <D> the entity class of holder type.
* @param <E> the entity class of target type extends {@link Model}.
*
* @author ahmet alp balkan <ahmetalpbalkan at gmail.com>
*/
public class EntityList<D, E extends Model<E>> implements List<E> {
private boolean lazyLoadingEnabled = false;
private boolean lazyLoaded = false;
private D holderInstance;
private Class<D> holderType;
private Class<E> targetType;
private List<E> elements;
private Entity holderEntity;
private Entity targetEntity;
Entity syntheticRelation;
public EntityList(Class<D> holderType, Class<E> targetType, D holderInstance){
this.holderInstance = holderInstance;
this.holderType = holderType;
this.targetType = targetType;
this.lazyLoadingEnabled = false;
holderEntity = MappingSession.getEntity(holderType);
targetEntity = MappingSession.getEntity(targetType);
syntheticRelation = MappingSession.getSyntheticEntity(holderType, targetType);
}
public EntityList(Class<D> holderType, Class<E> targetType, D holderInstance, boolean isLazyLoading){
this(holderType, targetType, holderInstance);
this.lazyLoadingEnabled = isLazyLoading;
}
public EntityList(Class<D> holderType, Class<E> targetType, D holderInstance, List<E> existingResultList){
this(holderType, targetType, holderInstance);
this.elements = existingResultList;
}
private void lazyLoadIfNeeded() {
// if lazy loading exists and not executed OR usual initialization
if ((lazyLoadingEnabled && !lazyLoaded) || elements == null){
if (lazyLoadingEnabled) lazyLoaded = true;
refreshList();
}
}
/**
* Refreshes entity list from the database without any conditions
* satisfied.
*/
public void refreshList() {
ModelQuery mq = ModelQuery.select();
if (syntheticRelation != null){
// ManyToMany exists.
List<Field> synthFields = syntheticRelation.getFields();
Field queryField = null; // guaranteed to be filled.
for(Field sF : synthFields){
if (sF.getClazz().equals(holderType)){
queryField = sF;
break;
}
}
ModelQuery subq = ModelQuery.select().from(syntheticRelation);
subq = subq.selectColumn(
syntheticRelation,
synthFields.get(
synthFields.get(0).equals(queryField) ? 1 : 0)
.getOriginalName());
subq = subq.where(C.eq(syntheticRelation,
queryField.getOriginalName(),
holderInstance));
mq = mq.from(targetType);
mq = mq.where(C.in(targetType, targetEntity.getAutoIncrementField().getOriginalName(), subq.getQuery()));
} else {
// OneToMany exists.
mq = mq.from(targetType);
mq = mq.where(C.eq(targetType,
getTargetField(holderEntity, targetEntity).getGeneratedName(),
holderInstance));
}
Query q = mq.getQuery();
elements = Model.fetchQuery(q, targetType);
Log.trace("Fetched %d target entities to EntityList.", elements.size());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public synchronized boolean add(E e) {
if (e == null) return false;
lazyLoadIfNeeded();
Entity holderEntity = MappingSession.getEntity(holderType);
Entity targetEntity = MappingSession.getEntity(targetType);
if (syntheticRelation == null){
// find @OneToMany class on holderType
// then get on() from it.
Field targetField = getTargetField(holderEntity, targetEntity);
e.setEntityField(targetField, targetEntity, holderInstance);
e.update(); // do update on weak entity.
this.softAdd(e); // add to list.
} else {
// create insert query on synthetic join table
ModelQuery inq = ModelQuery.insert().from(syntheticRelation);
Object holderId = ((Model)holderInstance).getEntityField(holderEntity.getAutoIncrementField());
Object targetId = e.getEntityField(targetEntity.getAutoIncrementField());
for(Field sF : syntheticRelation.getFields()){
inq = inq.set(sF, (sF.getClazz().equals(holderType)) ? holderId : targetId);
}
Model.execute(inq.getQuery());
// find @ManyToMany class on targetType
Field targetField = getM2MTargetField(targetEntity);
if (targetField != null){
// @ManyToMany exists on the other side, update it.
EntityList foreignList = (EntityList) e.getEntityField(targetField);
foreignList.softAdd((Model)holderInstance);
}
this.softAdd(e);
}
return true;
}
/**
* Does not update database, just adds the value to the
* underlying list. Does lazy loading if needed.
* @param e instance.
*/
protected synchronized boolean softAdd(E e){
lazyLoadIfNeeded();
return elements.add(e);
}
public E remove(int index) {
lazyLoadIfNeeded();
E e = elements.remove(index);
if (e == null){ return null; }
else {
// if ManyToOne just delete weak entity.
if (syntheticRelation == null){
e.delete();
} else {
// On ManyToMany, break relationship.
ModelQuery dq = ModelQuery.delete().from(syntheticRelation);
@SuppressWarnings("rawtypes")
Object holderId = ((Model)holderInstance).getEntityField(holderEntity.getAutoIncrementField());
Object targetId = e.getEntityField(targetEntity.getAutoIncrementField());
List<Field> sFL = syntheticRelation.getFields();
boolean is1stFieldHolder = sFL.get(0).getClazz().equals(holderType);
dq = dq.where(C.and(
C.eq(syntheticRelation, is1stFieldHolder ? sFL.get(0).getOriginalName() : sFL.get(1).getOriginalName(), is1stFieldHolder ? holderId : targetId),
C.eq(syntheticRelation, !is1stFieldHolder ? sFL.get(0).getOriginalName() : sFL.get(1).getOriginalName(), !is1stFieldHolder ? holderId : targetId)
));
Model.execute(dq.getQuery());
}
return e;
}
}
public boolean removeAll(Collection<?> c) {
for(Object o : c){
boolean result = remove(o);
if (!result){ // early termination
return false;
}
}
return true;
}
public boolean retainAll(Collection<?> c) {
throw new FeatureNotImplementedException("This method is not implemented on EntityList.");
}
public E set(int index, E element) {
throw new FeatureNotImplementedException("This method is not supported on EntityList.");
}
public boolean contains(Object o) {
lazyLoadIfNeeded();
return elements.contains(o);
}
public boolean containsAll(Collection<?> c) {
lazyLoadIfNeeded();
return elements.containsAll(c);
}
public void add(int index, E element) {
add(element);
}
public boolean addAll(Collection<? extends E> c) {
for(E e : c) {
boolean result = add(e);
if(!result){
// terminate insertions immediately
// not transactional.
return false;
}
}
return true;
}
public boolean addAll(int index, Collection<? extends E> c) {
return addAll(c);
}
/**
* Deletes all items connected to holder entity instance
* and also removes them from entity list.
*/
public void clear() {
lazyLoadIfNeeded();
while(!isEmpty()){
remove(0);
}
elements.clear(); // clear list.
}
public boolean remove(Object o) {
lazyLoadIfNeeded();
@SuppressWarnings("unchecked")
E e = (E) o;
if (e == null) return false;
else {
e.delete();
return elements.remove(o);
}
}
public E get(int index) {
lazyLoadIfNeeded();
return elements.get(index);
}
public int indexOf(Object o) {
lazyLoadIfNeeded();
return elements.indexOf(o);
}
public boolean isEmpty() {
lazyLoadIfNeeded();
return elements.isEmpty();
}
public Iterator<E> iterator() {
lazyLoadIfNeeded();
return elements.iterator();
}
public int lastIndexOf(Object o) {
lazyLoadIfNeeded();
return elements.lastIndexOf(o);
}
public ListIterator<E> listIterator() {
lazyLoadIfNeeded();
return elements.listIterator();
}
public ListIterator<E> listIterator(int index) {
lazyLoadIfNeeded();
return elements.listIterator(index);
}
public int size() {
lazyLoadIfNeeded();
return elements.size();
}
public List<E> subList(int fromIndex, int toIndex) {
throw new FeatureNotImplementedException("This method is not implemented on EntityList.");
}
public Object[] toArray() {
lazyLoadIfNeeded();
return elements.toArray();
}
public <T> T[] toArray(T[] a) {
lazyLoadIfNeeded();
return elements.toArray(a);
}
public String toString() {
lazyLoadIfNeeded();
return (elements == null) ? null : elements.toString();
}
/**
* Finds @{@link OneToMany}-annotated field on given
* holder entity and then extracts and returns foreign key
* {@link Field} on target entity.
*
* @param holderEntity
* @param targetEntity
*/
private Field getTargetField(Entity holderEntity, Entity targetEntity) {
// TODO this class assumes there exists only OneToMany in one class.
for(Field i : holderEntity.getFields()){
OneToMany ann = i.getAnnotation(OneToMany.class);
if (ann != null){
String targetFieldName = ann.onField();
Field targetField = targetEntity.getFieldByName(targetFieldName);
if (targetField == null)
throw new FieldNotFoundException(
holderEntity.getOriginalFullName(), targetFieldName);
else return targetField;
}
}
return null;
}
/**
* Locates other @{@link ManyToMany}-annotated {@link Field} on
* reverse target entity and returns its {@link EntityList} so that
* values can be softly add to provide consistency.
*
* @param targetEntity
* @return <code>null</code> if not exists.
*/
private Field getM2MTargetField(Entity targetEntity) {
// TODO this class assumes there exists only OneToMany in one class.
for(Field cand : targetEntity.getFields()){
ManyToMany ann = cand.getAnnotation(ManyToMany.class);
if (ann != null){
return cand;
}
}
return null;
}
}
| 27.147583 | 152 | 0.699503 |
f1abe3e069a7b0de62259d1a2e85edb36c3f498f | 7,644 | package com.example.cybersafetyapp.ActivityPackage;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.example.cybersafetyapp.R;
import com.example.cybersafetyapp.UtilityPackage.IntentSwitchVariables;
import com.example.cybersafetyapp.UtilityPackage.UtilityVariables;
import org.json.JSONArray;
import org.json.JSONObject;
public class PostInformationDetails extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private String email;
private int requestType;
private TableLayout tablePostDetails;
private Bundle messages;
private String classname = this.getClass().getSimpleName();
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_information_details);
setupToolbarMenu();
setupNavigationDrawerMenu();
messages = getIntent().getExtras();
this.email = messages.getString(IntentSwitchVariables.EMAIL);
this.requestType = messages.getInt(IntentSwitchVariables.REQUEST);
this.tablePostDetails = (TableLayout)findViewById(R.id.activity_post_information_details_table);
if(this.requestType == IntentSwitchVariables.REQUEST_INSTAGRAM_POST_DETAILS)
{
showInstagramPostDetails();
}
}catch (Exception ex)
{
Log.i(UtilityVariables.tag,this.classname+": Exception onCreate: "+ex.toString());
}
}
private void setupNavigationDrawerMenu()
{
NavigationView navigationView = (NavigationView)findViewById(R.id.navigationView);
if(UtilityVariables.isLoggedIn) {
navigationView.inflateMenu(R.menu.menu_loggedin);
//TextView emailTextView = (TextView)findViewById(R.id.txvEmail);
//emailTextView.setText(this.email);
}
else
{
navigationView.inflateMenu(R.menu.menu_loggedout);
}
mDrawerLayout = (DrawerLayout)findViewById(R.id.activity_post_information_details);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
}
private void setupToolbarMenu()
{
mToolbar = (Toolbar)findViewById(R.id.toolbar);
mToolbar.setTitle("Menu");
}
private void addInstagramDataToTable(JSONArray resultArray) throws Exception
{
if(resultArray.length() > 0)
{
for(int i=0; i< resultArray.length();i++)
{
TableRow tr_head = new TableRow(this);
tr_head.setId(i);
tr_head.setBackgroundColor(Color.GRAY);
tr_head.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
tr_head.setPadding(50,5,15,5);
TextView t = new TextView(this);
t.setText(resultArray.getJSONObject(i).getJSONObject("from").getString("username")+":");
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT);
t.setLayoutParams(layoutParams);
//t.setPadding(50,15,5,15);
tr_head.addView(t);
t = new TextView(this);
t.setText(resultArray.getJSONObject(i).getString("text"));
layoutParams = new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT);
t.setLayoutParams(layoutParams);
//t.setPadding(2,15,5,15);
tr_head.addView(t);
this.tablePostDetails.addView(tr_head, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
}
}
private void showInstagramPostDetails() throws Exception
{
JSONObject resultjson = new JSONObject(messages.getString(IntentSwitchVariables.INSTAGRAM_POST_DETAILS_RESULT_JSON));
JSONArray resultArray = resultjson.getJSONArray("data");
addInstagramDataToTable(resultArray);
}
private void closeDrawer() {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
private void showDrawer() {
mDrawerLayout.openDrawer(GravityCompat.START);
}
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
closeDrawer();
else {
Toast.makeText(this," Use the navigate menu to navigate please ", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
closeDrawer();
Intent intent;
switch (menuItem.getItemId())
{
case R.id.MenuAboutUs:
intent = new Intent(this, Aboutus.class);
intent.putExtra(IntentSwitchVariables.SOURCE_CLASS_NAME,this.getClass().getName());
startActivity(intent);
break;
case R.id.MenuLogIn:
intent = new Intent(this, LogIn.class);
intent.putExtra(IntentSwitchVariables.SOURCE_CLASS_NAME,this.getClass().getName());
startActivity(intent);
break;
case R.id.MenuRegister:
intent = new Intent(this, Register.class);
intent.putExtra(IntentSwitchVariables.SOURCE_CLASS_NAME,this.getClass().getName());
startActivity(intent);
break;
case R.id.MenuLogout:
UtilityVariables.isLoggedIn=false;
intent = new Intent(this, WelcomeToCybersafetyApp.class);
startActivity(intent);
break;
case R.id.MenuAddUser:
break;
case R.id.MenuDashboard:
intent = new Intent(this, Dashboard.class);
intent.putExtra(IntentSwitchVariables.EMAIL,this.email);
intent.putExtra(IntentSwitchVariables.SOURCE_CLASS_NAME,this.getClass().getName());
startActivity(intent);
break;
case R.id.MenuEditProfile:
break;
case R.id.MenuSettings:
break;
case R.id.MenuCheckMonitoringProfiles:
intent = new Intent(this, MonitoringProfileList.class);
intent.putExtra(IntentSwitchVariables.EMAIL,this.email);
startActivity(intent);
break;
case R.id.MenuTurnAlarmOn:
break;
}
return false;
}
}
| 37.655172 | 163 | 0.647828 |
72bdeeb6454dfda6855762520c1d1fd7bd8cd75e | 2,579 | package com.hackcaffebabe.mtg.gui.panel.insertupdatecard;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
import com.hackcaffebabe.mtg.model.MTGCard;
import com.hackcaffebabe.mtg.model.Planeswalker;
/**
* Panel to get the MTG Card planes walker info.
*
* @author Andrea Ghizzoni. More info at [email protected]
* @version 1.0
*/
public class PlaneswalkerInfo extends JPanel
{
private static final long serialVersionUID = 1L;
private JSpinner spinLife;
/**
* Create the panel.
*/
public PlaneswalkerInfo(int start){
super();
setBorder( new TitledBorder( "Planeswalker Info" ) );
setLayout( new MigLayout( "", "[][grow]", "[]" ) );
setOpaque( true );
this.initContent( start );
}
/* initialize all components */
private void initContent(int s){
add( new JLabel( "Life:" ), "cell 0 0,alignx trailing" );
this.spinLife = new JSpinner( new SpinnerNumberModel( s, s, 100, 1 ) );
JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) this.spinLife.getEditor();
editor.getTextField().setEnabled( true );
editor.getTextField().setEditable( false );
add( this.spinLife, "cell 1 0,growx" );
}
//===========================================================================================
// METHOD
//===========================================================================================
/**
* This method display the planes walker life from {@link MTGCard} given.
* @param c {@link MTGCard} if null or not instance of Planeswalker.class nothing happen;
*/
public void setData(MTGCard c){
if(c != null && c instanceof Planeswalker) {
this.spinLife.setValue( ((Planeswalker) c).getLife() );
}
}
/**
* Disable all components
*/
public void disableAllComponents(){
((SpinnerNumberModel) this.spinLife.getModel()).setValue( 1 );
for(Component c: getComponents()) {
c.setEnabled( false );
}
}
/**
* Enable all components
*/
public void enableAllComponents(){
for(Component c: getComponents()) {
c.setEnabled( true );
}
}
//===========================================================================================
// GETTER
//===========================================================================================
/**
* Returns the {@link Planeswalker} life.
* @return {@link Integer} the planes walker life.
*/
public int getPlaneswalkerLife(){
return (Integer) this.spinLife.getValue();
}
}
| 28.655556 | 93 | 0.598682 |
2d7ff117fa10aac31fff06d4829869442504a40b | 2,119 | package edu.postech.aadl.maude.preferences;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
public class MaudePrefPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
public static final String MAUDE_DIR = "MAUDE_DIR";
public static final String MAUDE = "MAUDE";
public static final String MAUDE_OPTS = "MAUDE_OPTS";
private IPreferenceStore pref = new ScopedPreferenceStore(InstanceScope.INSTANCE,
"edu.postech.maude.preferences.page");
public MaudePrefPage() {
super(GRID);
ResourcesPlugin.getWorkspace().getRoot().getLocation().toString();
}
@Override
public void init(IWorkbench workbench) {
setPreferenceStore(pref);
setDescription("Maude Preferences");
performDefaults();
}
@Override
protected void createFieldEditors() {
addField(new DirectoryFieldEditor(MAUDE_DIR, "Maude directory:", getFieldEditorParent()));
addField(new FileFieldEditor(MAUDE, "Maude executable:", getFieldEditorParent()));
}
public void validMaudePreferences() throws ExecutionException {
String maudeDirPath = getMaudeDirPath();
if (maudeDirPath.length() == 0) {
throw new ExecutionException("Maude directory is not set properly. Please check Maude Preferences.");
}
String maudeExecPath = getMaudeExecPath();
if (maudeExecPath.length() == 0) {
throw new ExecutionException("Maude binary is not set properly. Please check Maude Preferences.");
}
}
public String getMaudeDirPath() {
String maudeDirPath = pref.getString(MAUDE_DIR);
return maudeDirPath;
}
public String getMaudeExecPath() {
String maudeExecPath = pref.getString(MAUDE);
return maudeExecPath;
}
}
| 33.634921 | 104 | 0.789523 |
4c73a4f0623012b32fe3fbe548763b7a2124cc16 | 1,550 | package ru.job4j.io.socket.file_manager;
import java.io.*;
/**
* Класс, реализующий команду загрузки файла на сервер.
* @author agavrikov
* @since 18.08.2017
* @version 1
*/
public class UploadFile extends Action{
/**
* Команда.
*/
private static final String COMMAND = "upload";
/**
* Конструктор для инициализации.
*/
public UploadFile() {
super(COMMAND);
}
/**
* Метод для выполнения действия.
* @param out выходной поток данных
* @param in входной поток данных
* @param path путь к файлу или папке, с которыми нужно произвести действие
*/
@Override
public void doAction(OutputStream out, InputStream in, Dir path) {
try {
PrintWriter pw = new PrintWriter(out, true);
String[] pathArr = path.getNewPath().split("/");
String name = pathArr[pathArr.length - 1];
File file = new File(String.format("%s%s",path.getPath(), name));
FileOutputStream fos = new FileOutputStream(file);
pw.write(String.format("fileIsReady%s", this.getLN()));
pw.println();
int b;
while ((b = in.read()) != -1) {
fos.write((char) b);
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Метод для получения описания команды.
*
* @return описание команды
*/
@Override
public String getDescr() {
return "Command upload file";
}
}
| 25.833333 | 79 | 0.559355 |
e260fd591fcc2a6e12944a6552eaafec670e3140 | 933 | package application.startup;
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.LongPollingBot;
import application.boilerplate.BotControllerBoilerplate;
import application.context.ApplicationContext;
import application.context.ContextInitializer;
/**
*
* @author Oleksandr Zhyshko
*
*/
public class Application {
private Application() {}
/**
* A method, which has to be called to start the application
*/
public static void start() {
ApiContextInitializer.init();
ContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
try {
botsApi.registerBot((LongPollingBot)ApplicationContext.getComponent(BotControllerBoilerplate.class));
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
| 23.923077 | 104 | 0.78135 |
8681e16449e5fb1edecb9d5c93c331b1dd3953f9 | 8,588 | /* ###
* IP: GHIDRA
*
* 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.
*/
// Figures out computed memory references at the current cursor location or at the instruction at the
// start of each range in an address set.
// Place the cursor on a register or constant operand, and run the script. Also, if a
// register has a value set at the beginning of a function, that register value is assumed
// to be a constant.
//
// For ease of use, attach this to a key-binding to create the reference in one keystroke.
//
// This script is very useful on the ARM, PowerPC and most RISC based processors that
// use multiple instructions to build up memory references, where the reference was
// missed by auto-analysis. It is also useful for references that weren't created
// because of complex base address + offset calculations.
//
// It is very easy to use this script in conjunction with any type of search. For
// example on the ARM, MOVT is used to build up and address. Search the program text
// for all mnemonics MOVT and then select the ones that are creating a reference, make
// a selection in the listing from the search, and then execute this function. It is
// best if you have already assigned a key binding. You can also choose single items
// from the search table and press the key bound to this script.
//
// NOTE: Any values loaded from memory are assumed to be constant.
// If a reference does not make sense on an operand, then it is added to the mnemonic.
//
//@category Analysis
import java.math.BigInteger;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.*;
import ghidra.program.model.block.CodeBlock;
import ghidra.program.model.block.PartitionCodeSubModel;
import ghidra.program.model.lang.*;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.util.*;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
public class MultiInstructionMemReference extends GhidraScript {
Address memReferenceLocation = null;
private Address curInstrloc;
@Override
public void run() throws Exception {
long numInstructions = currentProgram.getListing().getNumInstructions();
monitor.initialize((int) (numInstructions));
monitor.setMessage("Multi-Instruction Reference Markup");
int currentOpIndex = 0;
Address start = currentLocation.getAddress();
if ((currentSelection == null || currentSelection.isEmpty()) &&
currentLocation instanceof OperandFieldLocation) {
currentOpIndex = ((OperandFieldLocation) currentLocation).getOperandIndex();
}
// set up the address set to restrict processing
AddressSet refLocationsSet = new AddressSet(currentSelection);
if (refLocationsSet.isEmpty()) {
refLocationsSet.addRange(start, start);
}
findMemRefAtOperand(currentOpIndex, refLocationsSet);
}
@SuppressWarnings("unused")
private boolean isSingleInstructions(AddressSet restrictedSet) {
if (restrictedSet.isEmpty()) {
return false;
}
AddressRangeIterator riter = restrictedSet.getAddressRanges();
restrictedSet = new AddressSet(restrictedSet);
while (riter.hasNext()) {
AddressRange addressRange = riter.next();
Instruction instr =
currentProgram.getListing().getInstructionAt(addressRange.getMinAddress());
if (instr != null) {
addressRange = new AddressRangeImpl(instr.getMinAddress(), instr.getMaxAddress());
}
restrictedSet.delete(addressRange);
}
return restrictedSet.isEmpty();
}
private void findMemRefAtOperand(final int opIndex, AddressSetView set) {
// follow all flows building up context
// use context to fill out addresses on certain instructions
ContextEvaluator eval = new ContextEvaluatorAdapter() {
@Override
public boolean evaluateContext(VarnodeContext context, Instruction instr) {
// TODO: could look at instructions like LEA, that are an address to create a reference to something.
if (instr.getMinAddress().equals(curInstrloc)) {
if (checkInstructionMatch(opIndex, context, instr)) {
return true;
}
// if instruction is in delayslot, assume reference is good.
if (instr.getDelaySlotDepth() > 0) {
instr = instr.getNext();
return checkInstructionMatch(opIndex, context, instr);
}
}
return false;
}
private boolean checkInstructionMatch(final int opIdx, VarnodeContext context,
Instruction instr) {
int firstIndex = opIdx;
if (instr.getRegister(firstIndex) == null) {
firstIndex = 0;
}
for (int index = firstIndex; index < instr.getNumOperands(); index++) {
Object[] opObjects = instr.getOpObjects(index);
for (int indexOpObj = 0; indexOpObj < opObjects.length; indexOpObj++) {
if (!(opObjects[indexOpObj] instanceof Register)) {
continue;
}
Register reg = (Register) opObjects[indexOpObj];
RegisterValue rval = context.getRegisterValue(reg);
if (rval == null) {
continue;
}
BigInteger uval = rval.getUnsignedValue();
if (uval == null) {
continue;
}
long offset = uval.longValue();
AddressSpace space = instr.getMinAddress().getAddressSpace();
Address addr = space.getTruncatedAddress(offset, true);
// assume that they want the reference, don't worry it isn't in memory
makeReference(instr, index, addr, monitor);
return false;
}
}
return false;
}
@Override
public boolean allowAccess(VarnodeContext context, Address addr) {
// allow values to be read from writable memory
return true;
}
};
try {
AddressRangeIterator riter = set.getAddressRanges();
while (riter.hasNext() && !monitor.isCancelled()) {
AddressRange addressRange = riter.next();
curInstrloc = addressRange.getMinAddress();
AddressSet body = null;
Address start = curInstrloc;
Function curFunc =
currentProgram.getFunctionManager().getFunctionContaining(curInstrloc);
if (curFunc != null) {
start = curFunc.getEntryPoint();
body = new AddressSet(curFunc.getBody());
}
else {
body = new AddressSet(curInstrloc);
PartitionCodeSubModel model = new PartitionCodeSubModel(currentProgram);
CodeBlock block = model.getFirstCodeBlockContaining(curInstrloc, monitor);
if (block != null) {
start = block.getFirstStartAddress();
body.add(block);
}
}
// if the instruction attempting to markup is in the delayslot, backup an instruction
Instruction instr = currentProgram.getListing().getInstructionAt(curInstrloc);
if (instr != null && instr.isInDelaySlot()) {
instr = instr.getPrevious();
if (instr != null) {
curInstrloc = instr.getMinAddress();
}
}
SymbolicPropogator symEval = new SymbolicPropogator(currentProgram);
symEval.setParamRefCheck(false);
symEval.setReturnRefCheck(false);
symEval.setStoredRefCheck(false);
symEval.flowConstants(start, body, eval, true, monitor);
}
}
catch (CancelledException e) {
}
}
/**
* @param instruction
* @param space
* @param scalar
* @param nextInstr
* @param addend
* @param taskMonitor
*/
private void makeReference(Instruction instruction, int opIndex, Address addr,
TaskMonitor taskMonitor) {
if (instruction.getPrototype().hasDelaySlots()) {
instruction = instruction.getNext();
if (instruction == null) {
return;
}
}
if (opIndex == -1) {
for (int i = 0; i < instruction.getNumOperands(); i++) {
int opType = instruction.getOperandType(i);
// markup the program counter for any flow
if ((opType & OperandType.DYNAMIC) != 0) {
opIndex = i;
break;
}
}
}
if (opIndex == -1) {
opIndex = instruction.getNumOperands() - 1;
}
if (opIndex == -1) {
instruction.addMnemonicReference(addr, RefType.DATA, SourceType.ANALYSIS);
}
else {
instruction.addOperandReference(opIndex, addr, RefType.DATA, SourceType.ANALYSIS);
}
}
}
| 34.352 | 105 | 0.713088 |
3afb4e947ddb89553c01da011c21ae896958e95d | 1,138 | package mx.gob.sre.nec.util.main;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RenameFile {
private static final Map<String, String> myMap;
static {
myMap = new HashMap<String, String>();
myMap.put("DerPulgar_1_1", "1");
myMap.put("id_1_2", "2");
myMap.put("DerMedio_1_3", "3");
myMap.put("DerAnular_1_4", "4");
myMap.put("DerMenique_1_5", "5");
myMap.put("IzqPulgar_1_6", "6");
myMap.put("ii_1_7", "7");
myMap.put("IzqMedio_1_8", "8");
myMap.put("IzqAnular_1_9", "9");
myMap.put("IzqMenique_1_10", "10");
}
public void renameFiles(List<File> files) {
// for(int i=0;i<files.size();i++){
// //if()
//
// }
for (File file : files) {
for (String key : myMap.keySet()) {
if (file.getName().contains(key)) {
//
if (file.renameTo(new File(file.getParentFile()+"/"+myMap.get(key)+".wsq"))) {
System.out.println("rename " + file.getName() + " to " + myMap.get(key));
} else {
System.err.println("Fail to rename " + file.getName() + " to " + myMap.get(key));
}
}
}
file.getName();
}
}
}
| 22.313725 | 87 | 0.598418 |
2b0200d6ebe12bdb61641691e62e71d23878bb6d | 3,084 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation 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.unitime.timetable.model.base;
import java.io.Serializable;
import org.unitime.timetable.model.DistributionObject;
import org.unitime.timetable.model.DistributionPref;
import org.unitime.timetable.model.PreferenceGroup;
/**
* Do not change this class. It has been automatically generated using ant create-model.
* @see org.unitime.commons.ant.CreateBaseModelFromXml
*/
public abstract class BaseDistributionObject implements Serializable {
private static final long serialVersionUID = 1L;
private Long iUniqueId;
private Integer iSequenceNumber;
private DistributionPref iDistributionPref;
private PreferenceGroup iPrefGroup;
public static String PROP_UNIQUEID = "uniqueId";
public static String PROP_SEQUENCE_NUMBER = "sequenceNumber";
public BaseDistributionObject() {
initialize();
}
public BaseDistributionObject(Long uniqueId) {
setUniqueId(uniqueId);
initialize();
}
protected void initialize() {}
public Long getUniqueId() { return iUniqueId; }
public void setUniqueId(Long uniqueId) { iUniqueId = uniqueId; }
public Integer getSequenceNumber() { return iSequenceNumber; }
public void setSequenceNumber(Integer sequenceNumber) { iSequenceNumber = sequenceNumber; }
public DistributionPref getDistributionPref() { return iDistributionPref; }
public void setDistributionPref(DistributionPref distributionPref) { iDistributionPref = distributionPref; }
public PreferenceGroup getPrefGroup() { return iPrefGroup; }
public void setPrefGroup(PreferenceGroup prefGroup) { iPrefGroup = prefGroup; }
public boolean equals(Object o) {
if (o == null || !(o instanceof DistributionObject)) return false;
if (getUniqueId() == null || ((DistributionObject)o).getUniqueId() == null) return false;
return getUniqueId().equals(((DistributionObject)o).getUniqueId());
}
public int hashCode() {
if (getUniqueId() == null) return super.hashCode();
return getUniqueId().hashCode();
}
public String toString() {
return "DistributionObject["+getUniqueId()+"]";
}
public String toDebugString() {
return "DistributionObject[" +
"\n DistributionPref: " + getDistributionPref() +
"\n PrefGroup: " + getPrefGroup() +
"\n SequenceNumber: " + getSequenceNumber() +
"\n UniqueId: " + getUniqueId() +
"]";
}
}
| 33.89011 | 109 | 0.756485 |
26fe2838bc1a63b2334800522b8d7d3637e6cab0 | 3,094 | package nico.styTool;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.os.Environment;
public class Downloader
{
String urlStr;// 下载链接
String filePath;// 下载路径
String fileName;// 下载文件名
DownloadListener downloadListener;
public void setDownloadListener(DownloadListener listener)
{
this.downloadListener = listener;
}
public Downloader(Context context, String url, String filePath, String fileName)
{
this.urlStr = url;
this.filePath = filePath;
this.fileName = fileName;
}
public Downloader(Context context, String url, String fileName)
{
this(context, url, "/download/", fileName);
}
/**
* 开始下载
*/
public void start()
{
URL url = null;
try
{
url = new URL(urlStr);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setDoInput(true);
urlCon.setRequestMethod("GET");
urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 建立连接
urlCon.connect();
int length = urlCon.getContentLength();
downloadListener.onStart(length);
if (urlCon.getResponseCode() == 200)
{
File path = Environment.getExternalStoragePublicDirectory(filePath);
File file = new File(path, fileName);
BufferedInputStream is = new BufferedInputStream(urlCon.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[10240];
int len = 0;
int receivedBytes = 0;
label: while (true)
{
// 这里如果暂停下载,并没有真正的销毁线程,而是处于等待状态
// 但如果这时候用户退出了,要做处理,比如取消任务;或做其他处理
if (isPause)
downloadListener.onPause();
if (isCancel)
{
downloadListener.onCancel();
break label;
}
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
while (!isPause && (len = is.read(buffer)) > 0)
{
out.write(buffer, 0, len);
receivedBytes += len;
downloadListener.onProgress(receivedBytes);
if (receivedBytes == length)
{
downloadListener.onSuccess(file);
break label;
}
if (isCancel)
{
downloadListener.onCancel();
file.delete();
break label;
}
}
}
is.close();
out.close();
}
else
{
//Log.e("jlf", "ResponseCode:" + urlCon.getResponseCode() + ", msg:" + urlCon.getResponseMessage());
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
downloadListener.onFail();
}
catch (IOException e)
{
e.printStackTrace();
downloadListener.onFail();
}
}
private boolean isPause;
public void pause()
{
isPause = true;
}
public void resume()
{
isPause = false;
isCancel = false;
downloadListener.onResume();
}
private boolean isCancel;
public void cancel()
{
isCancel = true;
}
}
| 20.626667 | 104 | 0.661603 |
2f6146816bfa37c0b2dec211e2db26508ec02253 | 16,599 | /**
* COPYRIGHT (C) 2015 Alex Aiezza. All Rights Reserved.
*
* See the LICENSE for the specific language governing permissions and
* limitations under the License provided with this project.
*/
package edu.rit.flick.genetics;
import static edu.rit.flick.config.DefaultOptionSet.DELETE_FLAG;
import static edu.rit.flick.config.DefaultOptionSet.VERBOSE_FLAG;
import static java.lang.String.format;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import org.apache.commons.io.FileUtils;
import com.google.common.collect.BiMap;
import com.google.common.io.Files;
import edu.rit.flick.FileDeflator;
import edu.rit.flick.config.Configuration;
import edu.rit.flick.genetics.util.ByteBufferOutputStream;
import it.unimi.dsi.io.ByteBufferInputStream;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
/**
* @author Alex Aiezza
*
*/
public abstract class FastFileDeflator implements FastFileArchiver, FileDeflator
{
public final static double EXPECTED_COMPRESSION_RATIO = 0.25;
private boolean interrupted = false;
// Output files
protected ByteBufferOutputStream datahcf;
protected ByteBufferOutputStream nfile;
protected BufferedOutputStream headerfile;
protected BufferedOutputStream iupacfile;
protected BufferedOutputStream tailfile;
protected FileWriter metafile;
// Input file
protected ByteBufferInputStream fastIn;
// Tracking fields
private boolean writingToNFile = false;
protected byte [] hyperCompressionBytes = new byte [4];
protected byte dnaByte;
protected final AtomicInteger lineType = new AtomicInteger(
SEQUENCE_IDENTIFIER_LINE );
protected final LongAdder dnaPosition = new LongAdder()
// @formatter:off
{
private static final long serialVersionUID = 1L;
@Override
public void increment()
{
super.increment();
localSeqLineSize++;
}
};
// @formatter:on
protected int compressionCounter = 0;
protected int localSeqLineSize = 0;
protected int seqLineSize = 0;
private boolean containsCarriageReturns = false;
private boolean isRNAData = false;
protected final BiMap<String, Byte> byteConverter;
public FastFileDeflator()
{
byteConverter = new ByteConverterBiMapFactory().getByteConverter( 4 );
}
protected void afterProcessNucleotides() throws IOException
{}
protected void beforeProcessNucleotide()
{}
@Override
public boolean containsCarriageReturns()
{
return containsCarriageReturns;
}
protected void createOutputFiles( final File fastFile, final String tempOutputDirectory )
throws IOException
{
datahcf = ByteBufferOutputStream.map( new File( tempOutputDirectory + SEQUENCE_DATA_FILE ),
MapMode.READ_WRITE, (long) ( fastFile.length() * EXPECTED_COMPRESSION_RATIO ) );
nfile = ByteBufferOutputStream.map( new File( tempOutputDirectory + N_FILE ),
MapMode.READ_WRITE, (long) ( fastFile.length() * EXPECTED_COMPRESSION_RATIO * 2 ) );
headerfile = new BufferedOutputStream(
new FileOutputStream( tempOutputDirectory + SEQUENCE_ID_FILE ), DEFAULT_BUFFER );
iupacfile = new BufferedOutputStream(
new FileOutputStream( tempOutputDirectory + IUPAC_CODE_FILE ), DEFAULT_BUFFER );
tailfile = new BufferedOutputStream(
new FileOutputStream( tempOutputDirectory + SEQUENCE_TAIL_FILE ), DEFAULT_BUFFER );
metafile = new FileWriter( new File( tempOutputDirectory + META_FILE ) );
metafile.write( format( META_FILE_SIZE_FORMAT, fastFile.length() ) );
final FileInputStream fastFis = new FileInputStream( fastFile );
fastIn = ByteBufferInputStream.map( fastFis.getChannel() );
fastFis.close();
}
@Override
public File deflate( final Configuration configuration, final File fileIn, final File fileOut )
{
assert fileIn.exists();
try
{
// Deflate to Directory
final String outputDirectoryPath = fileOut.getPath().replaceAll(
"." + Files.getFileExtension( fileOut.getPath() ), FLICK_FAST_FILE_TMP_DIR_SUFFIX );
final File tmpOutputDirectory = new File( outputDirectoryPath );
if ( tmpOutputDirectory.exists() )
FileUtils.deleteDirectory( tmpOutputDirectory );
tmpOutputDirectory.mkdirs();
final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>();
// Deflate Fast file to a temporary directory
final Thread deflateToDirectoryThread = new Thread( () -> {
try
{
// Deflate Fast file to a temporary directory
deflateToDirectory( fileIn, tmpOutputDirectory );
// Remove unused buffer space
removeUnusedBufferSpace( outputDirectoryPath );
// Compress Directory to a zip file
deflateToFile( tmpOutputDirectory, fileOut );
Runtime.getRuntime().removeShutdownHook( cleanHookAtomic.get() );
} catch ( final Exception e )
{
if ( !interrupted )
System.err.println( e.getMessage() );
}
}, "Default_Deflation_Thread" );
// Make cleaning hook
final Thread cleanHook = new Thread( () -> {
interrupted = true;
configuration.setFlag( VERBOSE_FLAG, false );
configuration.setFlag( DELETE_FLAG, false );
try
{
if ( deflateToDirectoryThread.isAlive() )
deflateToDirectoryThread.interrupt();
// Remove unused buffer space
removeUnusedBufferSpace( outputDirectoryPath );
// Delete files that were not able to be processed
FileUtils.deleteQuietly( tmpOutputDirectory );
System.out.println();
} catch ( final IOException | InterruptedException e )
{
e.printStackTrace();
}
}, "Deflation_Cleaning_Thread" );
cleanHookAtomic.set( cleanHook );
Runtime.getRuntime().addShutdownHook( cleanHook );
deflateToDirectoryThread.start();
deflateToDirectoryThread.join();
} catch ( final IOException | InterruptedException e )
{
e.printStackTrace();
}
return fileOut;
}
public void deflateToDirectory( final File fileIn, final File tmpOutputDirectory )
throws IOException
{
createOutputFiles( fileIn, tmpOutputDirectory.getPath() + File.separator );
initializeDeflator();
if ( fastIn.available() > 0 )
dnaByte = (byte) fastIn.read();
while ( fastIn.available() > 0 )
{
switch ( lineType.get() )
{
case SEQUENCE_IDENTIFIER_LINE:
processSequenceIdentifier();
break;
case SEQUENCE_LINE:
processNucleotides();
afterProcessNucleotides();
break;
default:
processLineType();
}
progressLineType();
}
processProperties();
processTail();
}
protected void deflateToFile( final File tmpOutputDirectory, final File fileOut )
throws IOException, ZipException
{
if ( fileOut.exists() )
fileOut.delete();
final ZipFile flickFile = new ZipFile( fileOut );
final ZipParameters zParams = new ZipParameters();
zParams.setIncludeRootFolder( false );
zParams.setCompressionMethod( Zip4jConstants.COMP_DEFLATE );
zParams.setCompressionLevel( Zip4jConstants.DEFLATE_LEVEL_NORMAL );
flickFile.createZipFileFromFolder( tmpOutputDirectory, zParams, false, 0 );
// Delete files that were just zipped
FileUtils.deleteQuietly( tmpOutputDirectory );
}
@Override
public BiMap<String, Byte> getByteConverter()
{
return byteConverter;
}
protected abstract List<Byte> getSequenceEscapes();
protected void initializeDeflator()
{
writingToNFile = false;
hyperCompressionBytes = new byte [4];
dnaByte = 0;
lineType.set( SEQUENCE_IDENTIFIER_LINE );
dnaPosition.reset();
compressionCounter = 0;
localSeqLineSize = 0;
seqLineSize = 0;
containsCarriageReturns = false;
isRNAData = false;
}
@Override
public boolean isRNAData()
{
return isRNAData;
}
protected void processLineType()
{}
protected void processNucleotides() throws IOException
{
while ( fastIn.available() > 0 && ( dnaByte = (byte) fastIn.read() ) != -1 )
{
beforeProcessNucleotide();
switch ( dnaByte )
{
// Check for N
case N:
if ( !writingToNFile )
{
writingToNFile = true;
final String nPositionStr = Long.toHexString( dnaPosition.longValue() )
.toUpperCase() + RANGE;
nfile.write( nPositionStr.getBytes() );
}
dnaPosition.increment();
continue;
// Check for uppercase nucleotides
case A:
case C:
case G:
case T:
case U:
// Check for U
if ( dnaByte == U || dnaByte == u )
{
isRNAData = true;
dnaByte = T;
}
if ( writingToNFile )
{
final String nPositionStr = Long.toHexString( dnaPosition.longValue() )
.toUpperCase() + PIPE;
nfile.write( nPositionStr.getBytes() );
writingToNFile = false;
}
processConventionalNucleotide();
dnaPosition.increment();
continue;
case CARRIAGE_RETURN:
containsCarriageReturns = true;
continue;
case NEWLINE:
if ( seqLineSize < localSeqLineSize )
seqLineSize = localSeqLineSize;
localSeqLineSize = 0;
continue;
default:
if ( getSequenceEscapes().contains( dnaByte ) )
return;
if ( writingToNFile )
{
final String nPositionStr = Long.toHexString( dnaPosition.longValue() )
.toUpperCase() + PIPE;
nfile.write( nPositionStr.getBytes() );
writingToNFile = false;
}
// File for IUPAC codes and erroneous characters
final String iupacBase = format( "%s-%s|",
Long.toHexString( dnaPosition.longValue() ), (char) dnaByte + "" );
iupacfile.write( iupacBase.getBytes() );
dnaPosition.increment();
}
}
}
protected void processConventionalNucleotide() throws IOException
{
hyperCompressionBytes[compressionCounter] = dnaByte;
if ( compressionCounter == 3 )
{
final String tetramer = new String( hyperCompressionBytes );
if ( !getByteConverter().containsKey( tetramer ) )
throw new TetramerNotFoundException( tetramer );
else datahcf.put( getByteConverter().get( tetramer ).byteValue() );
compressionCounter = 0;
} else compressionCounter++;
}
protected void processProperties() throws IOException
{
metafile.write( format( META_CARRIAGE_RETURN_FORMAT, containsCarriageReturns() ) );
metafile.write( format( META_RNA_DATA_FORMAT, isRNAData() ) );
}
protected String processSequenceIdentifier() throws IOException
{
assert dnaByte == getSequenceIdentifierStart();
// Write Start Location in File
long hI = 0;
if ( fastIn.position() > 1 )
hI = fastIn.position() - ( containsCarriageReturns ? 3 : 2 );
final StringBuffer seqId = new StringBuffer();
while ( dnaByte != NEWLINE )
{
dnaByte = (byte) fastIn.read();
if ( dnaByte == CARRIAGE_RETURN )
containsCarriageReturns = true;
seqId.append( (char) dnaByte );
}
headerfile.write( ( hI + PIPE + seqId.toString() ).getBytes() );
return seqId.toString();
}
protected void processTail() throws IOException
{
int tailCounter = 0;
while ( compressionCounter-- != 0 )
{
final char nucleotide = (char) hyperCompressionBytes[tailCounter];
tailfile.write( nucleotide );
if ( nucleotide != N && writingToNFile )
{
final String nPositionStr = Long.toHexString( dnaPosition.longValue() )
.toUpperCase() + PIPE;
nfile.write( nPositionStr.getBytes() );
writingToNFile = false;
}
dnaPosition.increment();
tailCounter++;
}
if ( writingToNFile )
{
final String nPositionStr = Long.toHexString( dnaPosition.longValue() ).toUpperCase() +
PIPE;
nfile.write( nPositionStr.getBytes() );
writingToNFile = false;
}
}
protected void progressLineType()
{
if ( lineType.get() == SEQUENCE_IDENTIFIER_LINE )
lineType.set( SEQUENCE_LINE );
else lineType.set( SEQUENCE_IDENTIFIER_LINE );
}
@SuppressWarnings ( "resource" )
protected void removeUnusedBufferSpace( final String tmpOutputDirectory )
throws IOException, InterruptedException
{
final long actualDataHcfFileSize = datahcf.position();
final long actualNFileSize = nfile.position();
fastIn.close();
datahcf.close();
headerfile.close();
nfile.close();
iupacfile.close();
tailfile.close();
metafile.close();
fastIn = null;
datahcf = null;
nfile = null;
// Give the last method a moment to garbage collect
// System.gc();
// Thread.sleep( 1000 );
final File dataFile = new File( tmpOutputDirectory + SEQUENCE_DATA_FILE );
final File nFile = new File( tmpOutputDirectory + N_FILE );
// Remove unused buffer space
FileChannel fc = new FileOutputStream( dataFile, true ).getChannel();
fc.force( true );
fc.truncate( actualDataHcfFileSize ).close();
fc = new FileOutputStream( nFile, true ).getChannel();
fc.force( true );
fc.truncate( actualNFileSize ).close();
}
}
| 34.437759 | 101 | 0.562865 |
afef025a54cdd0b406177389fc00baabb19e4cce | 1,785 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.mobile.cordova;
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.utils.async.AppCenterFuture;
import com.microsoft.appcenter.utils.async.DefaultAppCenterFuture;
import android.os.Handler;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
public class AppCenterSharedPlugin extends CordovaPlugin {
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("getInstallId")) {
AppCenterUtils.sendUUIDPluginResultFromFuture(AppCenter.getInstallId(), callbackContext);
return true;
}
if (action.equals("setUserId")) {
String userId = args.getString(0);
AppCenterUtils.sendVoidPluginResultFromFuture(setUserId(userId), callbackContext);
return true;
}
return false;
}
private synchronized AppCenterFuture<Void> setUserId(final String userId) {
final DefaultAppCenterFuture<Void> future = new DefaultAppCenterFuture<>();
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
AppCenter.setUserId(userId);
future.complete(null);
}
});
return future;
}
}
| 31.315789 | 119 | 0.697479 |
5e3a90f29ce01cc19c93a829b623ada5d0624ce5 | 12,904 | package com.github.water.quartz.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.github.water.quartz.dto.ResultDTO;
import com.github.water.quartz.dto.ScheduleDTO;
import com.github.water.quartz.dto.ScheduleJob;
import com.github.water.quartz.exeption.ScheduleException;
import com.github.water.quartz.util.MyFactoryJob;
import com.github.water.quartz.util.ScheduleUtils;
import com.github.water.quartz.util.constant.Constants;
/**
* @Author : water
* @Date : 2016年9月19日
* @Desc : TODO
* @version: V1.0
*/
@Service
@Transactional
public class ScheduleService {
private final Logger LOG = LoggerFactory.getLogger(ScheduleService.class);
@Resource
private SchedulerFactoryBean schedulerFactoryBean;
@Value("${factoryJobConfig.param}")
private String factoryJobConfigParam;
@Value("${factoryJobConfig.url}")
private String factoryJobConfigUrl;
/**
* @param scheduleDTO
* @return
*/
/*@SuppressWarnings({ "unchecked", "rawtypes" })
public ResultDTO addJob(ScheduleDTO scheduleDTO) {
System.out.println("------------------" + factoryJobConfigUrl);
ResultDTO resultDTO = new ResultDTO();
String triggerType = scheduleDTO.getTriggerType();
if (!StringUtils.isEmpty(triggerType)) {
String jobName = scheduleDTO.getScenarioId();
String jobGroup = scheduleDTO.getJobGroup();
Map<String, Object> jobDataMap = scheduleDTO.getJobDataMap();
TriggerBuilder triggerBuilder = ScheduleUtils.createTriggerBuilder(jobName, jobGroup);
JobBuilder jobBuilder = ScheduleUtils.createJobBuilder(MyFactoryJob.class, jobName, jobGroup);
JobDetail jobDetail = ScheduleUtils.createJobDetail(jobBuilder, jobDataMap);
jobDetail.getJobDataMap().put("factoryJobConfigUrl", factoryJobConfigUrl);
jobDetail.getJobDataMap().put("factoryJobConfigParam", factoryJobConfigParam);
Scheduler scheduler;
try {
scheduler = StdSchedulerFactory.getDefaultScheduler();
if (triggerType.equalsIgnoreCase(Constants.QZ_CRON_TRIGGER)) {
String cronExpression = scheduleDTO.getCronExpression();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
CronTrigger cronTrigger = (CronTrigger) triggerBuilder
.withSchedule(scheduleBuilder.withMisfireHandlingInstructionFireAndProceed()).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
} else if (triggerType.equalsIgnoreCase(Constants.QZ_SIMPLE_TRIGGER)) {
Date startTime = scheduleDTO.getStartTime();
Date endTime = scheduleDTO.getEndTime();
int repeatCount = scheduleDTO.getRepeatCount();
int repeatInterval = scheduleDTO.getRepeatInterval();
SimpleTrigger simpleTrigger = ScheduleUtils.createSimpleTrigger(triggerBuilder, startTime, endTime,
repeatCount, repeatInterval);
scheduler.scheduleJob(jobDetail, simpleTrigger);
}
scheduler.start();
resultDTO.setResultMessage(Constants.RESULT_SUCCESS_MSG);
resultDTO.setResultCode(Constants.RESULT_SUCCESS_CODE);
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
resultDTO.setResultMessage(Constants.RESULT_EXCEPTION_MSG);
resultDTO.setResultCode(Constants.RESULT_EXCEPTION_CODE);
}
return resultDTO;
}*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public ResultDTO addJob(ScheduleDTO scheduleDTO) {
System.out.println("------------------" + factoryJobConfigUrl);
ResultDTO resultDTO = new ResultDTO();
String triggerType = scheduleDTO.getTriggerType();
if (!StringUtils.isEmpty(triggerType)) {
String jobName = scheduleDTO.getScenarioId();
String jobGroup = scheduleDTO.getJobGroup();
Map<String, Object> jobDataMap = scheduleDTO.getJobDataMap();
TriggerBuilder triggerBuilder = ScheduleUtils.createTriggerBuilder(jobName, jobGroup);
JobBuilder jobBuilder = ScheduleUtils.createJobBuilder(MyFactoryJob.class, jobName, jobGroup);
JobDetail jobDetail = ScheduleUtils.createJobDetail(jobBuilder, jobDataMap);
jobDetail.getJobDataMap().put("factoryJobConfigUrl", factoryJobConfigUrl);
jobDetail.getJobDataMap().put("factoryJobConfigParam", factoryJobConfigParam);
Scheduler scheduler;
try {
scheduler = StdSchedulerFactory.getDefaultScheduler();
if (triggerType.equalsIgnoreCase(Constants.QZ_CRON_TRIGGER)) {
String cronExpression = scheduleDTO.getCronExpression();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
CronTrigger cronTrigger = (CronTrigger) triggerBuilder
.withSchedule(scheduleBuilder.withMisfireHandlingInstructionFireAndProceed()).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
} else if (triggerType.equalsIgnoreCase(Constants.QZ_SIMPLE_TRIGGER)) {
Date startTime = scheduleDTO.getStartTime();
Date endTime = scheduleDTO.getEndTime();
int repeatCount = scheduleDTO.getRepeatCount();
int repeatInterval = scheduleDTO.getRepeatInterval();
SimpleTrigger simpleTrigger = ScheduleUtils.createSimpleTrigger(triggerBuilder, startTime, endTime,
repeatCount, repeatInterval);
scheduler.scheduleJob(jobDetail, simpleTrigger);
}
scheduler.start();
resultDTO.setResultMessage(Constants.RESULT_SUCCESS_MSG);
resultDTO.setResultCode(Constants.RESULT_SUCCESS_CODE);
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
resultDTO.setResultMessage(Constants.RESULT_EXCEPTION_MSG);
resultDTO.setResultCode(Constants.RESULT_EXCEPTION_CODE);
}
return resultDTO;
}
/**
* 计划中的任务
*
* @return
* @throws Exception
*/
public List<ScheduleJob> jobInPlan(Scheduler scheduler) throws Exception {
GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
for (JobKey jobKey : jobKeys) {
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
for (Trigger trigger : triggers) {
ScheduleJob job = new ScheduleJob();
job.setJobName(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDescription("触发器:" + trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.setStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
}
jobList.add(job);
}
}
return jobList;
}
public List<ScheduleDTO> getJobListByStatus(Scheduler scheduler, String jobStatus) throws Exception {
GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
List<ScheduleDTO> jobList = new ArrayList<ScheduleDTO>();
for (JobKey jobKey : jobKeys) {
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
for (Trigger trigger : triggers) {
ScheduleDTO job = new ScheduleDTO();
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
if (jobStatus.equalsIgnoreCase(triggerState.name())) {
job.setScenarioId(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDescription("触发器:" + trigger.getKey());
job.setStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
job.setTriggerType(Constants.QZ_CRON_TRIGGER);
} else if (trigger instanceof SimpleTrigger) {
SimpleTrigger simpleTriggerTrigger = (SimpleTrigger) trigger;
Date startTime = simpleTriggerTrigger.getStartTime();
Date entTime = simpleTriggerTrigger.getEndTime();
int repeatCount = simpleTriggerTrigger.getRepeatCount();
int repeatInterval = (int) simpleTriggerTrigger.getRepeatInterval();
job.setStartTime(startTime);
job.setEndTime(entTime);
job.setRepeatCount(repeatCount);
job.setRepeatInterval(repeatInterval / 1000);
job.setTriggerType(Constants.QZ_SIMPLE_TRIGGER);
}
}
jobList.add(job);
}
}
return jobList;
}
/**
* 运行中的任务
*
* @return
* @throws Exception
*/
public List<ScheduleJob> jobInRunning(Scheduler scheduler) throws Exception {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size());
for (JobExecutionContext executingJob : executingJobs) {
ScheduleJob job = new ScheduleJob();
JobDetail jobDetail = executingJob.getJobDetail();
JobKey jobKey = jobDetail.getKey();
Trigger trigger = executingJob.getTrigger();
job.setJobName(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDescription("触发器:" + trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.setStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
}
jobList.add(job);
}
return jobList;
}
/**
* 删除定时任务
*
* @param scheduler
* @param jobName
* @param jobGroup
* @throws ScheduleException
*/
public ResultDTO deleteJob(Scheduler scheduler, JobKey jobKey) throws ScheduleException {
ResultDTO resultDTO = new ResultDTO();
try {
scheduler.deleteJob(jobKey);
} catch (SchedulerException e) {
LOG.error("删除定时任务失败", e);
throw new ScheduleException("删除定时任务失败: " + e.getMessage());
}
resultDTO.setResultCode(Constants.RESULT_SUCCESS_CODE);
resultDTO.setResultMessage(Constants.RESULT_SUCCESS_MSG);
return resultDTO;
}
/**
* @param scheduler
* @param jobName
* @param jobGroup
* @throws ScheduleException
*/
public void runOnce(Scheduler scheduler, JobKey jobKey) throws ScheduleException {
try {
scheduler.triggerJob(jobKey);
} catch (SchedulerException e) {
LOG.error("运行一次定时任务失败: ", e);
throw new ScheduleException("运行一次定时任务失败: " + e.getMessage());
}
}
/**
* @param scheduler
* @param jobName
* @param jobGroup
* @throws ScheduleException
*/
public void pauseJob(Scheduler scheduler, JobKey jobKey) throws ScheduleException {
try {
scheduler.pauseJob(jobKey);
LOG.info("Pause scene successful: " + jobKey.getName());
} catch (SchedulerException e) {
LOG.error("暂停定时任务失败", e);
throw new ScheduleException("暂停定时任务失败: " + e.getMessage());
}
}
/**
* 恢复任务
*
* @param scheduler
* @param jobName
* @param jobGroup
* @throws ScheduleException
*/
public void resumeJob(Scheduler scheduler, JobKey jobKey) throws ScheduleException {
try {
scheduler.resumeJob(jobKey);
LOG.info("Resume scene successful: " + jobKey.getName());
} catch (SchedulerException e) {
LOG.error("恢复定时任务失败", e);
throw new ScheduleException("恢复定时任务失败: " + e.getMessage());
}
}
public void updateJob(ScheduleDTO scheduleDTO) throws ScheduleException {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(scheduleDTO.getScenarioId(), scheduleDTO.getJobGroup());
// 获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
// 表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleDTO.getCronExpression());
// 按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
// 按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
} catch (SchedulerException e) {
LOG.error("更新定时任务失败", e);
throw new ScheduleException("更新定时任务失败: " + e.getMessage());
}
}
}
| 34.047493 | 107 | 0.74876 |
6b424fceb7c484155940c00edc6fdaa22e615c84 | 174 | package org.folio.ed.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class CheckInItem {
private String itemBarcode;
}
| 15.818182 | 33 | 0.804598 |
82802f6ea4f3b468bb93477df2a57529e2e3f941 | 5,021 | /*
* 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.commons.collections4.collection;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.Predicate;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the PredicatedCollection.Builder class.
*
* @since 4.1
*/
public class PredicatedCollectionBuilderTest {
/**
* Verify that passing the Predicate means ending up in the buffer.
*/
@Test
public void addPass() {
final PredicatedCollection.Builder<String> builder = PredicatedCollection.notNullBuilder();
builder.add("test");
assertEquals(builder.createPredicatedList().size(), 1);
}
/**
* Verify that failing the Predicate means NOT ending up in the buffer.
*/
@Test
public void addFail() {
final PredicatedCollection.Builder<String> builder = PredicatedCollection.notNullBuilder();
builder.add((String) null);
assertTrue(builder.createPredicatedList().isEmpty());
assertEquals(1, builder.rejectedElements().size());
}
/**
* Verify that only items that pass the Predicate end up in the buffer.
*/
@Test
public void addAllPass() {
final PredicatedCollection.Builder<String> builder = PredicatedCollection.notNullBuilder();
builder.addAll(Arrays.asList("test1", null, "test2"));
assertEquals(builder.createPredicatedList().size(), 2);
}
@Test
public void createPredicatedCollectionWithNotNullPredicate() {
final PredicatedCollection.Builder<String> builder = PredicatedCollection.notNullBuilder();
builder.add("test1");
builder.add((String) null);
final List<String> predicatedList = builder.createPredicatedList();
checkPredicatedCollection1(predicatedList);
final Set<String> predicatedSet = builder.createPredicatedSet();
checkPredicatedCollection1(predicatedSet);
final Bag<String> predicatedBag = builder.createPredicatedBag();
checkPredicatedCollection1(predicatedBag);
final Queue<String> predicatedQueue = builder.createPredicatedQueue();
checkPredicatedCollection1(predicatedQueue);
}
private void checkPredicatedCollection1(final Collection<String> collection) {
assertEquals(1, collection.size());
collection.add("test2");
assertEquals(2, collection.size());
assertThrows(IllegalArgumentException.class, () -> collection.add(null), "Expecting IllegalArgumentException for failing predicate!");
}
@Test
public void createPredicatedCollectionWithPredicate() {
final OddPredicate p = new OddPredicate();
final PredicatedCollection.Builder<Integer> builder = PredicatedCollection.builder(p);
builder.add(1);
builder.add(2);
builder.add(3);
final List<Integer> predicatedList = builder.createPredicatedList();
checkPredicatedCollection2(predicatedList);
final Set<Integer> predicatedSet = builder.createPredicatedSet();
checkPredicatedCollection2(predicatedSet);
final Bag<Integer> predicatedBag = builder.createPredicatedBag();
checkPredicatedCollection2(predicatedBag);
final Queue<Integer> predicatedQueue = builder.createPredicatedQueue();
checkPredicatedCollection2(predicatedQueue);
}
private void checkPredicatedCollection2(final Collection<Integer> collection) {
assertEquals(2, collection.size());
assertThrows(IllegalArgumentException.class, () -> collection.add(4), "Expecting IllegalArgumentException for failing predicate!");
assertEquals(2, collection.size());
collection.add(5);
assertEquals(3, collection.size());
}
private static class OddPredicate implements Predicate<Integer> {
@Override
public boolean evaluate(final Integer value) {
return value % 2 == 1;
}
}
}
| 36.122302 | 142 | 0.713005 |
2bdb84f8d899b14da1e50b181405a76ccb8768f6 | 347 | package com.ucloud.library.netanalysis.callback;
import com.ucloud.library.netanalysis.module.UCAnalysisResult;
/**
* Created by joshua on 2018/9/19 14:01.
* Company: UCloud
* E-mail: [email protected]
*/
public interface OnAnalyseListener {
/** 网络质量分析结果回调, {@link UCAnalysisResult} */
void onAnalysed(UCAnalysisResult result);
}
| 24.785714 | 62 | 0.743516 |
c2f907488bc813bd25c09354a07ea873693c8af5 | 3,124 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.model.transform.plugins;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.ReferencesTrait;
import software.amazon.smithy.model.traits.Trait;
import software.amazon.smithy.model.transform.ModelTransformer;
import software.amazon.smithy.model.transform.ModelTransformerPlugin;
import software.amazon.smithy.utils.FunctionalUtils;
/**
* Removes references to resources that are removed from
* {@link ReferencesTrait}s.
*/
public final class CleanResourceReferences implements ModelTransformerPlugin {
@Override
public Model onRemove(ModelTransformer transformer, Collection<Shape> shapes, Model model) {
Set<Shape> toReplace = new HashSet<>();
shapes.forEach(shape -> toReplace.addAll(getAffectedStructures(model, shape)));
return transformer.replaceShapes(model, toReplace);
}
private Set<Shape> getAffectedStructures(Model model, Shape resource) {
return model.shapes(StructureShape.class)
.flatMap(s -> Trait.flatMapStream(s, ReferencesTrait.class))
.flatMap(pair -> {
// Subject is the structure shape that might be modified.
StructureShape subject = pair.getLeft();
ReferencesTrait trait = pair.getRight();
// Get the reference to a particular shape.
List<ReferencesTrait.Reference> references = trait.getResourceReferences(resource.getId());
if (references.isEmpty()) {
return Stream.empty();
}
// If the trait contains a reference to the resource, then create a new version of the
// trait and shape that no longer reference the resource.
ReferencesTrait.Builder traitBuilder = trait.toBuilder().clearReferences();
trait.getReferences().stream()
.filter(FunctionalUtils.not(references::contains))
.forEach(traitBuilder::addReference);
return Stream.of(subject.toBuilder().addTrait(traitBuilder.build()).build());
})
.collect(Collectors.toSet());
}
}
| 44.628571 | 111 | 0.677017 |
50663bd6b6813cdbacc00f6ae1f04c47321c8984 | 2,624 | /*
* This file is part of ScriptController, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* 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 me.lucko.scriptcontroller.exports;
import java.util.Collection;
/**
* A registry of {@link Export}s shared between scripts.
*
* <p>Allows scripts to share persistent state, or provide a resource in a known
* namespace.</p>
*
* <p>Some scripts will be designed to be totally stateless, and may use exports
* to store state between invocations.</p>
*/
public interface ExportRegistry {
/**
* Creates a new standalone {@link ExportRegistry}.
*
* @return a new export registry
*/
static ExportRegistry create() {
return new ExportRegistryImpl();
}
/**
* Gets an export
*
* @param name the name of the export
* @param <T> the export type
* @return the export
*/
<T> Export<T> get(String name);
/**
* Gets a pointer to an export
*
* @param name the name of the export
* @param <T> the export type
* @return a pointer
* @see Export.Pointer
*/
default <T> Export.Pointer<T> pointer(String name) {
return this.<T>get(name).pointer();
}
/**
* Deletes an export
*
* @param name the name of the export to remove.
*/
void remove(String name);
/**
* Returns a collection of all known exports.
*
* @return a collection of known exports
*/
Collection<Export<?>> getAll();
}
| 30.511628 | 82 | 0.671875 |
f5c30b02c5bcfe31c4ee2195c94ef1051e6e3bc1 | 865 | /*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.webkit.dom;
import org.w3c.dom.html.HTMLParagraphElement;
public class HTMLParagraphElementImpl extends HTMLElementImpl implements HTMLParagraphElement {
HTMLParagraphElementImpl(long peer) {
super(peer);
}
static HTMLParagraphElement getImpl(long peer) {
return (HTMLParagraphElement)create(peer);
}
// Attributes
public String getAlign() {
return getAlignImpl(getPeer());
}
native static String getAlignImpl(long peer);
public void setAlign(String value) {
setAlignImpl(getPeer(), value);
}
native static void setAlignImpl(long peer, String value);
}
| 16.320755 | 95 | 0.662428 |
5d66248bd5fe5cb38a746206728123485df36e52 | 497 |
package com.bs.service;
import java.util.List;
import com.bs.entity.NewsCategory;
import com.bs.utils.PageUtil;
/**
* @author 作者 :yuedengfeng
* @date 创建时间:2019年9月14日 下午7:21:59
* @version 1.0
*/
public interface NewsCategoryService extends Service{
void addNewsCategory(NewsCategory category);
void deleteNewsCategory(int id);
void updateNewsCategory(NewsCategory category);
PageUtil<NewsCategory> selectNewsCategoryList(int page,int pageSize);
List<NewsCategory> selectList();
}
| 19.115385 | 70 | 0.774648 |
862d755563a850e65bfea2ee0e3f9644fd975a70 | 1,053 | package net.twasi.core.plugin.api.customcommands;
import net.twasi.core.plugin.api.TwasiUserPlugin;
import net.twasi.core.translations.renderer.TranslationRenderer;
public abstract class TwasiPluginCommand extends TwasiCustomCommand {
private TwasiUserPlugin twasiUserPlugin;
public TwasiPluginCommand(TwasiUserPlugin twasiUserPlugin) {
this.twasiUserPlugin = twasiUserPlugin;
}
@Override
public boolean allowsTimer() {
return true;
}
@Override
public boolean allowsListing() {
return true;
}
@Deprecated
protected final String getTranslation(String key, Object... objects) {
return this.twasiUserPlugin.getTranslation(key, objects);
}
@Deprecated
protected final String getRandomTranslation(String key, Object... objects) {
return this.twasiUserPlugin.getRandomTranslation(key, objects);
}
@Override
protected final TranslationRenderer getTranslationRenderer(){
return TranslationRenderer.getInstance(twasiUserPlugin);
}
}
| 27 | 80 | 0.731244 |
c846222423aeb5f897aca6a365be7c1ce791cf41 | 1,712 | /*
* This file was automatically generated by EvoSuite
* Mon Nov 14 09:26:04 GMT 2016
*/
package org.openecomp.mso.adapters.tenantrest;
import org.junit.Test;
import static org.junit.Assert.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true)
public class RollbackTenantRequestESTest extends RollbackTenantRequestESTestscaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
RollbackTenantRequest rollbackTenantRequest0 = new RollbackTenantRequest();
TenantRollback tenantRollback0 = new TenantRollback();
rollbackTenantRequest0.setTenantRollback(tenantRollback0);
tenantRollback0.setTenantCreated(true);
TenantRollback tenantRollback1 = rollbackTenantRequest0.getTenantRollback();
assertTrue(tenantRollback1.getTenantCreated());
}
@Test(timeout = 4000)
public void test1() throws Throwable {
RollbackTenantRequest rollbackTenantRequest0 = new RollbackTenantRequest();
TenantRollback tenantRollback0 = new TenantRollback();
rollbackTenantRequest0.setTenantRollback(tenantRollback0);
TenantRollback tenantRollback1 = rollbackTenantRequest0.getTenantRollback();
assertSame(tenantRollback1, tenantRollback0);
}
@Test(timeout = 4000)
public void test2() throws Throwable {
RollbackTenantRequest rollbackTenantRequest0 = new RollbackTenantRequest();
TenantRollback tenantRollback0 = rollbackTenantRequest0.getTenantRollback();
assertNull(tenantRollback0);
}
}
| 38.909091 | 148 | 0.777453 |
06b4ab6f4e40a5acfd27f5d370ae3abd51e9b2fb | 1,276 | package fi.jubic.quanta.auth;
import fi.jubic.easyschedule.Task;
import fi.jubic.quanta.config.Configuration;
import fi.jubic.quanta.dao.UserDao;
import fi.jubic.quanta.exception.ApplicationException;
import fi.jubic.quanta.models.User;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Optional;
@Singleton
public class AdminAuthenticationTask implements Task {
private final Configuration configuration;
private final UserDao userDao;
@Inject
AdminAuthenticationTask(
Configuration configuration,
UserDao userDao
) {
this.configuration = configuration;
this.userDao = userDao;
}
public void run() {
if (configuration.getAdmin().getUsername().length() == 0
|| configuration.getAdmin().getPassword().length() == 0
) {
return;
}
Admin admin = configuration.getAdmin();
Optional<User> adminUser = userDao.getUserByName(
admin.getUsername()
);
if (!adminUser.isPresent()) {
userDao.createAdmin(
admin
).orElseThrow(
() -> new ApplicationException("Couldn't create Admin account")
);
}
}
}
| 26.040816 | 83 | 0.623041 |
b513556a68d27c1710f1f405c6f4900778924a43 | 10,639 | package com.github.ryanlevell.adamantdriver.dataprovider;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.ITestAnnotation;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.internal.annotations.TestAnnotation;
import com.github.ryanlevell.adamantdriver.stubs.BrowserMobProxyStub;
import com.github.ryanlevell.adamantdriver.stubs.WebDriverStub;
import net.lightbody.bmp.BrowserMobProxy;
/**
* Contains the data provider util methods.
*
* @author ryan
*
*/
public class DataProviderUtil {
private static Logger LOG = LoggerFactory.getLogger(DataProviderUtil.class);
/**
* Calls the original data provider method.
*
* @param testContext
* One of the possible params injected by TestNG.
* @param testMethod
* One of the possible params injected by TestNG.
* @return The original 2D array of data.
*/
public static Object[][] callDataProvider(ITestContext testContext, Method testMethod) {
Class<?> dpClass = getDPClass(testMethod);
Method dpMethod = getDPMethod(testMethod);
// only DPs in another class must be static - same class DPs can be
// instance methods.
boolean dpIsStatic = Modifier.isStatic(dpMethod.getModifiers());
Object clazz = null;
if (!dpIsStatic) {
try {
// can't use dpMethod.getDeclaringClass(), method could be in
// abstract parent class
clazz = dpClass.newInstance();
} catch (InstantiationException e) {
LOG.error(Arrays.toString(e.getStackTrace()), e);
} catch (IllegalAccessException e) {
LOG.error(Arrays.toString(e.getStackTrace()), e);
}
}
Object[][] params = null;
try {
Class<?>[] types = dpMethod.getParameterTypes();
// check all possible combinations of possibly injected params to
// make the call via reflection
if (types.length == 2) {
if (types[0].isAssignableFrom(ITestContext.class)) {
params = (Object[][]) dpMethod.invoke(clazz, testContext, testMethod);
} else {
params = (Object[][]) dpMethod.invoke(clazz, testMethod, testContext);
}
} else if (types.length == 1) {
if (types[0].isAssignableFrom(ITestContext.class)) {
params = (Object[][]) dpMethod.invoke(clazz, testContext);
} else if (types[0].isAssignableFrom(Method.class)) {
params = (Object[][]) dpMethod.invoke(clazz, testMethod);
}
} else {
params = (Object[][]) dpMethod.invoke(clazz);
}
} catch (IllegalAccessException e) {
LOG.error(Arrays.toString(e.getStackTrace()), e);
} catch (IllegalArgumentException e) {
LOG.error(Arrays.toString(e.getStackTrace()), e);
} catch (InvocationTargetException e) {
LOG.error(Arrays.toString(e.getStackTrace()), e);
}
return params;
}
/**
* Gets the {@link DataProvider} class. It first checks the test annotation
* dataProviderClass attribute.<br>
* If the attribute is missing, the data provider must be declared in the
* same class.
*
* @param testMethod
* The test method of which we are trying to find the data
* provider.
* @return The data provider class.
*/
private static Class<?> getDPClass(Method testMethod) {
// get dp class
Class<?> dpClass = testMethod.getAnnotation(Test.class).dataProviderClass();
// #dataProviderClass() returns Object if not found so check for it
// explicitly
if (dpClass == null || dpClass == Object.class) {
// class is declaring class (or a super class) if no dp class
// attribute
dpClass = testMethod.getDeclaringClass();
}
return dpClass;
}
/**
* Determine if the test method has the parallel attribute set.
*
* @param m
* The test method.
* @return Whether the test will be ran in parallel.
*/
public static boolean isParallel(Method m) {
DataProvider dpAnnotation = m.getAnnotation(DataProvider.class);
return dpAnnotation != null && dpAnnotation.parallel();
}
/**
* Gets the {@link DataProvider} method.
*
* @param testMethod
* The test method.
* @return The data provider method.
*/
public static Method getDPMethod(Method testMethod) {
Class<?> dpClass = getDPClass(testMethod);
Test ta = testMethod.getAnnotation(Test.class);
String dpName = ta.dataProvider();
List<Method> classMethods = new ArrayList<Method>();
classMethods.addAll(Arrays.asList(dpClass.getMethods()));
// look into all super class's methods as well
Class<?> superClass = dpClass.getSuperclass();
while (superClass != null) {
classMethods.addAll(Arrays.asList(superClass.getMethods()));
superClass = superClass.getSuperclass();
}
// get all methods in the dp class
for (Method m : classMethods) {
DataProvider dpAnnotation = m.getAnnotation(DataProvider.class);
if (dpAnnotation != null && dpAnnotation.name().equals(dpName)) {
return m;
}
}
throw new IllegalStateException("Data Provider not found with name [" + dpName + "] in [" + dpClass + "#"
+ testMethod.getName() + "]. Check that the DataProvider name and DataProvider class are correct.");
}
/**
* Adds the {@link WebDriver} object to the beginning of the original data
* provider array.
*
* @param oldParams
* The original data provider array.
* @return The new array with the {@link WebDriver} object inserted at at
* the beginning.
*/
static Object[][] addWdToParams(Object[][] oldParams) {
Object[][] params = oldParams;
Object[][] paramsWithWd = new Object[params.length][params[0].length + 1];
// add driver to beginning of params list
for (int i = 0; i < params.length; i++) {
Object[] row = new Object[params[i].length + 1];
row[0] = new WebDriverStub();
for (int j = 1; j < paramsWithWd[i].length; j++) {
row[j] = params[i][j - 1];
}
paramsWithWd[i] = row;
}
return paramsWithWd;
}
/**
* Adds the {@link WebDriver} and {@link BrowserMobProxy} objects to the
* beginning of the original data provider array.
*
* @param oldParams
* The original data provider array.
* @return The new array with the {@link WebDriver} and
* {@link BrowserMobProxy} objects inserted at at the beginning.
*/
static Object[][] addProxyToParams(Object[][] oldParams) {
Object[][] params = oldParams;
Object[][] paramsWithWd = new Object[params.length][params[0].length + 2];
// add driver to beginning of params list
for (int i = 0; i < params.length; i++) {
Object[] row = new Object[params[i].length + 2];
row[0] = new WebDriverStub();
row[1] = new BrowserMobProxyStub();
for (int j = 2; j < paramsWithWd[i].length; j++) {
row[j] = params[i][j - 2];
}
paramsWithWd[i] = row;
}
return paramsWithWd;
}
/**
* Injects a custom {@link DataProvider} into the {@link TestAnnotation}
* that adds the {@link WebDriver} to the params list.
*
* @param annotation
* The annotation is customize.
* @param testMethod
* The test method with the annotation.
*/
public static void injectWebDriverProvider(ITestAnnotation annotation, Method testMethod) {
Class<?>[] paramTypes = testMethod.getParameterTypes();
// determine if we need to inject the old data provider
if (paramTypes.length == 1) {
annotation.setDataProviderClass(DataProviders.class);
annotation.setDataProvider(DataProviders.INJECT_WEBDRIVER);
} else {
Method dpMethod = DataProviderUtil.getDPMethod(testMethod);
annotation.setDataProviderClass(DataProviders.class);
if (DataProviderUtil.isParallel(dpMethod)) {
annotation.setDataProvider(DataProviders.INJECT_WEBDRIVER_WITH_PARAMS_PARALLEL);
} else {
annotation.setDataProvider(DataProviders.INJECT_WEBDRIVER_WITH_PARAMS);
}
}
}
/**
* Injects a custom {@link DataProvider} into the {@link TestAnnotation}
* that adds the {@link WebDriver} and {@link BrowserMobProxy} to the params
* list.
*
* @param annotation
* The annotation is customize.
* @param testMethod
* The test method with the annotation.
*/
public static void injectProxyProvider(ITestAnnotation annotation, Method testMethod) {
Class<?>[] paramTypes = testMethod.getParameterTypes();
// determine if we need to inject the old data provider
if (paramTypes.length == 2) {
annotation.setDataProviderClass(DataProviders.class);
annotation.setDataProvider(DataProviders.INJECT_PROXY);
} else {
Method dpMethod = DataProviderUtil.getDPMethod(testMethod);
annotation.setDataProviderClass(DataProviders.class);
if (DataProviderUtil.isParallel(dpMethod)) {
annotation.setDataProvider(DataProviders.INJECT_PROXY_WITH_PARAMS_PARALLEL);
} else {
annotation.setDataProvider(DataProviders.INJECT_PROXY_WITH_PARAMS);
}
}
}
/**
* Determines if the first parameter is a {@link WebDriver}.
*
* @param testMethod
* The test method.
* @return True or false.
*/
public static boolean hasWebDriverParam(Method testMethod) {
boolean isWebDriverParam = isParam(0, WebDriver.class, testMethod.getParameterTypes());
if (isWebDriverParam) {
if (testMethod.getAnnotation(Parameters.class) != null) {
throw new IllegalStateException(
"@Parameters is not yet supported by AdamantDriver. Use @DataProvider instead.");
}
}
return isWebDriverParam;
}
/**
* Determines if the first parameter is a {@link WebDriver} and the second
* parameter is a {@link BrowserMobProxy}.
*
* @param testMethod
* The test method.
* @return True or false.
*/
public static boolean hasProxyParam(Method testMethod) {
// must be webdriver test
if (!hasWebDriverParam(testMethod)) {
return false;
}
return isParam(1, BrowserMobProxy.class, testMethod.getParameterTypes());
}
/**
* Determine if a parameter at the index is the class type expected.
*
* @param paramIndex
* The index in the parameter list.
* @param type
* The class type that is expected.
* @param paramTypes
* The parameter list.
* @return True or false.
*/
private static boolean isParam(int paramIndex, Class<?> type, Class<?>[] paramTypes) {
if (paramTypes != null && paramIndex < paramTypes.length) {
if (paramTypes[paramIndex].isAssignableFrom(type)) {
return true;
}
}
return false;
}
}
| 32.045181 | 107 | 0.690854 |
f729f9bad356f0aa5931d07597e52df2302e5c53 | 1,392 | package org.linlinjava.litemall.core;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.concurrent.Executor;
/**
* 测试邮件发送服务
* <p>
* 注意LitemallNotifyService采用异步线程操作
* 因此测试的时候需要睡眠一会儿,保证任务执行
* <p>
* 开发者需要确保:
* 1. 在相应的邮件服务器设置正确notify.properties已经设置正确
* 2. 在相应的邮件服务器设置正确
*/
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MailTest {
@Autowired
private NotifyService notifyService;
@Test
public void testMail() {
notifyService.notifyMail("订单信息", "订单1111111已付款,请发货");
}
@Configuration
@Import(ApplicationCore.class)
static class ContextConfiguration {
@Bean
@Primary
public Executor executor() {
return new SyncTaskExecutor();
}
}
}
| 26.264151 | 71 | 0.76796 |
1962e38512a304f2f0773d19776c517a3de2cbe4 | 13,616 | package com.example.performance_tracker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import templates_and_keys.Class;
import templates_and_keys.Keys;
import templates_and_keys.Priority;
import templates_and_keys.Task;
import templates_and_keys.User;
public class AddClassFragment extends Fragment {
private User user;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add_class, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// getting the data from the Profile Activity as a bundle
Bundle bundle = getArguments();
// this part connects to the firebase database
FirebaseUser loggedInUser = FirebaseAuth.getInstance().getCurrentUser();
String loggedInUserId = loggedInUser.getUid();
DocumentReference userProfile = FirebaseFirestore.getInstance().document(Keys.USERS.concat("/").concat(loggedInUserId));
// for accessing the class list and updating the classes listview
ListView newTaskClassRelated = view.findViewById(R.id.classes_list);
ArrayList<Class> classesName = new ArrayList<>();
ArrayAdapter<Class> classNameAdapter = new ArrayAdapter<Class>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, classesName);
newTaskClassRelated.setAdapter(classNameAdapter);
if (bundle != null) {
user = bundle.getParcelable(Keys.BUNDLE_USER);
HashMap<String, Class> classes = user.classes;
if (classes != null) {
classesName.addAll(classes.values());
classNameAdapter.notifyDataSetChanged();
}
}
// for manual add class
EditText className = view.findViewById(R.id.canvas_class);
Button addClass = view.findViewById(R.id.add_class);
addClass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String classNameValue = className.getText().toString().trim();
if (classNameValue.isEmpty()) {
className.setError("Class Name shouldn't be empty");
return;
}
Class userClass = new Class(className.getText().toString().trim());
userProfile.update(Keys.CLASS_LISTS_KEY.concat(".").concat(userClass.classUid), userClass);
classesName.add(userClass);
classNameAdapter.notifyDataSetChanged();
}
});
Button importClass = view.findViewById(R.id.import_class_from_canvas);
importClass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (user.canvasAPIKey==null) {
// create a new intent to show the pop up window: Call the InsertCanvasAPIKey class
openLauchBar();
} else {
// this part finds all the classes information from CANVAS using the Canvas REST API
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest getAllCanvasClassesRequest = new JsonArrayRequest(Request.Method.GET, Keys.CANVAS_CLASS_JSON_URL, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
String className = jsonObject.getString("name");
String classUid = jsonObject.getString("id");
String classUUid = jsonObject.getString("uuid");
Class newCanvasClass = new Class(className, classUUid, classUid);
userProfile.update(Keys.CLASS_LISTS_KEY.concat(".").concat(classUUid), newCanvasClass);
if (!classesName.contains(newCanvasClass)) {
user.classes.put(classUUid, newCanvasClass);
classesName.add(newCanvasClass);
classNameAdapter.notifyDataSetChanged();
Toast.makeText(getContext(), className, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("Authorization", "Bearer " + user.canvasAPIKey);
return params;
}
};
// first add the request to the queue that is processed in separate thread using Volley
queue.add(getAllCanvasClassesRequest);
// now we need to get all the assignment from that class: so we need to send another GET request
if (!user.classes.isEmpty()) {
for (Class canvasClass : user.classes.values()) {
JsonArrayRequest assignmentRequest = new JsonArrayRequest(Request.Method.GET, Keys.GET_CLASS_ASSIGNMENTS_URL(canvasClass.courseId), null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
// this part captures whether the assignment has been already submitted or not
Boolean assignmentStatus = jsonObject.getBoolean("has_submitted_submissions");
if (jsonObject != null && !assignmentStatus) {
// see the CANVAS LMS to understand why we use Hardcoded string
String taskName = jsonObject.getString("name");
Priority priorityLevel; // generally we put class stuffs as high priority task
if (jsonObject.getBoolean("is_quiz_assignment"))
priorityLevel = Priority.HIGH;
else
priorityLevel = Priority.MEDIUM;
String taskDueDate = jsonObject.getString("due_at").split("T")[0];
if (taskDueDate == null || taskDueDate == "null") {
taskDueDate = "No Deadline";
priorityLevel = Priority.LOW;
}
String classUid = jsonObject.getString("course_id");
Task newTask = new Task(taskName, taskDueDate, priorityLevel, canvasClass.classUid);
userProfile.update(Keys.TASK_LISTS.concat(".").concat(taskDueDate).concat(".").concat(newTask.uuid), newTask);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("Authorization", "Bearer " + user.canvasAPIKey);
return params;
}
};
queue.add(assignmentRequest);
}
}
}
}
});
// on item listener
newTaskClassRelated.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Class selectedClass = (Class) parent.getSelectedItem();
String selectedClassUid = selectedClass.classUid;
Toast.makeText(getContext(), selectedClass.className + " ->" + selectedClass.classUid, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
// this activity launcher overrides if the task / assignment is marked completed in LoadTaskObject
private final ActivityResultLauncher<Intent> activityLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
// if the task is marked as completed, the return value is RESULT_OK = -1 from the class LoadTask Object
if (result.getResultCode() == Activity.RESULT_OK) {
//if the task is mark completed, then get all the task information from the intent
String canvasKeygen = result.getData().getStringExtra(Keys.CLASS_CANVAS_API_KEY);
// invokes the firebase API to update the completed task
FirebaseUser loggedInUser = FirebaseAuth.getInstance().getCurrentUser();
String loggedInUserId = loggedInUser.getUid();
String path = Keys.USERS + "/" + loggedInUserId;
user.canvasAPIKey = canvasKeygen;
DocumentReference userProfile = FirebaseFirestore.getInstance().document(path);
userProfile.update(Keys.CLASS_CANVAS_API_KEY, canvasKeygen);
} else if (result.getResultCode() == Activity.RESULT_CANCELED) {
Toast.makeText(getContext(), "Task Update Cancelled", Toast.LENGTH_LONG).show();
}
}
}
);
private void openLauchBar() {
Intent insertAPIKeyActivity = new Intent(getContext(), InsertCanvasAPIKey.class);
activityLauncher.launch(insertAPIKeyActivity); // launches the activity through the custom activity launcher
}
}
| 50.80597 | 202 | 0.545314 |
d210a77f637678414f7e8919916a382441b81859 | 1,796 | /*
* TypeNativePrimitiveXML.java
*
* Created on 29 de octubre de 2004, 12:10
*/
package com.innowhere.jnieasy.core.impl.common.typedec.xml;
import com.innowhere.jnieasy.core.JNIEasyXMLException;
import com.innowhere.jnieasy.core.impl.TaskContext;
import com.innowhere.jnieasy.core.impl.common.typedec.model.TypeNativePrimitiveImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.traversal.TreeWalker;
public abstract class TypeNativePrimitiveXML extends TypeNativeXML
{
/** Creates a new instance of TypeNativePrimitiveXML */
public TypeNativePrimitiveXML(TypeNativePrimitiveImpl typeDec)
{
super(typeDec);
}
public TypeNativePrimitiveImpl getTypeNativePrimitive()
{
return (TypeNativePrimitiveImpl)typeDec;
}
public void parse(Element typeNode, TreeWalker walker, TaskContext ctx)
{
super.parse(typeNode, walker, ctx);
TypeNativePrimitiveImpl typeDec = getTypeNativePrimitive();
parseAttMemSize(typeNode,typeDec);
}
public static void parseAttMemSize(Element typeNode,TypeNativePrimitiveImpl typeDec)
{
try
{
Attr attMemSize = typeNode.getAttributeNode("memSize");
if (attMemSize != null)
typeDec.setMemSizeExpr(attMemSize.getValue());
Attr attPrefAlignSize = typeNode.getAttributeNode("prefAlignSize");
if (attPrefAlignSize != null)
typeDec.setPreferredAlignSizeExpr(attPrefAlignSize.getValue());
}
catch(JNIEasyXMLException ex)
{
throw ex;
}
catch(Exception ex)
{
throw new JNIEasyXMLException(ex,typeNode);
}
}
}
| 29.442623 | 91 | 0.655345 |
0697c2d839939b802c5273d2161f3a8705cbc1f6 | 8,330 | /**
* Copyright (c) 2012-2019 CSMAKE, Inc.
*
* Generate by csmake.com for java Mon Oct 21 20:37:46 CST 2019
*/
package cn.ehiot;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The driverServlet interface.
*
* <p>Note: Generate by csmake for java .</p>
*
* {@link cn.ehiot.driver}
* @author www.csmake.com
*/
@WebServlet(name = "cn.ehiot.driver", urlPatterns = {"/cn.ehiot.driver/*"})
public class driverServlet extends HttpServlet{
public driverServlet(){
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String url = request.getRequestURI().replace(request.getContextPath(), "");
System.out.print(url);
int i = url.lastIndexOf("/");
String cmd = "";
if (i > 1)
{
cmd = java.net.URLDecoder.decode(url.substring(i + 1), "UTF8");
int dot = cmd.indexOf(".");
if (dot != -1)
{
cmd = cmd.substring(0, dot);
}
}
switch (cmd)
{
default://json调用
{
cn.stdiot.JSONCall call = JSON.parseObject(request.getInputStream(), cn.stdiot.JSONCall.class);
handleRequest(call, request, response);
break;
}
}
} catch (Exception ex) {
StringBuilder sb = new StringBuilder();
sb.append("{errcode:\"500\",errmsg:\"").append(ex.toString()).append("\",value:''}");
byte[] utf8 = sb.toString().getBytes("UTF-8");
response.setContentLength(utf8.length);
try (javax.servlet.ServletOutputStream out = response.getOutputStream()) {
out.write(utf8);
}
}
}
protected void handleRequest(cn.stdiot.JSONCall $, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
cn.stdiot.JSONReturn ret = call($);
byte[] utf8 = JSON.toJSONString(ret).getBytes("UTF-8");
response.setContentLength(utf8.length);
try (javax.servlet.ServletOutputStream out = response.getOutputStream()) {
out.write(utf8);
}
}
private long sessionid= System.currentTimeMillis();
protected String getSessionId(){
return String.valueOf(sessionid++);
}
private cn.stdiot.JSONReturn call(cn.stdiot.JSONCall $)
{
String errcode = "200";
Object retValue = null;
String errmsg = "";
cn.ehiot.driver proxy = cn.ehiot.driver.Singleton();
try
{
switch ($.cmd){
/** public methods */
case "help" :{
cn.stdiot.JSONCall context = $;
String[] name = $.args.containsKey("name")? JSONObject.parseArray(((JSONArray)$.args.get("name")).toJSONString(), java.lang.String.class).toArray(new java.lang.String[0]):new java.lang.String[0];
retValue = proxy.help(context, name);
break;
}
case "shutdown" :{
cn.stdiot.JSONCall context = $;
org.bson.Document option = JSON.parseObject(JSON.toJSONString($.args.get("option")), org.bson.Document.class);
retValue = proxy.shutdown(context, option);
break;
}
case "get" :{
cn.stdiot.JSONCall context = $;
String[] property = $.args.containsKey("property")? JSONObject.parseArray(((JSONArray)$.args.get("property")).toJSONString(), java.lang.String.class).toArray(new java.lang.String[0]):new java.lang.String[0];
retValue = proxy.get(context, property);
break;
}
case "trigger" :{
cn.stdiot.JSONCall context = $;
org.bson.Document[] list = $.args.containsKey("list")? JSONObject.parseArray(((JSONArray)$.args.get("list")).toJSONString(), org.bson.Document.class).toArray(new org.bson.Document[0]):new org.bson.Document[0];
retValue = proxy.trigger(context, list);
break;
}
case "close" :{
cn.stdiot.JSONCall context = $;
org.bson.Document option = JSON.parseObject(JSON.toJSONString($.args.get("option")), org.bson.Document.class);
retValue = proxy.close(context, option);
break;
}
case "set" :{
cn.stdiot.JSONCall context = $;
org.bson.Document property = JSON.parseObject(JSON.toJSONString($.args.get("property")), org.bson.Document.class);
retValue = proxy.set(context, property);
break;
}
case "reset" :{
cn.stdiot.JSONCall context = $;
org.bson.Document option = JSON.parseObject(JSON.toJSONString($.args.get("option")), org.bson.Document.class);
retValue = proxy.reset(context, option);
break;
}
case "open" :{
cn.stdiot.JSONCall context = $;
org.bson.Document option = JSON.parseObject(JSON.toJSONString($.args.get("option")), org.bson.Document.class);
retValue = proxy.open(context, option);
break;
}
case "token" :{
cn.stdiot.JSONCall context = $;
org.bson.Document option = JSON.parseObject(JSON.toJSONString($.args.get("option")), org.bson.Document.class);
retValue = proxy.token(context, option);
break;
}
case "restart" :{
cn.stdiot.JSONCall context = $;
org.bson.Document option = JSON.parseObject(JSON.toJSONString($.args.get("option")), org.bson.Document.class);
retValue = proxy.restart(context, option);
break;
}
case "getEvent" :{
cn.stdiot.JSONCall context = $;
String[] type = $.args.containsKey("type")? JSONObject.parseArray(((JSONArray)$.args.get("type")).toJSONString(), java.lang.String.class).toArray(new java.lang.String[0]):new java.lang.String[0];
retValue = proxy.getEvent(context, type);
break;
}
default:{
break;
}
}
}
catch(Exception ex){
if(ex instanceof cn.stdiot.InvokeException){
cn.stdiot.InvokeException e = (cn.stdiot.InvokeException)ex;
errcode=e.errcode;
errmsg=e.getMessage();
}else{
errcode = "500";
if($.cmd.startsWith("constructor")){
errmsg = ex.toString();
}else{
errmsg = ex.toString();
}
}
}
cn.stdiot.JSONReturn ret= new cn.stdiot.JSONReturn($.tid, errcode, errmsg, retValue);
return ret;
}
}//end of class driver
| 41.859296 | 229 | 0.536615 |
c9985a61928d91d459aa9b651305171e6431612e | 1,231 | package com.dev.mytbt.Routing.APIs.OsrmAPI.ResponseModels;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Luís Henriques for MyTbt.
* 16-04-2018, 12:25
*/
@SuppressWarnings("UnusedDeclaration")
public class OsrmRoutes {
@SerializedName("geometry")
@Expose
private OsrmGeometry geometry;
@SerializedName("legs")
@Expose
private OsrmLegs[] legs;
@SerializedName("distance")
@Expose
private String distance;
@SerializedName("duration")
@Expose
private float duration;
public OsrmRoutes() {
}
public OsrmGeometry getGeometry() {
return geometry;
}
public void setGeometry(OsrmGeometry geometry) {
this.geometry = geometry;
}
public OsrmLegs[] getLegs() {
return legs;
}
public void setLegs(OsrmLegs[] legs) {
this.legs = legs;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public float getDuration() {
return duration;
}
public void setDuration(float duration) {
this.duration = duration;
}
}
| 19.234375 | 58 | 0.645816 |
553cbbc92c82dbcbc96684557fb86428ee14746d | 1,206 | package test.support;
public final class Category {
public static final String AUTH_TEST = "auth";
public static final String MULTI_AUTH_TEST = "multi-auth";
public static final String AMOEBA_TEST = "amoebadb";
public static final String CLINEPI_TEST = "clinepidb";
public static final String CRYPTO_TEST = "cryptodb";
public static final String EUPATH_TEST = "eupathdb";
public static final String FUNGI_TEST = "fungidb";
public static final String GIARDIA_TEST = "giardiadb";
public static final String MICROBIOME_TEST = "microbiomedb";
public static final String MICROSPORIDIA_TEST = "microsporidiadb";
public static final String ORTHOMCL_TEST = "orthomcl";
public static final String PIROPLASMA_TEST = "piroplasmadb";
public static final String PLASMO_TEST = "plasmodb";
public static final String TOXO_TEST = "toxodb";
public static final String TRICH_TEST = "trichdb";
public static final String TRITRYP_TEST = "tritrypdb";
public static final String PUBLIC_STRATEGIES_TEST = "public-strategies";
private Category() {}
}
| 44.666667 | 74 | 0.679104 |
68274c12da6e6705298a1646f4aeafe6fff7453c | 4,445 | package ch.uhlme.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import java.util.SplittableRandom;
public class FileUtils {
private static final SplittableRandom random = new SplittableRandom();
private FileUtils() {}
/**
* Delete a path including all subdirectories and files recursively. It also works if called on
* just a file. Note: if an exception occurs, some files/folders might already be deleted.
*
* @param path path to delete
* @throws IOException if any file/folder cannot be deleted.
*/
public static void deleteRecursive(Path path) throws IOException {
Files.walkFileTree(
path,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Checks if the lines in a file are sorted (using the default comparator).
*
* @param path file to check
* @return true if sorted, false otherwise
* @throws IOException if an error occurs while reading the file.
*/
public static boolean areLinesInFileSorted(Path path) throws IOException {
Objects.requireNonNull(path);
try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String previousLine = ""; // NOPMD
String currentLine = br.readLine();
while (currentLine != null) {
if (previousLine.compareTo(currentLine) > 0) {
return false;
}
previousLine = currentLine; // NOPMD
currentLine = br.readLine();
}
}
return true;
}
/**
* Generates a file containing random lines. Each line consists of 100 random characters between
* a-z
*
* @param path file to generate
* @param lines number of lines to generate
* @throws IOException if an error occurs during writing the file
* @throws IllegalArgumentException if the number of lines is not positive
*/
public static void generateFileWithRandomLines(Path path, long lines) throws IOException {
Objects.requireNonNull(path);
if (lines <= 0) {
throw new IllegalArgumentException("lines must be positive");
}
try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
for (int i = 0; i < lines; i++) {
bw.write(randomLine());
bw.newLine();
}
bw.flush();
}
}
private static String randomLine() {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
int targetStringLength = 100;
return random
.ints(leftLimit, rightLimit + 1)
.limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
/**
* Takes a path and returns the same path with a suffix inserted in the filename, respecting
* fileextension. It handles files with extensions, files that have only an extension as well as
* files without an extension.
*
* <p>Examples (with suffix _1:
*
* <ul>
* <li>input.txt - input_1.txt
* <li>.gitignore - _1.gitignore
* <li>input - input_1
* </ul>
*
* @param path path of the file
* @param suffix suffix to insert
* @return path with the file containing the suffix
*/
public static Path getPathWithSuffixInFilename(Path path, String suffix) {
Objects.requireNonNull(path);
Objects.requireNonNull(suffix);
int fileExtensionPosition = path.toString().lastIndexOf('.');
String filename;
if (fileExtensionPosition > -1) {
filename = path.toString().substring(0, fileExtensionPosition);
filename += suffix;
filename += path.toString().substring(fileExtensionPosition);
} else {
filename = path.toString() + suffix;
}
return Paths.get(filename);
}
}
| 30.868056 | 99 | 0.670191 |
732995a0a8527738317969a4686e37fedf4fa892 | 5,126 | package com.home.shine.utils;
import com.home.shine.data.BaseData;
import com.home.shine.dataEx.VInt;
import com.home.shine.dataEx.VObj;
import com.home.shine.support.collection.IntList;
import com.home.shine.support.collection.IntObjectMap;
import com.home.shine.support.collection.LongObjectMap;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
/** 其他方法 */
public class OtherUtils
{
/** 数组相等比较 */
public static boolean dataArrEquals(BaseData[] arr1,BaseData[] arr2)
{
if(arr1==null || arr2==null)
return false;
int len;
if((len=arr1.length)!=arr2.length)
return false;
for(int i=0;i<len;i++)
{
if(!arr1[i].dataEquals(arr2[i]))
return false;
}
return true;
}
/** 移除不存在的项,从字典1,参考字典2 */
public static <T1,T2> void removeNotExistFromDic1WithDic2(IntObjectMap<T1> dic1,IntObjectMap<T2> dic2)
{
int[] keys=dic1.getKeys();
int fv=dic1.getFreeValue();
int k;
for(int i=keys.length-1;i>=0;--i)
{
if((k=keys[i])!=fv)
{
if(!dic2.contains(k))
{
dic1.remove(k);
++i;
}
}
}
}
/** 在字典中找寻最小的Key */
public static <T> int findLeastOfDic(IntObjectMap<T> dic,Comparator<T> compare)
{
VObj<T> temp=new VObj<>();
VInt re=new VInt(-1);
dic.forEach((k,v)->
{
if(temp.value==null)
{
temp.value=v;
re.value=k;
}
else
{
if(compare.compare(temp.value,v)<0)
{
temp.value=v;
re.value=k;
}
}
});
return re.value;
}
/** 在字典中找寻最小的 */
public static <T> long findLeastOfDic(LongObjectMap<T> dic,Comparator<T> compare)
{
long[] keys=dic.getKeys();
T[] values=dic.getValues();
long fv=dic.getFreeValue();
long k;
T v;
T temp=null;
long re=-1;
for(int i=keys.length-1;i>=0;--i)
{
if((k=keys[i])!=fv)
{
v=values[i];
if(temp==null)
{
temp=v;
re=k;
}
else
{
if(compare.compare(temp,v)<0)
{
temp=v;
re=k;
}
}
}
}
return re;
}
/** 将元素放入有尺寸限制的集合中 */
public static <T> void putObjInDicWithMax(int key,T obj,IntObjectMap<T> dic,int max,Comparator<T> compare)
{
if(max<=0)
{
dic.put(key,obj);
}
else
{
if(dic.contains(key))
{
dic.put(key,obj);
}
else
{
if(dic.size()>=max)
{
int leastKey=findLeastOfDic(dic,compare);
dic.remove(leastKey);
}
dic.put(key,obj);
}
}
}
/** 将元素放入有尺寸限制的集合中 */
public static <T> void putObjInDicWithMax(long key,T obj,LongObjectMap<T> dic,int max,Comparator<T> compare)
{
if(max<=0)
{
dic.put(key,obj);
}
else
{
if(dic.contains(key))
{
dic.put(key,obj);
}
else
{
if(dic.size()>=max)
{
long leastKey=findLeastOfDic(dic,compare);
dic.remove(leastKey);
}
dic.put(key,obj);
}
}
}
/** 获得第一个非回环的ip */
public static String getIp() throws SocketException
{
Enumeration en = NetworkInterface.getNetworkInterfaces();
List<String> ips = new ArrayList<>();
while (en.hasMoreElements()) {
NetworkInterface i = (NetworkInterface) en.nextElement();
for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr = (InetAddress) en2.nextElement();
if (!addr.isLoopbackAddress()) {
if (addr instanceof Inet4Address) {
ips.add(addr.getHostAddress());
}
}
}
}
ips.sort(Comparator.naturalOrder());
return ips.get(0);
}
public static <T> T getLastFromDic(IntObjectMap<T> intObjectMap)
{
if(intObjectMap.length()<1)
{
return null;
}
IntList sortedKeyList=intObjectMap.getSortedKeyList();
int lastId=sortedKeyList.get(sortedKeyList.length() - 1);
return intObjectMap.get(lastId);
}
public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
double ew1, ns1, ew2, ns2;
double distance;
// 角度转换为弧度
// PI/180.0
double DEF_PI180=Math.PI / 180;
ew1 = lng1 * DEF_PI180;
ns1 = lat1 * DEF_PI180;
ew2 = lng2 * DEF_PI180;
ns2 = lat2 * DEF_PI180;
// 求大圆劣弧与球心所夹的角(弧度)
distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1) * Math.cos(ns2) * Math.cos(ew1 - ew2);
// 调整到[-1..1]范围内,避免溢出
if (distance > 1.0){
distance = 1.0;
} else if (distance < -1.0){
distance = -1.0;
}
// 求大圆劣弧长度
// 地球半径
double DEF_R=6370693.5;
distance = DEF_R * Math.acos(distance);
return distance;
}
/**
* 通过经纬度获取距离 小于 (单位:公里)
*
* @param lat1
* @param lng1
* @param lat2
* @param lng2
* @param kilometre 距离 公里
* @return
*/
public static boolean distanceLessThan(double lat1,double lng1,double lat2,double lng2,int kilometre ){
return OtherUtils.getDistance(lat1,lng1,lat2,lng2)<=kilometre*1000;
}
}
| 20.023438 | 110 | 0.590519 |
c52fdb470593b3cf6085e17ec5ee1ae677765610 | 7,521 | package org.sil.bloom.reader;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import static org.sil.bloom.reader.models.BookCollection.getLocalBooksDirectory;
public class ImportBundleTask extends AsyncTask<Uri, String, Void> {
private final WeakReference<MainActivity> mainActivityRef;
private final Toast toast;
private final List<String> newBookPaths;
private final List<Uri> bundlesToCleanUp;
private final ImportBundleErrorHandler importBundleErrorHandler;
@SuppressLint("ShowToast")
ImportBundleTask(MainActivity mainActivity) {
// See https://stackoverflow.com/questions/44309241/warning-this-asynctask-class-should-be-static-or-leaks-might-occur/46166223#46166223
this.mainActivityRef = new WeakReference<>(mainActivity);
// Using a single toast object allows us to update the message immediately
this.toast = Toast.makeText(mainActivity, "", Toast.LENGTH_SHORT);
this.newBookPaths = new ArrayList<>();
this.bundlesToCleanUp = new ArrayList<>();
this.importBundleErrorHandler = new ImportBundleErrorHandler(mainActivity, toast); // setup ErrorHandler object
}
protected Void doInBackground(Uri... bundleUris) {
try {
for(Uri bloomBundleUri : bundleUris) {
extractBloomBundle(bloomBundleUri);
bundlesToCleanUp.add(bloomBundleUri);
}
}
catch (IOException e) {
// The exception is already handled by the importBundleErrorHandler,
// but we need the catch phrase here to satisfy the compiler.
}
return null;
}
protected void onProgressUpdate(String... filenames) {
// get a reference to the activity if it is still there
MainActivity mainActivity = mainActivityRef.get();
if (mainActivity == null || mainActivity.isFinishing())
return;
String toastMessage = mainActivity.getString(R.string.adding_book, filenames[0]);
toast.setText(toastMessage);
toast.show();
}
protected void onPostExecute(Void v) {
// get a reference to the activity if it is still there
MainActivity mainActivity = mainActivityRef.get();
if (mainActivity == null || mainActivity.isFinishing())
return;
if (newBookPaths.size() > 0)
mainActivity.reloadBookList();
if (importBundleErrorHandler.hasErrors()) {
importBundleErrorHandler.toastErrors();
}
new FileCleanupTask(mainActivity).execute(bundlesToCleanUp.toArray(new Uri[0]));
}
private void extractBloomBundle(Uri bloomBundleUri) throws IOException {
// get a reference to the activity if it is still there
MainActivity mainActivity = mainActivityRef.get();
if (mainActivity == null || mainActivity.isFinishing())
return;
TarArchiveInputStream tarInput = null;
try {
InputStream fs = mainActivity.getContentResolver().openInputStream(bloomBundleUri);
tarInput = new TarArchiveInputStream(fs);
final String booksDirectoryPath = getLocalBooksDirectory().getAbsolutePath();
ArchiveEntry entry;
while ((entry = tarInput.getNextEntry()) != null) {
publishProgress(entry.getName());
newBookPaths.add(IOUtilities.extractTarEntry(tarInput, booksDirectoryPath));
}
tarInput.close();
if (newBookPaths.isEmpty()) {
importBundleErrorHandler.addErrorUri(bloomBundleUri, null);
}
} catch (IOException e) {
// It could be that a .bloombundle.enc file really is still uuencoded I suppose.
// Or the file could have been corrupted.
if (tarInput != null)
tarInput.close();
if (bloomBundleUri != null)
importBundleErrorHandler.addErrorUri(bloomBundleUri, e);
}
}
private class ImportBundleErrorHandler {
WeakReference<MainActivity> mMainActivityRef;
Toast mToast;
List<ImportErrorObject> mImportErrors;
ImportBundleErrorHandler(MainActivity mainActivity, Toast toastSingleton) {
mToast = toastSingleton;
mMainActivityRef = new WeakReference<>(mainActivity);
mImportErrors = new ArrayList<>();
}
private boolean hasErrors() {
return mImportErrors.size() > 0;
}
private void toastErrors() {
MainActivity activity = mainActivityRef.get();
if (activity == null || activity.isFinishing())
return;
// Usually there will only be one... but be prepared.
for(ImportErrorObject importError : mImportErrors) {
reportSingleError(activity, importError);
}
}
private void reportSingleError(MainActivity activity, ImportErrorObject importError) {
String toastMessage;
String bundleName = importError.getBundleName();
if (importError.mException == null) {
Log.e("BundleIO", "Imported bloom bundle, but got no books. Probably " +
importError.getBundleName() + " was a corrupt file.");
toastMessage = activity.getString(R.string.bundle_import_error, bundleName);
} else {
IOException exception = importError.mException;
Log.e("BundleIO", "IO exception reading bloom bundle " +
importError.getBundleName() + ": " + exception.getMessage());
importError.mException.printStackTrace();
if (importError.mException.getMessage() != null &&
importError.mException.getMessage().contains("ENOSPC")) {
toastMessage = activity.getString(R.string.bundle_import_out_of_space);
} else {
toastMessage = activity.getString(R.string.bundle_import_error, bundleName);
}
// IOExceptions skip the file cleanup; so do it now.
new FileCleanupTask(activity).execute(importError.mUri);
}
// Trying to use the same member variable Toast for multiple error toasts only showed
// the last one. Also, we want a longer duration for these error messages.
Toast toast = Toast.makeText(activity, toastMessage, Toast.LENGTH_LONG);
toast.show();
}
private void addErrorUri(Uri bloomBundleUri, IOException e) {
mImportErrors.add(new ImportErrorObject(bloomBundleUri, e));
}
}
private static class ImportErrorObject {
private final Uri mUri;
private final IOException mException;
ImportErrorObject(Uri uri, IOException exc) {
mUri = uri;
mException = exc;
}
String getBundleName() {
String path = mUri.getEncodedPath();
return (path != null && path.contains("/")) ? Uri.decode(path.substring(path.lastIndexOf("/") + 1)) : "";
}
}
} | 40.875 | 144 | 0.637814 |
ce0a286befb3dff62627c7fd9e413ce6637a466c | 2,948 | package com.showcast.hvscroll.touchhelper;
/**
* Created by taro on 16/8/21.
*/
public class ClickPointComputeHelper {
private float mCellWidth;
private float mCellHeight;
private float mIntervalInWidth;
private float mIntervalInHeight;
private float mPaddingLeft;
private float mPaddingRight;
private float mPaddingTop;
private float mPaddingBottom;
public ClickPointComputeHelper() {
}
public ClickPointComputeHelper(float width, float height) {
this();
if (this.setParams(width, height, 0, 0)) {
throw new IllegalArgumentException("argument illegal,width and height must not be 0 or negative integer");
}
}
public boolean setPadding(float left, float top, float right, float bottom) {
if (left < 0 || top < 0 || right < 0 || bottom < 0) {
return false;
} else {
this.mPaddingLeft = left;
this.mPaddingTop = top;
this.mPaddingRight = right;
this.mPaddingBottom = bottom;
return true;
}
}
public boolean setParams(float cellWidth, float cellHeight, float intervalWidth, float intervalHeight) {
if (cellWidth <= 0 || cellHeight <= 0 || intervalWidth < 0 || intervalHeight < 0) {
return false;
}
this.mCellWidth = cellWidth;
this.mCellHeight = cellHeight;
this.mIntervalInWidth = intervalWidth;
this.mIntervalInHeight = intervalHeight;
return true;
}
public int computeClickXFromFirstLine(float y, float offsetY, float ignoreY, int maxRowCount) {
float remainX = y - mPaddingTop - ignoreY - offsetY;
int cellX = 0;
//out of click area
if (remainX < 0) {
return -1;
}
cellX = (int) (remainX / (mCellHeight + mIntervalInHeight));
return cellX >= maxRowCount ? -1 : cellX;
}
public int computeClickYFromFirstLine(float x, float offsetX, float ignoreX, int maxColumnCount) {
float remainY = x - mPaddingLeft - ignoreX - offsetX;
int cellY = 0;
if (remainY < 0) {
return -1;
}
cellY = (int) (remainY / (mCellWidth + mIntervalInWidth));
return cellY >= maxColumnCount ? -1 : cellY;
}
public int computeClickXFromMiddle(float x, float middleX, float leftStart, float rightStart) {
float remainX = Math.abs(x - middleX);
float start = 0;
int offsetMiddle = 0;
if (remainX <= 0) {
return offsetMiddle;
}
start = x - middleX < 0 ? leftStart : rightStart;
remainX -= start;
while (remainX > mPaddingLeft) {
remainX -= mCellWidth;
remainX -= mIntervalInWidth;
offsetMiddle++;
}
if (remainX + mIntervalInWidth > 0) {
return -1;
} else {
return offsetMiddle - 1;
}
}
}
| 32.395604 | 118 | 0.592266 |
d22b78ba2143833c2de2f883994b25eded5b2cb6 | 2,240 | package com.topway.fine.xml;
import com.topway.fine.model.CityModel;
import com.topway.fine.model.DistrictModel;
import com.topway.fine.model.ProvinceModel;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
/**
* 全国省市县XML文件解析器
*
* @author [email protected]
* @version 1.0
* @created 2016-3-1
*/
public class CityXmlParser extends DefaultHandler {
/**
* 存储所有的解析对象
*/
private List<ProvinceModel> provinceList = new ArrayList<ProvinceModel>();
public CityXmlParser() {
}
public List<ProvinceModel> getDataList() {
return provinceList;
}
@Override
public void startDocument() throws SAXException {
}
ProvinceModel province = new ProvinceModel();
CityModel city = new CityModel();
DistrictModel district = new DistrictModel();
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("province")) {
province = new ProvinceModel();
province.setName(attributes.getValue(0));
province.setCityList(new ArrayList<CityModel>());
} else if (qName.equals("city")) {
city = new CityModel();
city.setName(attributes.getValue(0));
city.setDistrictList(new ArrayList<DistrictModel>());
} else if (qName.equals("district")) {
district = new DistrictModel();
district.setName(attributes.getValue(0));
district.setZipcode(attributes.getValue(1));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// 遇到结束标记的时候,会调用这个方法
if (qName.equals("district")) {
city.getDistrictList().add(district);
} else if (qName.equals("city")) {
province.getCityList().add(city);
} else if (qName.equals("province")) {
provinceList.add(province);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
}
}
| 27.654321 | 78 | 0.632589 |
249aa994ee08fa34e0cdd16cd92106bc65e57bd2 | 5,471 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2022 TweetWallFX
*
* 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.tweetwallfx.devoxx.api.cfp.client.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import jakarta.ws.rs.ProcessingException;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class RestCallHelper {
private static final Logger LOGGER = LogManager.getLogger(RestCallHelper.class);
private RestCallHelper() {
// prevent instantiation
}
private static Client getClient() {
return ClientBuilder.newClient();
}
private static String getHttpsUrl(final String url) {
Objects.requireNonNull(url, "url parameter must not be null!");
if (url.startsWith("http:")) {
return url.replaceAll("^http:", "https:");
} else {
return url;
}
}
private static Response getResponse(final String url, final Map<String, Object> queryParameters) {
LOGGER.info("Calling URL: {} with query parameters: {}", url, queryParameters);
WebTarget webTarget = getClient().target(getHttpsUrl(url));
if (null != queryParameters && !queryParameters.isEmpty()) {
for (Map.Entry<String, Object> entry : queryParameters.entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();
webTarget = switch(value) {
case Object[] array -> webTarget.queryParam(key, array);
case Collection<?> collection -> webTarget.queryParam(key, collection.toArray());
default -> webTarget.queryParam(key, value);
};
}
}
final Response response = webTarget
.request(MediaType.APPLICATION_JSON)
.get();
LOGGER.info("Received Response: {}", response);
return response;
}
public static Optional<Response> getOptionalResponse(final String url, final Map<String, Object> queryParameters) {
try {
return Optional.ofNullable(getResponse(url, queryParameters));
} catch (final ProcessingException pe) {
LOGGER.error("Encountered ProcessingException while calling to '" + url + "'", pe);
return Optional.empty();
}
}
public static Optional<Response> getOptionalResponse(final String url) {
return getOptionalResponse(url, Collections.emptyMap());
}
public static <T> Optional<T> readOptionalFrom(final Response response, final Class<T> typeClass) {
return Optional.of(Objects.requireNonNull(response, "Parameter response must not be null!"))
.filter(r -> Response.Status.OK.getStatusCode() == r.getStatus())
.map(r -> r.readEntity(typeClass));
}
public static <T> Optional<T> readOptionalFrom(final Response response, final GenericType<T> genericType) {
return Optional.of(Objects.requireNonNull(response, "Parameter response must not be null!"))
.filter(r -> Response.Status.OK.getStatusCode() == r.getStatus())
.map(r -> r.readEntity(genericType));
}
public static <T> Optional<T> readOptionalFrom(final String url, final Class<T> typeClass) {
return readOptionalFrom(url, null, typeClass);
}
public static <T> Optional<T> readOptionalFrom(final String url, final Map<String, Object> queryParameters, final Class<T> typeClass) {
return getOptionalResponse(url, queryParameters)
.flatMap(response -> readOptionalFrom(response, typeClass));
}
public static <T> Optional<T> readOptionalFrom(final String url, final GenericType<T> genericType) {
return readOptionalFrom(url, null, genericType);
}
public static <T> Optional<T> readOptionalFrom(final String url, final Map<String, Object> queryParameters, final GenericType<T> genericType) {
return getOptionalResponse(url, queryParameters)
.flatMap(response -> readOptionalFrom(response, genericType));
}
}
| 42.084615 | 147 | 0.681594 |
bb5b9270be8309b445ea5263e11fa51b350b82fc | 8,846 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* rendererFrame.java
*
* Created on 8-ago-2009, 15.35.11
*/
package java4d.graphicRenderer;
import com.jogamp.opengl.util.Animator;
import javax.media.opengl.awt.GLJPanel;
/**
*
* @author Pierantonio
*/
public class myRendererFrame extends javax.swing.JFrame {
private Animator anim;
private myGlEventListener listener;
/** Creates new form rendererFrame */
public myRendererFrame() {
initComponents();
listener=new myGlEventListener(this);
gLJPanel1.addGLEventListener(listener);
anim=new Animator(gLJPanel1);
}
public void startAnimator()
{
anim.start();
}
public void stopAnimator()
{
anim.stop();
}
public myGlEventListener getGlEventListener()
{
return listener;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenu1 = new javax.swing.JMenu();
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem2 = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem3 = new javax.swing.JCheckBoxMenuItem();
gLJPanel1 = new GLJPanel();
jMenu1.setText("jMenu1");
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("MESH objects");
jCheckBoxMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/java4d/images/iconMESH.png"))); // NOI18N
jCheckBoxMenuItem1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBoxMenuItem1ItemStateChanged(evt);
}
});
jMenu1.add(jCheckBoxMenuItem1);
jCheckBoxMenuItem2.setSelected(true);
jCheckBoxMenuItem2.setText("DUMY objects");
jCheckBoxMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/java4d/images/iconDUMY.png"))); // NOI18N
jCheckBoxMenuItem2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBoxMenuItem2ItemStateChanged(evt);
}
});
jMenu1.add(jCheckBoxMenuItem2);
jCheckBoxMenuItem3.setSelected(true);
jCheckBoxMenuItem3.setText("LITE objects");
jCheckBoxMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/java4d/images/iconLITE.png"))); // NOI18N
jCheckBoxMenuItem3.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBoxMenuItem3ItemStateChanged(evt);
}
});
jMenu1.add(jCheckBoxMenuItem3);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
gLJPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
gLJPanel1.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
gLJPanel1MouseWheelMoved(evt);
}
});
gLJPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
gLJPanel1MouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
gLJPanel1MousePressed(evt);
}
});
gLJPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
gLJPanel1MouseDragged(evt);
}
});
javax.swing.GroupLayout gLJPanel1Layout = new javax.swing.GroupLayout(gLJPanel1);
gLJPanel1.setLayout(gLJPanel1Layout);
gLJPanel1Layout.setHorizontalGroup(
gLJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 529, Short.MAX_VALUE)
);
gLJPanel1Layout.setVerticalGroup(
gLJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 372, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(gLJPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(gLJPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// <editor-fold defaultstate="collapsed" desc="gLJPanel mouse handling">
private int axtmp,aytmp,axstart,aystart;
private int txtmp,tytmp,txstart,tystart;
private void gLJPanel1MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_gLJPanel1MouseWheelMoved
listener.dist+=evt.getWheelRotation() * 50;
}//GEN-LAST:event_gLJPanel1MouseWheelMoved
@SuppressWarnings("static-access")
private void gLJPanel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gLJPanel1MouseDragged
if(evt.getModifiers()==evt.BUTTON1_MASK)
{
listener.anglex=(axtmp+(axstart - evt.getX())) % 360;
listener.angley=(aytmp+(aystart - evt.getY()))% 360;
}
if(evt.getModifiers()==evt.BUTTON3_MASK)
{
listener.transpx=txtmp+(txstart - evt.getX());
listener.transpy=tytmp+(tystart - evt.getY());
}
}//GEN-LAST:event_gLJPanel1MouseDragged
@SuppressWarnings("static-access")
private void gLJPanel1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gLJPanel1MousePressed
txstart=axstart=evt.getX();
tystart=aystart=evt.getY();
axtmp=listener.anglex;
aytmp=listener.angley;
txtmp=listener.transpx;
tytmp=listener.transpy;
}//GEN-LAST:event_gLJPanel1MousePressed
private void jCheckBoxMenuItem1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem1ItemStateChanged
if(evt.getStateChange() == evt.SELECTED)
{listener.paintmesh=true;
}else{
listener.paintmesh=false;
}
listener.updateRendering();
}//GEN-LAST:event_jCheckBoxMenuItem1ItemStateChanged
private void jCheckBoxMenuItem2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem2ItemStateChanged
if(evt.getStateChange() == evt.SELECTED)
{listener.paintdumy=true;
}else{
listener.paintdumy=false;
}
listener.updateRendering();
}//GEN-LAST:event_jCheckBoxMenuItem2ItemStateChanged
private void jCheckBoxMenuItem3ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem3ItemStateChanged
if(evt.getStateChange() == evt.SELECTED)
{listener.paintlite=true;
}else{
listener.paintlite=false;
}
listener.updateRendering();
}//GEN-LAST:event_jCheckBoxMenuItem3ItemStateChanged
private void gLJPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gLJPanel1MouseClicked
if(evt.getButton()==evt.BUTTON3)
{
jMenu1.getPopupMenu().show(this, evt.getXOnScreen()-this.getX() , evt.getYOnScreen()-this.getY());
}
}//GEN-LAST:event_gLJPanel1MouseClicked
// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new myRendererFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private GLJPanel gLJPanel1;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem2;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem3;
private javax.swing.JMenu jMenu1;
// End of variables declaration//GEN-END:variables
}
| 37.483051 | 135 | 0.672846 |
fbb3e66426e2bef7b0cabaf8d1603149e8e18b54 | 4,485 | package com.codingyun.core.service.impl;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.codingyun.core.service.UploadFileService;
@Service
public class UploadFileServiceImpl implements UploadFileService {
private Logger logger = Logger.getLogger(this.getClass());
@Override
public boolean uploadFile(String destinationDir, MultipartFile file, String filename)
throws Exception {
logger.info("文件长度: " + file.getSize());
logger.info("文件类型: " + file.getContentType());
logger.info("文件名称: " + file.getName());
logger.info("文件原名: " + file.getOriginalFilename());
logger.info("========================================");
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
// FileUtils.copyInputStreamToFile(commentInfo.getAudioFile().getInputStream(),
// new File(realPath, commentInfo.getAudioFile().getOriginalFilename()));
try {
SaveFileFromInputStream(file.getInputStream(), destinationDir, filename);
} catch (IOException e) {
logger.info(e.getMessage());
return false;
}
return true;
}
/**保存文件
* @param stream
* @param path
* @param filename
* @throws IOException
*/
private void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException
{
// path = "E:/test"; //test
FileOutputStream outputStream = new FileOutputStream( path + "/"+ filename);
// byte[] buffer =new byte[1024*1024];
// int byteread = 0;
// while ((byteread=stream.read(buffer))!=-1)
// {
// byteread += byteread;
// outputStream.write(buffer,0,byteread);
// outputStream.flush();
// }
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = stream.read(bytes)) != -1){
outputStream.write(bytes, 0, byteCount);
}
outputStream.close();
stream.close();
}
@Override
public boolean uploadHandoutImg(String destinationDir, MultipartFile file,
String filename, int widthTarget) throws Exception {
logger.info("文件长度: " + file.getSize());
logger.info("文件类型: " + file.getContentType());
logger.info("文件名称: " + file.getName());
logger.info("文件原名: " + file.getOriginalFilename());
logger.info("========================================");
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
// FileUtils.copyInputStreamToFile(commentInfo.getAudioFile().getInputStream(),
// new File(realPath, commentInfo.getAudioFile().getOriginalFilename()));
try {
SaveImgFromInputStream(file.getInputStream(), destinationDir, filename, widthTarget);
} catch (IOException e) {
logger.info(e.getMessage());
return false;
}
return true;
}
/**
* 缩放图像
* @param scale 缩放比例
* @param flag 缩放选择:true 放大; false 缩小;
*/
private void SaveImgFromInputStream(InputStream stream, String path, String filename, int widthTarget) throws IOException{
// path = "E:/test"; //test
FileOutputStream outputStream = new FileOutputStream( path + "/"+ filename);
BufferedImage src = ImageIO.read(stream);
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
double scale = Double.parseDouble(new java.text.DecimalFormat("#.0000").format((double)width/(double)widthTarget));
if (scale > 1){
// 缩小
width = widthTarget;
height = (int) ((double)height / scale);
}else{
// 放大
// width = width * scale;
// height = height * scale;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(path + "/"+ filename));// 输出到文件流
outputStream.close();
stream.close();
}
}
| 36.463415 | 135 | 0.631884 |
b6d43449b94a9baa1b9648db5839fb0c48691aee | 1,971 | package com.eliteams.quick4j.core.util;
import java.io.*;
/**
* @author wyx
* @date 2020/12/5
* @Time 22:56
*/
public class FileUtils {
public static void readFile(File readFile,File writeFile){
FileInputStream fileInputStream = null;
BufferedReader br =null;
FileOutputStream fileOutputStream = null;
BufferedWriter bw = null;
String line = null;
StringBuilder sb ;
//
int startIndex = 0;
int endIndex = 0;
try {
fileInputStream = new FileInputStream(readFile);
fileOutputStream = new FileOutputStream(writeFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream,"UTF-8"));
br = new BufferedReader(new InputStreamReader(fileInputStream));
int i = 0;
while((line = br.readLine()) != null){
i = i+1;
line = line.replace("( SEQ_ID,","( ");
startIndex = line.indexOf("VALUES (");
endIndex = line.indexOf(",",startIndex);//第26个
sb = new StringBuilder(line);
sb.delete(startIndex+8,endIndex+1);
//System.out.println("写入:"+sb.toString());
writer.append(sb.toString());
sb = null;
writer.append("\r\n");
sb = null;
}
writer.close();
br.close();
fileInputStream.close();
} catch (Exception e){
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) {
// readFile(new File("C:\\Users\\Administrator\\Desktop\\sql\\ZJ_BANK_VOUCHER_PUSH_LOG.sql"));
readFile(new File("C:\\Users\\Administrator\\Desktop\\sql\\ZJJH_ZJ_ORG_PAID_IN_DAILY2020-12-08.sql"),
new File("C:\\Users\\Administrator\\Desktop\\sql\\ZJJH_ZJ_ORG_PAID_IN_DAILY2020-12-08.new.sql"));
}
}
| 33.982759 | 113 | 0.55657 |
1c253384903b79fc4f82c9153953616b664d7147 | 11,170 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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 io.netty.handler.logging;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
import io.netty.buffer.DefaultByteBufHolder;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.slf4j.Logger.ROOT_LOGGER_NAME;
/**
* Verifies the correct functionality of the {@link LoggingHandler}.
*/
public class LoggingHandlerTest {
private static final String LOGGER_NAME = LoggingHandler.class.getName();
private static final Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER_NAME);
private static final Logger logger = (Logger) LoggerFactory.getLogger(LOGGER_NAME);
private static final List<Appender<ILoggingEvent>> oldAppenders = new ArrayList<>();
/**
* Custom logback appender which gets used to match on log messages.
*/
private Appender<ILoggingEvent> appender;
@BeforeClass
public static void beforeClass() {
for (Iterator<Appender<ILoggingEvent>> i = rootLogger.iteratorForAppenders(); i.hasNext();) {
Appender<ILoggingEvent> a = i.next();
oldAppenders.add(a);
rootLogger.detachAppender(a);
}
Unpooled.buffer();
}
@AfterClass
public static void afterClass() {
for (Appender<ILoggingEvent> a: oldAppenders) {
rootLogger.addAppender(a);
}
}
@Before
@SuppressWarnings("unchecked")
public void setup() {
appender = mock(Appender.class);
logger.addAppender(appender);
}
@After
public void teardown() {
logger.detachAppender(appender);
}
@Test(expected = NullPointerException.class)
public void shouldNotAcceptNullLogLevel() {
LogLevel level = null;
new LoggingHandler(level);
}
@Test
public void shouldApplyCustomLogLevel() {
LoggingHandler handler = new LoggingHandler(LogLevel.INFO);
assertEquals(LogLevel.INFO, handler.level());
}
@Test
public void shouldLogChannelActive() {
new EmbeddedChannel(new LoggingHandler());
verify(appender).doAppend(argThat(new RegexLogMatcher(".+ACTIVE$")));
}
@Test
public void shouldLogChannelWritabilityChanged() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
// this is used to switch the channel to become unwritable
channel.config().setWriteBufferLowWaterMark(5);
channel.config().setWriteBufferHighWaterMark(10);
channel.write("hello", channel.newPromise());
verify(appender).doAppend(argThat(new RegexLogMatcher(".+WRITABILITY CHANGED$")));
}
@Test
public void shouldLogChannelRegistered() {
new EmbeddedChannel(new LoggingHandler());
verify(appender).doAppend(argThat(new RegexLogMatcher(".+REGISTERED$")));
}
@Test
public void shouldLogChannelClose() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.close().await();
verify(appender).doAppend(argThat(new RegexLogMatcher(".+CLOSE$")));
}
@Test
public void shouldLogChannelConnect() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.connect(new InetSocketAddress(80)).await();
verify(appender).doAppend(argThat(new RegexLogMatcher(".+CONNECT: 0.0.0.0/0.0.0.0:80$")));
}
@Test
public void shouldLogChannelConnectWithLocalAddress() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.connect(new InetSocketAddress(80), new InetSocketAddress(81)).await();
verify(appender).doAppend(argThat(new RegexLogMatcher(
"^\\[id: 0xembedded, L:embedded - R:embedded\\] CONNECT: 0.0.0.0/0.0.0.0:80, 0.0.0.0/0.0.0.0:81$")));
}
@Test
public void shouldLogChannelDisconnect() throws Exception {
EmbeddedChannel channel = new DisconnectingEmbeddedChannel(new LoggingHandler());
channel.connect(new InetSocketAddress(80)).await();
channel.disconnect().await();
verify(appender).doAppend(argThat(new RegexLogMatcher(".+DISCONNECT$")));
}
@Test
public void shouldLogChannelInactive() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.pipeline().fireChannelInactive();
verify(appender).doAppend(argThat(new RegexLogMatcher(".+INACTIVE$")));
}
@Test
public void shouldLogChannelBind() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.bind(new InetSocketAddress(80));
verify(appender).doAppend(argThat(new RegexLogMatcher(".+BIND: 0.0.0.0/0.0.0.0:80$")));
}
@Test
@SuppressWarnings("RedundantStringConstructorCall")
public void shouldLogChannelUserEvent() throws Exception {
String userTriggered = "iAmCustom!";
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.pipeline().fireUserEventTriggered(new String(userTriggered));
verify(appender).doAppend(argThat(new RegexLogMatcher(".+USER_EVENT: " + userTriggered + '$')));
}
@Test
public void shouldLogChannelException() throws Exception {
String msg = "illegalState";
Throwable cause = new IllegalStateException(msg);
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.pipeline().fireExceptionCaught(cause);
verify(appender).doAppend(argThat(new RegexLogMatcher(
".+EXCEPTION: " + cause.getClass().getCanonicalName() + ": " + msg + '$')));
}
@Test
public void shouldLogDataWritten() throws Exception {
String msg = "hello";
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.writeOutbound(msg);
verify(appender).doAppend(argThat(new RegexLogMatcher(".+WRITE: " + msg + '$')));
verify(appender).doAppend(argThat(new RegexLogMatcher(".+FLUSH$")));
}
@Test
public void shouldLogNonByteBufDataRead() throws Exception {
String msg = "hello";
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.writeInbound(msg);
verify(appender).doAppend(argThat(new RegexLogMatcher(".+READ: " + msg + '$')));
String handledMsg = channel.readInbound();
assertThat(msg, is(sameInstance(handledMsg)));
assertThat(channel.readInbound(), is(nullValue()));
}
@Test
public void shouldLogByteBufDataRead() throws Exception {
ByteBuf msg = Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.writeInbound(msg);
verify(appender).doAppend(argThat(new RegexLogMatcher(".+READ: " + msg.readableBytes() + "B$")));
ByteBuf handledMsg = channel.readInbound();
assertThat(msg, is(sameInstance(handledMsg)));
handledMsg.release();
assertThat(channel.readInbound(), is(nullValue()));
}
@Test
public void shouldLogEmptyByteBufDataRead() throws Exception {
ByteBuf msg = Unpooled.EMPTY_BUFFER;
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.writeInbound(msg);
verify(appender).doAppend(argThat(new RegexLogMatcher(".+READ: 0B$")));
ByteBuf handledMsg = channel.readInbound();
assertThat(msg, is(sameInstance(handledMsg)));
assertThat(channel.readInbound(), is(nullValue()));
}
@Test
public void shouldLogByteBufHolderDataRead() throws Exception {
ByteBufHolder msg = new DefaultByteBufHolder(Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8)) {
@Override
public String toString() {
return "foobar";
}
};
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.writeInbound(msg);
verify(appender).doAppend(argThat(new RegexLogMatcher(".+READ: foobar, 5B$")));
ByteBufHolder handledMsg = channel.readInbound();
assertThat(msg, is(sameInstance(handledMsg)));
handledMsg.release();
assertThat(channel.readInbound(), is(nullValue()));
}
@Test
public void shouldLogChannelReadComplete() throws Exception {
ByteBuf msg = Unpooled.EMPTY_BUFFER;
EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
channel.writeInbound(msg);
verify(appender).doAppend(argThat(new RegexLogMatcher(".+READ COMPLETE$")));
}
/**
* A custom EasyMock matcher that matches on Logback messages.
*/
private static final class RegexLogMatcher implements ArgumentMatcher<ILoggingEvent> {
private final String expected;
private String actualMsg;
RegexLogMatcher(String expected) {
this.expected = expected;
}
@Override
@SuppressWarnings("DynamicRegexReplaceableByCompiledPattern")
public boolean matches(ILoggingEvent actual) {
// Match only the first line to skip the validation of hex-dump format.
actualMsg = actual.getMessage().split("(?s)[\\r\\n]+")[0];
return actualMsg.matches(expected);
}
}
private static final class DisconnectingEmbeddedChannel extends EmbeddedChannel {
private DisconnectingEmbeddedChannel(ChannelHandler... handlers) {
super(handlers);
}
@Override
public ChannelMetadata metadata() {
return new ChannelMetadata(true);
}
}
}
| 37.233333 | 117 | 0.685765 |
4c14a0b2151a691e41977c01ea4448cfbcc45f37 | 1,900 | /*
* Copyright (C) 2020-21 Application Library Engineering Group
*
* 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.warkiz.tickseekbar.slice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.render.layoutboost.LayoutBoost;
import ohos.app.Context;
import com.warkiz.tickseekbar.ResourceTable;
/**
* Custom Fraction to display Custom TickSeekBar.
*/
public class CustomFraction extends Fraction {
private ComponentContainer mComponentContainer;
private Context mContext;
/**
* CustomFraction constructor.
*
* @param context context
* @param componentContainer component Container
*/
public CustomFraction(Context context, ComponentContainer componentContainer) {
this.mContext = context;
this.mComponentContainer = componentContainer;
}
@Override
protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
return scatter.parse(ResourceTable.Layout_custom_layout, container, false);
}
@Override
public Component getComponent() {
return LayoutBoost.inflate(this.mContext, ResourceTable.Layout_custom_layout, this.mComponentContainer, false);
}
} | 34.545455 | 119 | 0.755263 |
6ba52e61dfa65a8d6c5d8b0a8bff4c25542ba09e | 2,052 | package org.netcrusher.core.meter;
import org.netcrusher.core.chronometer.Chronometer;
import org.netcrusher.core.chronometer.SystemChronometer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class RateMeterImpl implements RateMeter {
private final long createdMs;
private final AtomicLong totalCount;
private final AtomicLong periodCount;
private final AtomicLong periodMarkerNs;
private final Chronometer chronometer;
public RateMeterImpl(Chronometer chronometer) {
this.chronometer = chronometer;
this.createdMs = chronometer.getEpochMs();
this.totalCount = new AtomicLong(0);
this.periodCount = new AtomicLong(0);
this.periodMarkerNs = new AtomicLong(chronometer.getTickNs());
}
public RateMeterImpl() {
this(SystemChronometer.INSTANCE);
}
@Override
public long getTotalElapsedMs() {
return Math.max(0, chronometer.getEpochMs() - createdMs);
}
@Override
public long getTotalCount() {
return totalCount.get();
}
@Override
public RateMeterPeriod getTotal() {
return new RateMeterPeriod(getTotalCount(), getTotalElapsedMs());
}
@Override
public RateMeterPeriod getPeriod(boolean reset) {
final long nowNs = chronometer.getTickNs();
final long elapsedNs = Math.max(0, nowNs - periodMarkerNs.get());
final long elapsedMs = TimeUnit.NANOSECONDS.toMillis(elapsedNs);
if (reset) {
periodMarkerNs.set(nowNs);
final long count = periodCount.getAndSet(0);
return new RateMeterPeriod(count, elapsedMs);
} else {
final long count = periodCount.get();
return new RateMeterPeriod(count, elapsedMs);
}
}
public void update(long delta) {
totalCount.addAndGet(delta);
periodCount.addAndGet(delta);
}
public void increment() {
update(+1);
}
public void decrement() {
update(-1);
}
}
| 26.307692 | 73 | 0.663255 |
8866fee02cbf81ecb41c3a0b9cefbc592e1100b9 | 3,227 | package com.zimmer.zombieapocalypse.creatures;
import com.zimmer.zombieapocalypse.files.CustomConfiguration;
import net.minecraft.server.v1_16_R3.*;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_16_R3.CraftWorld;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Spider;
import org.bukkit.inventory.ItemStack;
public class GrenadierZombie extends EntitySkeleton {
public GrenadierZombie(Location location){
super(EntityTypes.SKELETON, ((CraftWorld) location.getWorld()).getHandle());
this.setPosition(location.getX(), location.getY(), location.getZ());
this.setCustomName(new ChatComponentText(ChatColor.GOLD + "" + ChatColor.BOLD + "Grenadier"));
long currentTime = System.currentTimeMillis()/1000;
long sessionStart = CustomConfiguration.get().getLong("session-start");
long sessionTotal = CustomConfiguration.get().getLong("session-total");
long timeElapsed = currentTime - sessionStart + sessionTotal;
int days = Math.round(timeElapsed/1200);
double zombieHealth = (days - 3) + 20;
((LivingEntity) this.getBukkitEntity()).setMaxHealth(zombieHealth);
((LivingEntity) this.getBukkitEntity()).setHealth(zombieHealth);
ItemStack zombieHead = new ItemStack(Material.ZOMBIE_HEAD);
((LivingEntity) this.getBukkitEntity()).getEquipment().setHelmet(zombieHead);
((LivingEntity) this.getBukkitEntity()).getEquipment().setItemInMainHand(new ItemStack(Material.BOW));
if(days - 3 <= 3){
((LivingEntity) this.getBukkitEntity()).getEquipment().setLeggings(new ItemStack(Material.LEATHER_LEGGINGS));
} else if(days - 3 < 18){
((LivingEntity) this.getBukkitEntity()).getEquipment().setLeggings(new ItemStack(Material.IRON_LEGGINGS));
} else if(days - 3 < 108){
((LivingEntity) this.getBukkitEntity()).getEquipment().setLeggings(new ItemStack(Material.NETHERITE_LEGGINGS));
}
/*
Spider spider = location.getWorld().spawn(location, Spider.class);
spider.setCustomName(ChatColor.GOLD + "Grenadier Mount");
spider.setCustomNameVisible(true);
spider.setPassenger(this.getBukkitEntity());
*/
EntitySpider spider = new EntitySpider(EntityTypes.SPIDER, ((CraftWorld) location.getWorld()).getHandle());
((LivingEntity) spider.getBukkitEntity()).setMaxHealth(zombieHealth);
((LivingEntity) spider.getBukkitEntity()).setHealth(zombieHealth);
spider.setPosition(location.getX(), location.getY(), location.getZ());
spider.setCustomName(new ChatComponentText(ChatColor.GOLD + "" + ChatColor.BOLD + "Grenadier Mount"));
((LivingEntity) spider.getBukkitEntity()).setPassenger(this.getBukkitEntity());
WorldServer world = ((CraftWorld) location.getWorld()).getHandle();
world.addEntity(spider);
((LivingEntity) this.getBukkitEntity()).getEquipment().setHelmetDropChance(0.0f);
((LivingEntity) this.getBukkitEntity()).getEquipment().setLeggingsDropChance(0.0f);
}
} | 46.1 | 124 | 0.690734 |
82c8ce7e5a69647d4c9dfe9f11d76de933d26c30 | 3,254 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.elasticsearch;
import com.facebook.presto.common.type.StandardTypes;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.common.type.TypeManager;
import com.facebook.presto.common.type.TypeSignature;
import com.facebook.presto.elasticsearch.client.ElasticsearchClient;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.ConnectorTableLayoutHandle;
import com.facebook.presto.spi.SplitContext;
import com.facebook.presto.spi.connector.ConnectorPageSourceProvider;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import javax.inject.Inject;
import java.util.List;
import static com.facebook.presto.elasticsearch.ElasticsearchTableHandle.Type.QUERY;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;
public class ElasticsearchPageSourceProvider
implements ConnectorPageSourceProvider
{
private final ElasticsearchClient client;
private final Type jsonType;
@Inject
public ElasticsearchPageSourceProvider(ElasticsearchClient client, TypeManager typeManager)
{
this.client = requireNonNull(client, "client is null");
this.jsonType = typeManager.getType(new TypeSignature(StandardTypes.JSON));
}
@Override
public ConnectorPageSource createPageSource(
ConnectorTransactionHandle transaction,
ConnectorSession session,
ConnectorSplit split,
ConnectorTableLayoutHandle layout,
List<ColumnHandle> columns,
SplitContext splitContext)
{
requireNonNull(split, "split is null");
requireNonNull(layout, "layout is null");
ElasticsearchTableLayoutHandle layoutHandle = (ElasticsearchTableLayoutHandle) layout;
ElasticsearchSplit elasticsearchSplit = (ElasticsearchSplit) split;
if (layoutHandle.getTable().getType().equals(QUERY)) {
return new PassthroughQueryPageSource(client, layoutHandle.getTable(), jsonType);
}
if (columns.isEmpty()) {
return new CountQueryPageSource(client, session, layoutHandle.getTable(), elasticsearchSplit);
}
return new ScanQueryPageSource(
client,
session,
layoutHandle.getTable(),
elasticsearchSplit,
columns.stream()
.map(ElasticsearchColumnHandle.class::cast)
.collect(toImmutableList()));
}
}
| 39.682927 | 106 | 0.731715 |
bd014e7410293af4cf3cc3f3792c34a3a933fca8 | 18,457 | /*
* Copyright (c) 2002-2012 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
/**
* A simple WebTestCase which doesn't require server to run, and doens't use WebDriver.
*
* It depends on {@link MockWebConnection} to simulate sending requests to the server.
*
* <b>Note that {@link WebDriverTestCase} should be used unless HtmlUnit-specific feature
* is needed and Selenium does not support it.</b>
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Mike Bowler</a>
* @author David D. Kilzer
* @author Marc Guillemot
* @author Chris Erskine
* @author Michael Ottati
* @author Daniel Gredler
* @author Ahmed Ashour
*/
public abstract class SimpleWebTestCase extends WebTestCase {
/** Logging support. */
private static final Log LOG = LogFactory.getLog(SimpleWebTestCase.class);
private WebClient webClient_;
private int nbJSThreadsBeforeTest_;
/**
* Load a page with the specified HTML using the default browser version.
* @param html the HTML to use
* @return the new page
* @throws Exception if something goes wrong
*/
public final HtmlPage loadPage(final String html) throws Exception {
return loadPage(html, null);
}
/**
* Load a page with the specified HTML and collect alerts into the list.
* @param browserVersion the browser version to use
* @param html the HTML to use
* @param collectedAlerts the list to hold the alerts
* @return the new page
* @throws Exception if something goes wrong
*/
public final HtmlPage loadPage(final BrowserVersion browserVersion,
final String html, final List<String> collectedAlerts) throws Exception {
if (generateTest_browserVersion_.get() == null) {
generateTest_browserVersion_.set(browserVersion);
}
return loadPage(browserVersion, html, collectedAlerts, getDefaultUrl());
}
/**
* User the default browser version to load a page with the specified HTML
* and collect alerts into the list.
* @param html the HTML to use
* @param collectedAlerts the list to hold the alerts
* @return the new page
* @throws Exception if something goes wrong
*/
public final HtmlPage loadPage(final String html, final List<String> collectedAlerts) throws Exception {
generateTest_browserVersion_.set(FLAG_ALL_BROWSERS);
final BrowserVersion version =
(getBrowserVersion() != null) ? getBrowserVersion() : BrowserVersion.getDefault();
return loadPage(version, html, collectedAlerts, getDefaultUrl());
}
/**
* Loads an external URL, accounting for the fact that the remote server may be down or the
* machine running the tests may not be connected to the internet.
* @param url the URL to load
* @return the loaded page, or <tt>null</tt> if there were connectivity issues
* @throws Exception if an error occurs
*/
protected static final HtmlPage loadUrl(final String url) throws Exception {
try {
final WebClient client = new WebClient();
client.getOptions().setUseInsecureSSL(true);
return client.getPage(url);
}
catch (final ConnectException e) {
// The remote server is probably down.
System.out.println("Connection could not be made to " + url);
return null;
}
catch (final SocketException e) {
// The local machine may not be online.
System.out.println("Connection could not be made to " + url);
return null;
}
catch (final UnknownHostException e) {
// The local machine may not be online.
System.out.println("Connection could not be made to " + url);
return null;
}
}
/**
* Loads a page with the specified HTML and collect alerts into the list.
* @param html the HTML to use
* @param collectedAlerts the list to hold the alerts
* @param url the URL that will use as the document host for this page
* @return the new page
* @throws Exception if something goes wrong
*/
protected final HtmlPage loadPage(final String html, final List<String> collectedAlerts,
final URL url) throws Exception {
return loadPage(BrowserVersion.getDefault(), html, collectedAlerts, url);
}
/**
* Load a page with the specified HTML and collect alerts into the list.
* @param browserVersion the browser version to use
* @param html the HTML to use
* @param collectedAlerts the list to hold the alerts
* @param url the URL that will use as the document host for this page
* @return the new page
* @throws Exception if something goes wrong
*/
protected final HtmlPage loadPage(final BrowserVersion browserVersion,
final String html, final List<String> collectedAlerts, final URL url) throws Exception {
if (webClient_ == null) {
webClient_ = new WebClient(browserVersion);
}
return loadPage(webClient_, html, collectedAlerts, url);
}
/**
* Load a page with the specified HTML and collect alerts into the list.
* @param client the WebClient to use (webConnection and alertHandler will be configured on it)
* @param html the HTML to use
* @param collectedAlerts the list to hold the alerts
* @param url the URL that will use as the document host for this page
* @return the new page
* @throws Exception if something goes wrong
*/
protected final HtmlPage loadPage(final WebClient client,
final String html, final List<String> collectedAlerts, final URL url) throws Exception {
if (collectedAlerts != null) {
client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
}
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setDefaultResponse(html);
client.setWebConnection(webConnection);
return client.getPage(url);
}
/**
* Load a page with the specified HTML and collect alerts into the list.
* @param client the WebClient to use (webConnection and alertHandler will be configured on it)
* @param html the HTML to use
* @param collectedAlerts the list to hold the alerts
* @return the new page
* @throws Exception if something goes wrong
*/
protected final HtmlPage loadPage(final WebClient client,
final String html, final List<String> collectedAlerts) throws Exception {
return loadPage(client, html, collectedAlerts, getDefaultUrl());
}
/**
* Convenience method to pull the MockWebConnection out of an HtmlPage created with
* the loadPage method.
* @param page HtmlPage to get the connection from
* @return the MockWebConnection that served this page
*/
protected static final MockWebConnection getMockConnection(final HtmlPage page) {
return (MockWebConnection) page.getWebClient().getWebConnection();
}
/**
* Runs the calling JUnit test again and fails only if it already runs.<br/>
* This is helpful for tests that don't currently work but should work one day,
* when the tested functionality has been implemented.<br/>
* The right way to use it is:
* <pre>
* public void testXXX() {
* if (notYetImplemented()) {
* return;
* }
*
* ... the real (now failing) unit test
* }
* </pre>
* @return <tt>false</tt> when not itself already in the call stack
*/
protected boolean notYetImplemented() {
setGenerateTest_notYetImplemented(true);
if (notYetImplementedFlag.get() != null) {
return false;
}
notYetImplementedFlag.set(Boolean.TRUE);
final Method testMethod = findRunningJUnitTestMethod();
try {
LOG.info("Running " + testMethod.getName() + " as not yet implemented");
testMethod.invoke(this, (Object[]) new Class[] {});
Assert.fail(testMethod.getName() + " is marked as not implemented but already works");
}
catch (final Exception e) {
LOG.info(testMethod.getName() + " fails which is normal as it is not yet implemented");
// method execution failed, it is really "not yet implemented"
}
finally {
notYetImplementedFlag.set(null);
}
return true;
}
/**
* Finds from the call stack the active running JUnit test case
* @return the test case method
* @throws RuntimeException if no method could be found
*/
private Method findRunningJUnitTestMethod() {
final Class<?> cl = getClass();
final Class<?>[] args = new Class[] {};
// search the initial junit test
final Throwable t = new Exception();
for (int i = t.getStackTrace().length - 1; i >= 0; i--) {
final StackTraceElement element = t.getStackTrace()[i];
if (element.getClassName().equals(cl.getName())) {
try {
final Method m = cl.getMethod(element.getMethodName(), args);
if (isPublicTestMethod(m)) {
return m;
}
}
catch (final Exception e) {
// can't access, ignore it
}
}
}
throw new RuntimeException("No JUnit test case method found in call stack");
}
/**
* From Junit. Test if the method is a junit test.
* @param method the method
* @return <code>true</code> if this is a junit test
*/
private boolean isPublicTestMethod(final Method method) {
return method.getParameterTypes().length == 0
&& (method.getName().startsWith("test") || method.getAnnotation(Test.class) != null)
&& method.getReturnType() == Void.TYPE
&& Modifier.isPublic(method.getModifiers());
}
private static final ThreadLocal<Boolean> notYetImplementedFlag = new ThreadLocal<Boolean>();
/**
* Load the specified resource for the supported browsers and tests
* that the generated log corresponds to the expected one for this browser.
*
* @param fileName the resource name which resides in /resources folder and
* belongs to the same package as the test class.
*
* @throws Exception if the test fails
*/
protected void testHTMLFile(final String fileName) throws Exception {
final String resourcePath = getClass().getPackage().getName().replace('.', '/') + '/' + fileName;
final URL url = getClass().getClassLoader().getResource(resourcePath);
final String browserKey = getBrowserVersion().getNickname().substring(0, 2);
final WebClient client = getWebClient();
final HtmlPage page = client.getPage(url);
final HtmlElement want = page.getHtmlElementById(browserKey);
final HtmlElement got = page.getHtmlElementById("log");
final List<String> expected = readChildElementsText(want);
final List<String> actual = readChildElementsText(got);
Assert.assertEquals(expected, actual);
}
private List<String> readChildElementsText(final HtmlElement elt) {
final List<String> list = new ArrayList<String>();
for (final DomElement child : elt.getChildElements()) {
list.add(child.asText());
}
return list;
}
/**
* Returns the WebClient instance for the current test with the current {@link BrowserVersion}.
* @return a WebClient with the current {@link BrowserVersion}
*/
protected WebClient createNewWebClient() {
return new WebClient(getBrowserVersion());
}
/**
* Returns the WebClient instance for the current test with the current {@link BrowserVersion}.
* @return a WebClient with the current {@link BrowserVersion}
*/
protected final WebClient getWebClient() {
if (webClient_ == null) {
webClient_ = createNewWebClient();
}
return webClient_;
}
/**
* Returns the WebClient instance for the current test with the current {@link BrowserVersion}.
* @return a WebClient with the current {@link BrowserVersion}
*/
protected final WebClient getWebClientWithMockWebConnection() {
if (webClient_ == null) {
webClient_ = createNewWebClient();
webClient_.setWebConnection(getMockWebConnection());
}
return webClient_;
}
/**
* Defines the provided HTML as the response of the MockWebConnection for {@link #getDefaultUrl()}
* and loads the page with this URL using the current browser version; finally, asserts that the
* alerts equal the expected alerts (in which "§§URL§§" has been expanded to the default URL).
* @param html the HTML to use
* @return the new page
* @throws Exception if something goes wrong
*/
protected final HtmlPage loadPageWithAlerts(final String html) throws Exception {
return loadPageWithAlerts(html, getDefaultUrl(), -1);
}
/**
* Defines the provided HTML as the response of the MockWebConnection for {@link #getDefaultUrl()}
* and loads the page with this URL using the current browser version; finally, asserts the alerts
* equal the expected alerts.
* @param html the HTML to use
* @param url the URL from which the provided HTML code should be delivered
* @param waitForJS the milliseconds to wait for background JS tasks to complete. Ignored if -1.
* @return the new page
* @throws Exception if something goes wrong
*/
protected final HtmlPage loadPageWithAlerts(final String html, final URL url, final int waitForJS)
throws Exception {
if (getExpectedAlerts() == null) {
throw new IllegalStateException("You must annotate the test class with '@RunWith(BrowserRunner.class)'");
}
// expand variables in expected alerts
expandExpectedAlertsVariables(url);
createTestPageForRealBrowserIfNeeded(html, getExpectedAlerts());
final WebClient client = getWebClientWithMockWebConnection();
final List<String> collectedAlerts = new ArrayList<String>();
client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
final MockWebConnection webConnection = getMockWebConnection();
webConnection.setResponse(url, html);
final HtmlPage page = client.getPage(url);
if (waitForJS > 0) {
assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(waitForJS));
}
assertEquals(getExpectedAlerts(), collectedAlerts);
return page;
}
/**
* Reads the number of JS threads remaining from unit tests run before the current one.
* Ideally it should be always 0.
*/
@Before
public void readJSThreadsBeforeTest() {
nbJSThreadsBeforeTest_ = getJavaScriptThreads().size();
}
/**
* Cleanup after a test.
*/
@After
public void releaseResources() {
super.releaseResources();
if (webClient_ != null) {
webClient_.closeAllWindows();
webClient_.getCookieManager().clearCookies();
}
webClient_ = null;
final List<Thread> jsThreads = getJavaScriptThreads();
// collect stack traces
// caution: the threads may terminate after the threads have been returned by getJavaScriptThreads()
// and before stack traces are retrieved
if (jsThreads.size() > nbJSThreadsBeforeTest_) {
final Map<String, StackTraceElement[]> stackTraces = new HashMap<String, StackTraceElement[]>();
for (final Thread t : jsThreads) {
final StackTraceElement elts[] = t.getStackTrace();
if (elts != null) {
stackTraces.put(t.getName(), elts);
}
}
if (!stackTraces.isEmpty()) {
System.err.println("JS threads still running:");
for (final Map.Entry<String, StackTraceElement[]> entry : stackTraces.entrySet()) {
System.err.println("Thread: " + entry.getKey());
final StackTraceElement elts[] = entry.getValue();
for (final StackTraceElement elt : elts) {
System.err.println(elt);
}
}
throw new RuntimeException("JS threads are still running: " + jsThreads.size());
}
}
}
/**
* Gets the active JavaScript threads.
* @return the threads
*/
protected List<Thread> getJavaScriptThreads() {
final Thread[] threads = new Thread[Thread.activeCount() + 10];
Thread.enumerate(threads);
final List<Thread> jsThreads = new ArrayList<Thread>();
for (final Thread t : threads) {
if (t != null && t.getName().startsWith("JS executor for")) {
jsThreads.add(t);
}
}
return jsThreads;
}
}
| 38.612971 | 117 | 0.647938 |
e181dd969633e8970e2ca29f98a7ccaa7d475a31 | 783 | package parser.syntax;
import junit.framework.TestCase;
import parser.ast.AST;
import parser.visitor.OutputVisitor;
/**
* @author Dagon0577
* @date 2020/7/15
*/
public class AbstractSyntaxTest extends TestCase {
private static final boolean debug = false;
protected String outputMySQL(AST node, byte[] sql) {
OutputVisitor ov = new OutputVisitor(sql);
//遍历
node.accept(ov);
String sb = new String(ov.getData());
if (debug) {
System.out.println("DagonParser: " + getClass().getName() + "'s testcase: ");
System.out.println(" " + sql);
System.out.println("==>" + sb);
System.out.println("--------------------------------------------------");
}
return sb;
}
}
| 27 | 89 | 0.555556 |
799070a3f348ad04d9d43ea6438e8088c97431c0 | 5,347 | package com.compomics.peptizer.util;
import com.compomics.peptizer.MatConfig;
import com.compomics.peptizer.interfaces.AgentAggregator;
import com.compomics.peptizer.util.fileio.MatLogger;
import org.apache.log4j.Logger;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: kenny
* Date: 17-aug-2007
* Time: 14:53:27
*/
/**
* Class description:
* ------------------
* This class was developed to control the AgentAggregators in peptizer.
* Based on Aggregator.xml, a collection of AgentAggregators are constructed and can be accessed trough
* this singleton instance.
*/
public class AgentAggregatorFactory {
// Class specific log4j logger for AgentAggregatorFactory instances.
private static Logger logger = Logger.getLogger(AgentAggregatorFactory.class);
/**
* The Map with Aggregators.
* Keys: Class reference.
* Values: AgentAggregator implementations.
*/
private HashMap iAgentAggregators = null;
/**
* The singleton AgentAggregatorFactory.
*/
private static AgentAggregatorFactory iAgentAggregatorFactory = null;
/**
* Private constructor for Singleton pattern.
*/
private AgentAggregatorFactory() {
iAgentAggregators = new HashMap();
StringBuffer sb = null;
// 1. Create a series of reusable fields to create the AgentAggregators by the properties file.
// 1a) Aggregator object.
AgentAggregator lAgentAggregator = null;
// 1b) The AgentAggregator's class reference, is the key of the properties file as well.
String lAgentAggregatorClassReference = null;
// 2. Get all the Agent identifiers.
String[] lAgentAggregatorIDs = MatConfig.getInstance().getUniqueAgentAggregatorIDs();
for (int i = 0; i < lAgentAggregatorIDs.length; i++) {
// Mind this is pretty messy code. Just as in the AgentFactory, class references from MatConfig are retrieved.
// If one of them is not in the classpath, the AgentAggregator will not be in the AgentAggregatorFactory.
//
// If one of the following exceptions is thrown, a boolean(lFailure) is set true and further on an error is printed simply
// saying the AgentFactory failed to load the specified AgentAggregator(s).
//
// Nothing more is done.
boolean lFailure = true;
try {
// Key is the Agent class reference and Agent's unique ID!
lAgentAggregatorClassReference = lAgentAggregatorIDs[i];
// Dynamically initiate the Agent.
lAgentAggregator = (AgentAggregator) Class.forName(lAgentAggregatorClassReference).newInstance();
// Store in the Agent container.
iAgentAggregators.put(lAgentAggregatorClassReference, lAgentAggregator);
// Agent added succesfully, no failure!
lFailure = false;
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
}
if (lFailure) {
if (sb == null) {
sb = new StringBuffer();
sb.append("AgentAggregatorFactory failed to load the following AgentAggregators during initialization:\n");
}
sb.append("\n\t-" + lAgentAggregatorClassReference);
}
}
if (sb != null) {
MatLogger.logExceptionalEvent(sb.toString());
}
}
/**
* Returns the AgentAggregatorFactory instance.
* Retrieve Aggregator by getAgentAggregator(String UniqueID) method.
*
* @return AgentAggregatorFactory instance.
*/
public static AgentAggregatorFactory getInstance() {
if (iAgentAggregatorFactory == null) {
iAgentAggregatorFactory = new AgentAggregatorFactory();
}
return iAgentAggregatorFactory;
}
/**
* Returns the AgentAggregator with class reference aUniqueID.
*
* @param aUniqueID class reference of the returning AgentAggregator.
* @return AgentAggregator corresponding class reference aUniqueID.
*/
public AgentAggregator getAgentAggregator(String aUniqueID) {
if (iAgentAggregators != null) {
return (AgentAggregator) iAgentAggregators.get(aUniqueID);
} else {
MatLogger.logExceptionalEvent("AgentAggregator with class reference: \"" + aUniqueID + "\" is not availlably in the AgentAggregatorFatory!!");
return null;
}
}
/**
* Returns all availlable AgentAggregators.
*
* @return AgentAggregator[]
*/
public AgentAggregator[] getAgentAggregators() {
AgentAggregator[] result = new AgentAggregator[iAgentAggregators.size()];
Object[] objects = iAgentAggregators.values().toArray();
for (int i = 0; i < objects.length; i++) {
result[i] = (AgentAggregator) objects[i];
}
Arrays.sort(result);
return result;
}
/**
* Resets the AgentAggregatorFactory.
* Reloading all AgentAggregators from the MatConfig instance.
*/
public static void reset() {
iAgentAggregatorFactory = new AgentAggregatorFactory();
}
}
| 36.623288 | 154 | 0.644474 |
d7875685f88549019262fd131dd2a4854fe1fb00 | 1,659 | package com.ls.custom_view_library.puzzle_verify;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import com.ls.comm_util_library.Size;
/**
* Captcha的拼图区域策咯
* Created by luozhanming on 2018/1/19.
*/
public abstract class CaptchaStrategy {
protected Context mContext;
public CaptchaStrategy(Context context) {
this.mContext = context;
}
protected Context getContext() {
return mContext;
}
public abstract Size getBlockSize(int viewWidth, int viewHeight);
/**
* 定义缺块的形状
*
* @param blockSize 单位dp,注意转化为px
* @return path of the shape
*/
public abstract Path getBlockShape(Size blockSize);
/**
* 定义缺块的位置信息
*
* @param width picture width unit:px
* @param height picture height unit:px
* @param blockSize
* @return position info of the block
*/
public abstract PositionInfo getBlockPositionInfo(int width, int height, Size blockSize);
/**
* 定义滑块图片的位置信息(只有设置为无滑动条模式有用)
*
* @param width picture width
* @param height picture height
* @return position info of the block
*/
public PositionInfo getPositionInfoForSwipeBlock(int width, int height, Size blockSize){
return getBlockPositionInfo(width,height,blockSize);
}
/**
* 获得缺块阴影的Paint
*/
public abstract Paint getBlockShadowPaint();
/**
* 获得滑块图片的Paint
*/
public abstract Paint getBlockBitmapPaint();
/**
* 装饰滑块图片,在绘制图片后执行,即绘制滑块前景
*/
public void decorateMaskBitmap(Canvas canvas, Path shape) {
}
}
| 22.12 | 93 | 0.664256 |
3916c7abab263c5086612d44e197e7120bd30567 | 2,478 |
package com.joymain.jecs.fi.service.impl;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import com.joymain.jecs.service.impl.BaseManager;
import com.joymain.jecs.fi.model.JfiPayAdvice;
import com.joymain.jecs.fi.dao.JfiPayAdviceDao;
import com.joymain.jecs.fi.service.JfiPayAdviceManager;
import com.joymain.jecs.util.data.CommonRecord;
import com.joymain.jecs.util.data.Pager;
public class JfiPayAdviceManagerImpl extends BaseManager implements JfiPayAdviceManager {
private JfiPayAdviceDao dao;
/**
* Set the Dao for communication with the data layer.
* @param dao
*/
public void setJfiPayAdviceDao(JfiPayAdviceDao dao) {
this.dao = dao;
}
/**
* @see com.joymain.jecs.fi.service.JfiPayAdviceManager#getJfiPayAdvices(com.joymain.jecs.fi.model.JfiPayAdvice)
*/
public List getJfiPayAdvices(final JfiPayAdvice jfiPayAdvice) {
return dao.getJfiPayAdvices(jfiPayAdvice);
}
/**
* @see com.joymain.jecs.fi.service.JfiPayAdviceManager#getJfiPayAdvice(String adviceCode)
*/
public JfiPayAdvice getJfiPayAdvice(final String adviceCode) {
return dao.getJfiPayAdvice(new String(adviceCode));
}
/**
* @see com.joymain.jecs.fi.service.JfiPayAdviceManager#saveJfiPayAdvice(JfiPayAdvice jfiPayAdvice)
*/
public void saveJfiPayAdvice(JfiPayAdvice jfiPayAdvice) {
dao.saveJfiPayAdvice(jfiPayAdvice);
}
/**
* @see com.joymain.jecs.fi.service.JfiPayAdviceManager#removeJfiPayAdvice(String adviceCode)
*/
public void removeJfiPayAdvice(final String adviceCode) {
dao.removeJfiPayAdvice(new String(adviceCode));
}
//added for getJfiPayAdvicesByCrm
public List getJfiPayAdvicesByCrm(CommonRecord crm, Pager pager){
return dao.getJfiPayAdvicesByCrm(crm,pager);
}
/**
* 批量保存或更新多个付款通知
* @param fiPayAdvices
*/
public void saveJfiPayAdvices(List jfiPayAdvices) {
dao.saveJfiPayAdvices(jfiPayAdvices);
}
/**
* 获取存折查询统计
* @param crm
* @return
*/
public Map getJfiPayAdviceStatMap(CommonRecord crm){
return dao.getJfiPayAdviceStatMap(crm);
}
/**
* 代理商分组查询付款通知
* @param crm
* @return
*/
public List getJfiPayAdvicesStatGroup(CommonRecord crm){
return dao.getJfiPayAdvicesStatGroup(crm);
}
/**
* 银行提款报表
* @param crm
* @return
*/
public List getJfiPayAdvicesStat(CommonRecord crm){
return dao.getJfiPayAdvicesStat(crm);
}
}
| 27.230769 | 116 | 0.718321 |
fcd2d7f31bbf2eccc560a5ba9ff8c5c1b87d4d23 | 1,363 | package net.coordinate.keeper.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.coordinate.keeper.data.Config;
import net.coordinate.keeper.data.Coordinates;
import net.coordinate.keeper.helpers.MessageHelper;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
public final class ReplaceCoordinatesCommand implements Command<ServerCommandSource> {
public static final String ID_ARGUMENT = "id";
private Config config;
public ReplaceCoordinatesCommand(Config config){
this.config = config;
}
@Override
public int run(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
String id = getString(context, ID_ARGUMENT);
ServerPlayerEntity user = context.getSource().getPlayer();
BlockPos block = user.getBlockPos();
Coordinates coordinates = new Coordinates(block.getX(), block.getY(), block.getZ());
config.addCoordinates(id, coordinates);
MessageHelper.sendSpecialInfo(context, id + " was replaced with ", coordinates.toString());
return 1;
}
} | 40.088235 | 99 | 0.768892 |
82f80d8cbadbd1df2288a211e79f423a248f88f6 | 2,324 | /*
*
*/
package au.org.aurin.wif.model.demand.info;
import au.org.aurin.wif.model.allocation.AllocationLU;
import au.org.aurin.wif.model.demand.DemandScenario;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* <b>DemandInfo.java</b> : Holds the configuration parameters for Demand
* Information. It is subclass to hold a specific information for a given land
* use type.
*
* @author <a href="mailto:[email protected]"> Marcos Nino-Ruiz
* [email protected]</a> - 2012
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public class DemandInfo {
/** The demand scenario. @uml.property name="the demandScenario" */
@JsonIgnore
private DemandScenario demandScenario;
/** The allocation lu id. */
private String allocationLUId;
/** The allocation lu. */
@JsonIgnore
private AllocationLU allocationLU;
/**
* Instantiates a new demand info.
*/
public DemandInfo() {
super();
}
/**
* Instantiates a new demand info.
*
* @param copy
* the copy
*/
public DemandInfo(DemandInfo copy) {
}
/**
* Sets the demand scenario.
*
* @param demandScenario
* the new demand scenario
*/
public void setDemandScenario(DemandScenario demandScenario) {
this.demandScenario = demandScenario;
}
/**
* Gets the demand scenario.
*
* @return the demand scenario
*/
public DemandScenario getDemandScenario() {
return demandScenario;
}
/**
* Gets the allocation lu id.
*
* @return the allocationLUId
*/
public String getAllocationLUId() {
return allocationLUId;
}
/**
* Sets the allocation lu id.
*
* @param allocationLUId
* the allocationLUId to set
*/
public void setAllocationLUId(String allocationLUId) {
this.allocationLUId = allocationLUId;
}
/**
* Gets the allocation lu.
*
* @return the allocationLU
*/
public AllocationLU getAllocationLU() {
return allocationLU;
}
/**
* Sets the allocation lu.
*
* @param allocationLU
* the allocationLU to set
*/
public void setAllocationLU(AllocationLU allocationLU) {
this.allocationLU = allocationLU;
}
}
| 21.321101 | 107 | 0.663511 |
636c369080805ba6e7112fa34820eb54bc2e71fe | 3,753 | package cn.elvea.platform.xapi.service.impl;
import cn.elvea.platform.xapi.entity.AgentProfileEntity;
import cn.elvea.platform.xapi.exception.InvalidRequestException;
import cn.elvea.platform.xapi.service.AgentProfileService;
import cn.elvea.platform.xapi.utils.XApiUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* AgentProfileServiceImpl
*
* @author elvea
*/
@Slf4j
@Service
public class AgentProfileServiceImpl extends AbstractXApiService implements AgentProfileService {
/**
* @see AgentProfileService#getAgentProfile(String, String)
*/
@Override
public String getAgentProfile(String agent, String profileId) {
//
Query query = new Query(this.createCriteria(agent, profileId, null));
//
AgentProfileEntity entity = this.mongoTemplate.findOne(query, AgentProfileEntity.class);
return entity != null ? entity.getContent() : "";
}
/**
* @see AgentProfileService#getAgentProfileList(String, String)
*/
@Override
public List<String> getAgentProfileList(String agent, String since) throws InvalidRequestException {
//
Query query = new Query(this.createCriteria(agent, null, since));
//
List<AgentProfileEntity> entityList = this.mongoTemplate.find(query, AgentProfileEntity.class);
return entityList.stream().map(AgentProfileEntity::getProfileId).collect(Collectors.toList());
}
/**
* @see AgentProfileService#saveAgentProfile(String, String, String)
*/
@Override
public void saveAgentProfile(String agent, String profileId, String content) {
//
Query query = new Query(this.createCriteria(agent, profileId, null));
//
AgentProfileEntity entity = this.mongoTemplate.findOne(query, AgentProfileEntity.class);
if (entity != null) { // Update
entity.setContent(content);
entity.setActive(Boolean.TRUE);
} else { // Create
entity = new AgentProfileEntity();
entity.setProfileId(profileId);
entity.setAgent(XApiUtils.extractAgentObject(agent));
entity.setContent(content);
entity.setActive(Boolean.TRUE);
}
this.agentProfileRepository.save(entity);
}
/**
* @see AgentProfileService#deleteAgentProfile(String, String)
*/
@Override
public void deleteAgentProfile(String agent, String profileId) {
//
Query query = new Query(this.createCriteria(agent, profileId, null));
//
List<AgentProfileEntity> entityList = this.mongoTemplate.find(query, AgentProfileEntity.class);
if (CollectionUtils.isNotEmpty(entityList)) {
this.agentProfileRepository.deleteAll(entityList);
}
}
/**
* 私有方法用于构建查询条件
*/
private Criteria createCriteria(String agentJson, String profileId, String since) {
Criteria criteria = new Criteria();
//
if (StringUtils.isNotEmpty(profileId)) {
criteria.and("profileId").is(profileId);
}
//
processAgentCriteria(criteria, agentJson);
//
if (StringUtils.isNotEmpty(since)) {
Date sinceDateObject = XApiUtils.parseTimestamp(since);
if (sinceDateObject != null) {
criteria.and("createdAt").gt(sinceDateObject);
}
}
return criteria;
}
}
| 34.431193 | 104 | 0.673328 |
419c911db2958f147e0ef7ad5d6e1b7bf4a836cd | 5,937 | /**
*
*/
package winterwell.jtwitter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import winterwell.jtwitter.Twitter.ITweet;
/**
* @WARNING There are bugs on Twitter's end -- the messages returned by this
* stream may not include all the messages to a user. The results vary
* from user to user!<br>
* Recommendation: Use {@link TwitterStream} with the keyword filter
* "@screenname" to get messages to you.
* <p>
* Connect to the streaming API.
* <p>
* This class picks up the following tweets: <br>
*
* - Tweets by you <br>
* - Tweets that mention you <br>
* - Tweets by people you follow IF {@link #setWithFollowings(boolean)}
* is true. <br>
* - Direct messages (DMs) to you<nr> - Retweets of your messages. <br>
* - Retweets made by you.
*
* <p>
* Duplicate messages may be delivered when reconnecting to the
* Streaming API.
*
* TODO test out url-signing over header-signing -- c.f. http://groups
* .google.com/group/twitter-development-talk/browse_thread
* /thread/420c4b555198aa6c/f85e2507b7f65e39?pli=1
*
* "figured it out on my own. must use HTTP GET with OAuth params
* passed in URI string. Not mentioned in the documentation. Wasted
* many hours figuring out this stuff would be clarified if someone
* updated the docs and made some examples."
*
*
* @author Daniel
* @testedby {@link UserStreamTest}
*/
public class UserStream extends AStream {
boolean withFollowings;
public UserStream(Twitter jtwit) {
super(jtwit);
}
@Override
HttpURLConnection connect2() throws IOException {
InternalUtils.log(LOGTAG, "connect2()... "+this);
connect3_rateLimit();
// API version 2?! Yes, this is right.
String url = "https://userstream.twitter.com/2/user.json?delimited=length";
Map<String, String> vars = new HashMap();
if (withFollowings) {
vars = InternalUtils.asMap("with",
(withFollowings ? "followings" : "user"));
}
HttpURLConnection con = client.connect(url, vars, true);
return con;
}
/**
* Protect the rate limits & _help_ you avoid annoying Twitter (only
* locally! And forgetful! Do NOT rely on this)
*/
private void connect3_rateLimit() {
if (jtwit.getScreenName() == null)
return; // dunno
AStream s = user2stream.get(jtwit.getScreenName());
if (s != null && s.isConnected()) {
throw new TwitterException.TooManyLogins("One account, one UserStream");
}
// memory paranoia
if (user2stream.size() > 500) {
// oh well -- forget stuff (this Map is just a safety check)
user2stream.clear();
}
user2stream.put(jtwit.getScreenName(), this);
}
/**
* Used to help avoid breaking api limits.
*/
private final static ConcurrentHashMap<String, AStream> user2stream = new ConcurrentHashMap();
/**
* Use the REST API to fill in: mentions of you. Missed you-follow-them
* events are automatically generated on reconnect.
*/
@Override
int fillInOutages2(Twitter jtwit2, Outage outage)
throws UnsupportedOperationException, TwitterException {
int cnt = 0;
// fetch
{ // get mentions of you
List<Status> mentions = jtwit2.getMentions();
InternalUtils.log(LOGTAG, "fillIn mentions "+jtwit2.getSinceId()+": "+mentions.size());
for (Status status : mentions) {
if (tweets.contains(status)) {
continue;
}
tweets.add(status);
cnt++;
}
}
if (withFollowings) { // Get your and network stuff.
// Can't get too many results, rate-limiting is severe (15x20 results per 15 mins) for this resource
jtwit2.setMaxResults(100);
List<Status> updates = jtwit2.getHomeTimeline();
InternalUtils.log(LOGTAG, "fillIn from-you "+jtwit2.getSinceId()+": "+updates.size());
for (Status status : updates) {
if (tweets.contains(status)) {
continue;
}
tweets.add(status);
cnt++;
}
// NB: 100k was the original setting -- see fillInOutages()
jtwit2.setMaxResults(100000);
} else { // get your traffic
List<Status> updates = jtwit2.getUserTimeline(jtwit2.getScreenName());
InternalUtils.log(LOGTAG, "fillIn from-you "+jtwit2.getSinceId()+": "+updates.size());
for (Status status : updates) {
if (tweets.contains(status)) {
continue;
}
tweets.add(status);
cnt++;
}
}
{ // different since-id for DMs
jtwit2.setSinceId(outage.sinceDMId);
List<Message> dms = jtwit2.getDirectMessages();
// debug info for latency issues
String dmids = "";
for (Message message : dms) {
if (message==null) continue; // paranoia
dmids += message.getId()+" ";
}
InternalUtils.log(LOGTAG, "fillIn DMs "+jtwit2.getSinceId()+": "+dms.size()+" "+dmids);
for (ITweet dm : dms) {
if (tweets.contains(dm)) {
continue;
}
tweets.add(dm);
cnt++;
}
}
// Missed follow events are sort of OK: the reconnect will update
// friends
return cnt;
}
/**
* @return people who the user follows -- at the point when the stream last
* connected.
*/
public Collection<Number> getFriends() {
// ??update the friends list from follow events? But we might miss some during an outage.
return friends;
}
/**
* @param withFollowings
* if true, pick up all tweets by the people the user follows.
*/
public void setWithFollowings(boolean withFollowings) {
assert !isConnected();
this.withFollowings = withFollowings;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("UserStream");
sb.append("["+jtwit.getScreenNameIfKnown());
if (withFollowings) sb.append(" +followings");
sb.append("]");
return sb.toString();
}
}
| 30.761658 | 103 | 0.654876 |
1483b52c13fd5f88e9a3aa73c9bb0bbc5675d2db | 568 | package game.GameObjects;
import java.awt.image.BufferedImage;
public class Projectile extends Movable {
private int damage = 4;
public Projectile(int x, int y, BufferedImage objImage, int vx, int vy, float angle) {
super(x, y, objImage, vx, vy, angle);
}
//this will call functions that update the positioning of the projectile in the world
@Override
public void update(int frameCounter) {
this.hitBox.setLocation(this.x, this.y);
moveForwards();
}
public int getDamage() {
return damage;
}
}
| 23.666667 | 90 | 0.661972 |
85c921536432d622e8fb803bf8320106b80b06d4 | 3,094 | package de.hdm_stuttgart.huber.itprojekt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import de.hdm_stuttgart.huber.itprojekt.client.gui.Notificator;
import de.hdm_stuttgart.huber.itprojekt.shared.EditorAsync;
import de.hdm_stuttgart.huber.itprojekt.shared.domainobjects.Notebook;
/**
* Notizbuch anlegen
*
* @author Nikita Nalivayko
*/
public class CreateNotebook extends BasicVerticalView {
private EditorAsync editorVerwaltung = ClientsideSettings.getEditorVerwaltung();
private VerticalPanel vPanel = new VerticalPanel();
private TextBox titleTextBox = new TextBox();
private TextBox subtitleTextBox = new TextBox();
private Button createButton = new Button("Create");
private Label title = new Label("Title");
private Label subtitle = new Label("Subtitle");
@Override
public void run() {
vPanel.add(title);
vPanel.add(titleTextBox);
vPanel.add(subtitle);
vPanel.add(subtitleTextBox);
vPanel.add(createButton);
createButton.addClickHandler(new CreateClickHandler());
this.add(vPanel);
}
@Override
public String getHeadlineText() {
return "CREATE A NOTEBOOK";
}
@Override
public String getSubHeadlineText() {
return "Give your notebook a title and subtitle to complete!";
}
// Neues Notizbuch wird erstellt
public void createNotebook() {
Notebook nb = new Notebook();
nb.setTitle(titleTextBox.getText());
nb.setSubtitle(subtitleTextBox.getText());
editorVerwaltung.createNoteBook(nb, new CreateNotebookCallback());
}
// Clickhandler für CreateButton
private class CreateClickHandler implements ClickHandler {
@Override
public void onClick(ClickEvent event) {
createNotebook();
}
}
/**
* Klasse die den callback zum Notizbuch anlegen implementiert. Das
* angelegte Notizbuch wird an die EditorImpl übergeben.
*/
private class CreateNotebookCallback implements AsyncCallback<Notebook> {
private Notificator notificator = Notificator.getNotificator();
@Override
public void onFailure(Throwable caught) {
notificator.showError("Erstellen fehlgeschlagen.");
GWT.log(caught.toString());
}
@Override
public void onSuccess(Notebook result) {
notificator.showSuccess("NoteBook " + result.getTitle() + " created successfully.");
ShowAllNotebooks san = new ShowAllNotebooks();
ApplicationPanel.getApplicationPanel().replaceContentWith(san);
}
}
}
| 29.188679 | 97 | 0.670006 |
7515965bb58ce7b6670c8b98f4bcbdf80052e836 | 2,179 | package c.f.b.b;
import android.util.Pair;
import java.util.HashMap;
public class c implements o {
static final HashMap<Pair<Integer, Integer>, String> a = new HashMap<>();
/* renamed from: b reason: collision with root package name */
static final HashMap<String, String> f2217b = new HashMap<>();
static {
a.put(Pair.create(4, 4), "layout_constraintBottom_toBottomOf");
a.put(Pair.create(4, 3), "layout_constraintBottom_toTopOf");
a.put(Pair.create(3, 4), "layout_constraintTop_toBottomOf");
a.put(Pair.create(3, 3), "layout_constraintTop_toTopOf");
a.put(Pair.create(6, 6), "layout_constraintStart_toStartOf");
a.put(Pair.create(6, 7), "layout_constraintStart_toEndOf");
a.put(Pair.create(7, 6), "layout_constraintEnd_toStartOf");
a.put(Pair.create(7, 7), "layout_constraintEnd_toEndOf");
a.put(Pair.create(1, 1), "layout_constraintLeft_toLeftOf");
a.put(Pair.create(1, 2), "layout_constraintLeft_toRightOf");
a.put(Pair.create(2, 2), "layout_constraintRight_toRightOf");
a.put(Pair.create(2, 1), "layout_constraintRight_toLeftOf");
a.put(Pair.create(5, 5), "layout_constraintBaseline_toBaselineOf");
f2217b.put("layout_constraintBottom_toBottomOf", "layout_marginBottom");
f2217b.put("layout_constraintBottom_toTopOf", "layout_marginBottom");
f2217b.put("layout_constraintTop_toBottomOf", "layout_marginTop");
f2217b.put("layout_constraintTop_toTopOf", "layout_marginTop");
f2217b.put("layout_constraintStart_toStartOf", "layout_marginStart");
f2217b.put("layout_constraintStart_toEndOf", "layout_marginStart");
f2217b.put("layout_constraintEnd_toStartOf", "layout_marginEnd");
f2217b.put("layout_constraintEnd_toEndOf", "layout_marginEnd");
f2217b.put("layout_constraintLeft_toLeftOf", "layout_marginLeft");
f2217b.put("layout_constraintLeft_toRightOf", "layout_marginLeft");
f2217b.put("layout_constraintRight_toRightOf", "layout_marginRight");
f2217b.put("layout_constraintRight_toLeftOf", "layout_marginRight");
}
public c(l lVar) {
}
}
| 50.674419 | 80 | 0.705369 |
e8a0f197531811477568bcf4291bcbe4c31b24e1 | 877 | package exercicio_6_1;
public class Week
{
public Weekdays getWeekdays(int weekdays)
{
switch(weekdays)
{
case 1: return new Sunday();
case 2: return new Monday();
case 3: return new Tuesday();
case 4: return new Wednesday();
case 5: return new Thursday();
case 6: return new Friday();
case 7: return new Saturday();
}
throw new IllegalArgumentException("'" + weekdays +
"' is an illegal argument for the parameter weekdays!");
}
public Weekdays getWeekdays(String weekdays)
{
try
{
return (Weekdays) Class.forName(weekdays).newInstance();
}
catch(Exception exception)
{
throw new IllegalArgumentException("'" + weekdays +
"' is an illegal argument for the parameter weekdays!");
}
}
} | 25.057143 | 97 | 0.578107 |
3692063f9163e5422969fbd58b4fa79c3d01ee0a | 414 | package lrg.dude.duplication;
public interface Entity {
String getName();
StringList getCode();
int getNoOfRelevantLines();
void setNoOfRelevantLines(int paramInt);
}
/* Location: C:\Users\emill\Dropbox\slimmerWorden\2018-2019-Semester2\THESIS\iPlasma6\tools\iPlasma\dude.jar!\lrg\dude\duplication\Entity.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 1.0.7
*/ | 24.352941 | 156 | 0.702899 |
2957387f607a59058ebc9cc70ef5ca1d7b6fc555 | 2,221 | package com.google.android.gms.fitness.result;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.internal.safeparcel.C0721a;
import com.google.android.gms.common.internal.safeparcel.C0723b;
import com.google.android.gms.fitness.data.Subscription;
import java.util.ArrayList;
/* renamed from: com.google.android.gms.fitness.result.e */
public class C1072e implements Parcelable.Creator<ListSubscriptionsResult> {
/* renamed from: a */
static void m2001a(ListSubscriptionsResult listSubscriptionsResult, Parcel parcel, int i) {
int H = C0723b.m750H(parcel);
C0723b.m776c(parcel, 1, listSubscriptionsResult.getSubscriptions(), false);
C0723b.m775c(parcel, 1000, listSubscriptionsResult.getVersionCode());
C0723b.m759a(parcel, 2, (Parcelable) listSubscriptionsResult.getStatus(), i, false);
C0723b.m751H(parcel, H);
}
/* renamed from: ch */
public ListSubscriptionsResult createFromParcel(Parcel parcel) {
int G = C0721a.m714G(parcel);
ArrayList<Subscription> arrayList = null;
int i = 0;
Status status = null;
while (parcel.dataPosition() < G) {
int F = C0721a.m713F(parcel);
int aH = C0721a.m720aH(F);
if (aH != 1000) {
switch (aH) {
case 1:
arrayList = C0721a.m723c(parcel, F, Subscription.CREATOR);
break;
case 2:
status = (Status) C0721a.m716a(parcel, F, Status.CREATOR);
break;
default:
C0721a.m721b(parcel, F);
break;
}
} else {
i = C0721a.m728g(parcel, F);
}
}
if (parcel.dataPosition() == G) {
return new ListSubscriptionsResult(i, arrayList, status);
}
throw new C0721a.C0722a("Overread allowed size end=" + G, parcel);
}
/* renamed from: dC */
public ListSubscriptionsResult[] newArray(int i) {
return new ListSubscriptionsResult[i];
}
}
| 38.293103 | 95 | 0.596128 |
b3f8cc4aef55e71c9f767b7f20d97076687018f8 | 1,443 | /* */ package edu.drexel.cis.dragon.ir.classification.featureselection;
/* */
/* */ import edu.drexel.cis.dragon.ir.classification.DocClassSet;
/* */ import edu.drexel.cis.dragon.ir.index.IRCollection;
/* */ import edu.drexel.cis.dragon.ir.index.IndexReader;
/* */ import edu.drexel.cis.dragon.matrix.SparseMatrix;
/* */ import java.io.Serializable;
/* */
/* */ public class NullFeatureSelector extends AbstractFeatureSelector
/* */ implements Serializable
/* */ {
/* */ private static final long serialVersionUID = 1L;
/* */
/* */ protected int[] getSelectedFeatures(IndexReader indexReader, DocClassSet trainingSet)
/* */ {
/* 21 */ int[] featureMap = new int[indexReader.getCollection().getTermNum()];
/* 22 */ for (int i = 0; i < featureMap.length; i++)
/* 23 */ featureMap[i] = i;
/* 24 */ return featureMap;
/* */ }
/* */
/* */ protected int[] getSelectedFeatures(SparseMatrix doctermMatrix, DocClassSet trainingSet)
/* */ {
/* 30 */ int[] featureMap = new int[doctermMatrix.columns()];
/* 31 */ for (int i = 0; i < featureMap.length; i++)
/* 32 */ featureMap[i] = i;
/* 33 */ return featureMap;
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.ir.classification.featureselection.NullFeatureSelector
* JD-Core Version: 0.6.2
*/ | 42.441176 | 100 | 0.603604 |
5e58c5977da87d7d3531695a051a419648e98e49 | 614 | package perobobbot.discord.resources;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Value;
@Value
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class SessionStartLimit {
int total;//The total number of session starts the current user is allowed
int remaining;//The remaining number of session starts the current user is allowed
int resetAfter;// The number of milliseconds after which the limit resets
int maxConcurrency;// The number of identify requests allowed per 5 seconds
}
| 40.933333 | 86 | 0.812704 |
88d507312753629b45fe9b50c184e1cbb283a058 | 29,017 | package cola.machine.game.myblocks.model.ui.html;
import com.dozenx.game.opengl.util.ShaderUtils;
import de.matthiasmann.twl.Clipboard;
import de.matthiasmann.twl.Event;
import de.matthiasmann.twl.InputMap;
import de.matthiasmann.twl.KeyStroke;
import de.matthiasmann.twl.model.DefaultEditFieldModel;
import de.matthiasmann.twl.model.EditFieldModel;
import de.matthiasmann.twl.utils.CallbackSupport;
import de.matthiasmann.twl.utils.TextUtil;
import javax.vecmath.Vector4f;
/**
* Created by luying on 17/1/12.
*/
public class EditField extends TextField {
//onMouseMove 鼠标变成竖杠
//onMouseMoveOut 鼠标变成正常的
//onkeyDown
//onclick
//onblur
//onfocus
int scrollPos;
int selectionStart;
int selectionEnd;
int numberOfLines;
public boolean multiLine;
boolean pendingScrollToCursor;
boolean pendingScrollToCursorForce;
private int maxTextLength = Short.MAX_VALUE;
//private int fontSize=12;
private int columns = 5;
private char passwordChar;
private Object errorMsg;
private boolean errorMsgFromModel;
private boolean textLongerThenWidget;
private boolean forwardUnhandledKeysToCallback;
private boolean autoCompletionOnSetText = true;
private int cursorPos;
public void setText(String text) {
setText(text, false);
}
public EditField(){
this.setFontSize(12);
this.canAcceptKeyboardFocus=true;
addActionMapping("cut", "cutToClipboard");
addActionMapping("copy", "copyToClipboard");
addActionMapping("paste", "pasteFromClipboard");
addActionMapping("selectAll", "selectAll");
addActionMapping("duplicateLineDown", "duplicateLineDown");
KeyStroke[] keys = new KeyStroke[]{KeyStroke.parse("ctrl X","cut"),
KeyStroke.parse("ctrl C","copy"),
KeyStroke.parse("ctrl V","paste"),
KeyStroke.parse("ctrl A","selectAll")};
InputMap inputMap =new InputMap(keys);
this.setInputMap(inputMap);
this.setColor(new Vector4f(0,0,1,1));
this.setMinHeight((short)getFontSize());
this.setMinWidth((short) (getFontSize() * 5));
this.width=(int)getFontSize()*5;
this.height=(int)getFontSize();
this.setBorderColor(new Vector4f(0.8f,0.8f,0.8f,1));
this.setBackgroundColor(new Vector4f(1,1,1,1));
//(int modifier, int keyCode, char keyChar, String action) {
}
void setText(String text, boolean fromModel) {
text = TextUtil.limitStringLength(text, maxTextLength);
editBuffer.replace(0, editBuffer.length(), text);
cursorPos = text.length();
selectionStart = 0;
selectionEnd = 0;
updateSelection();
updateText(autoCompletionOnSetText, fromModel, Event.KEY_NONE);
scrollToCursor(true);
}
public void updateSelection(){
/*
if(attributes != null) {
attributes.removeAnimationState(TextWidget.STATE_TEXT_SELECTION);
attributes.setAnimationState(TextWidget.STATE_TEXT_SELECTION,
selectionStart, selectionEnd, true);
attributes.optimize();
textRenderer.cacheDirty = true;
}*/
}
protected int getCursorPosFromMouse(int x, int y) {//根据坐标得到在文本的哪个位置
//Font font = getFont();
x -= this.getInnerX();//换算相对坐标
int lineStart = 0;
int lineEnd = editBuffer.length();
if(multiLine) {
y -= this.getInnerY();
int lineHeight =(int)this.getFontSize();
int endIndex = lineEnd;
for(;;) {
lineEnd = computeLineEnd(lineStart);
if(lineStart >= endIndex || y < lineHeight) {
break;
}
lineStart = Math.min(lineEnd + 1, endIndex);
y -= lineHeight;
}
}
return computeCursorPosFromX(x, lineStart, lineEnd);//根据第
}
protected int computeCursorPosFromX(int x, int lineStart) {
return computeCursorPosFromX(x, lineStart, computeLineEnd(lineStart));
}
protected int computeCursorPosFromX(int x, int lineStart, int lineEnd) {
// Font font = getFont();
return lineStart +(int) (x/this.getFontSize());
}
protected int computeLineEnd(int cursorPos) {//得到行的末尾
int endIndex = editBuffer.length();
if(!multiLine) {
return endIndex;
}
while(cursorPos < endIndex && editBuffer.charAt(cursorPos) != '\n') {
cursorPos++;
}
return cursorPos;
}
@Override
public boolean handleEvent(Event evt) {
boolean selectPressed = (evt.getModifiers() & Event.MODIFIER_SHIFT) != 0;
if(evt.isMouseEvent()) {
boolean hover = (evt.getType() != Event.Type.MOUSE_EXITED) && isMouseInside(evt);
// getAnimationState().setAnimationState(STATE_HOVER, hover);
}
if(evt.isMouseDragEvent()) {
if(evt.getType() == Event.Type.MOUSE_DRAGGED &&
(evt.getModifiers() & Event.MODIFIER_LBUTTON) != 0) {
int newPos = getCursorPosFromMouse(evt.getMouseX(), evt.getMouseY());
setCursorPos(newPos, true);
Document.needUpdate=true;
}
return true;
}
/*
if(super.handleEvent(evt)) {//为什么有这句呢 明明 就直接处理就可以了 啊
return true;
}
*/
/* if(autoCompletionWindow != null) {
if(autoCompletionWindow.handleEvent(evt)) {
return true;
}
}*/
switch (evt.getType()) {
case KEY_PRESSED:
switch (evt.getKeyCode()) {
case Event.KEY_BACK:
deletePrev();
return true;
case Event.KEY_DELETE:
deleteNext();
return true;
case Event.KEY_NUMPADENTER:
case Event.KEY_RETURN:
if(multiLine) {
if(evt.hasKeyCharNoModifiers()) {
insertChar('\n');
} else {
break;
}
} else {
doCallback(Event.KEY_RETURN);
}
return true;
case Event.KEY_ESCAPE:
doCallback(evt.getKeyCode());
return true;
case Event.KEY_HOME:
setCursorPos(computeLineStart(cursorPos), selectPressed);
return true;
case Event.KEY_END:
setCursorPos(computeLineEnd(cursorPos), selectPressed);
return true;
case Event.KEY_LEFT:
moveCursor(-1, selectPressed);
return true;
case Event.KEY_RIGHT:
moveCursor(+1, selectPressed);
return true;
case Event.KEY_UP:
if(multiLine) {
moveCursorY(-1, selectPressed);
return true;
}
break;
case Event.KEY_DOWN:
if(multiLine) {
moveCursorY(+1, selectPressed);
return true;
}
break;
case Event.KEY_TAB:
return false;
default:
if(evt.hasKeyCharNoModifiers()) {
// LogUtil.println(""+evt.getKeyChar());
insertChar(evt.getKeyChar());
return true;
}
}
if(forwardUnhandledKeysToCallback) {
//doCallback(evt.getKeyCode());
return true;
}
return false;
case KEY_RELEASED:
switch (evt.getKeyCode()) {
case Event.KEY_BACK:
case Event.KEY_DELETE:
case Event.KEY_NUMPADENTER:
case Event.KEY_RETURN:
case Event.KEY_ESCAPE:
case Event.KEY_HOME:
case Event.KEY_END:
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return true;
default:
return evt.hasKeyCharNoModifiers() || forwardUnhandledKeysToCallback;
}
case MOUSE_BTNUP:
if(evt.getMouseButton() == Event.MOUSE_RBUTTON && isMouseInside(evt)) {
// showPopupMenu(evt);
return true;
}
break;
case MOUSE_BTNDOWN:
if(evt.getMouseButton() == Event.MOUSE_LBUTTON && isMouseInside(evt)) {
int newPos = getCursorPosFromMouse(evt.getMouseX(), evt.getMouseY());
setCursorPos(newPos, selectPressed);
scrollPos = 0;//textRenderer.lastScrollPos;
Document.needUpdate=true;
return true;
}
break;
case MOUSE_CLICKED:
if(evt.getMouseClickCount() == 2) {
int newPos = getCursorPosFromMouse(evt.getMouseX(), evt.getMouseY());
selectWordFromMouse(newPos);
this.cursorPos = selectionStart;
scrollToCursor(false);
this.cursorPos = selectionEnd;
scrollToCursor(false);
Document.needUpdate=true;
return true;
}
if(evt.getMouseClickCount() == 3) {
selectAll();
return true;
}
break;
case MOUSE_WHEEL:
return false;
}
return evt.isMouseEvent();
}
public void handle(){
}
public void onMouseMoveOver(){
Window.cursor= Window.SELECT;
}
public void onMouseMoveOut(){
Window.cursor= Window.POINT;
}
public void onFocus(){
Window.cursor= Window.SELECT;
}
public void onClick(){
Window.cursor= Window.SELECT;
}
protected void moveCursorY(int dir, boolean select) {
if(multiLine) {
int x = computeRelativeCursorPositionX(cursorPos);
int lineStart;
if(dir < 0) {
lineStart = computeLineStart(cursorPos);
if(lineStart == 0) {
setCursorPos(0, select);
return;
}
lineStart = computeLineStart(lineStart - 1);
} else {
lineStart = Math.min(computeLineEnd(cursorPos) + 1, editBuffer.length());
}
setCursorPos(computeCursorPosFromX(x, lineStart), select);
}
}
@Override
public void buildVao(){//你好
// this.setMarginTop( (short)(this.getMarginTop()+10));
// this.setMarginLeft( (short)(this.getMarginLeft()+10));
this.innerText =editBuffer.toString();
super.buildVao();
//绘制鼠标
if(multiLine){
/* String[] ss = innerText.split("\n");
int count =0;
for(String s:ss){
ShaderUtils.draw2dColor(new Vector4f(1,1,1,1),this.getInnerX()+ (int)(this.cursorPos*this.getFontSize()),this.getInnerY(),10,(int)this.getFontSize());
count++;
}*/
if(selectionStart!=selectionEnd){
ShaderUtils.draw2dColor(new Vector4f(1,1,1,1),this.getInnerX()+ (int)(this.selectionStart*this.getFontSize()),this.getInnerY(),index+0.002f,(selectionEnd-selectionStart)*(int)getFontSize(),(int)this.getFontSize());
//这里涉及到了分段
//开始的选中位置
//多段集合 每个集合都标明了 开始结束位置
//linestart lineend
//this.computeLineStart()
}else{
int preY =0;
int preX =0;
int start=0;
preY=0;
String s= editBuffer.substring(0,this.cursorPos);
int thieLineStart =0;
int totalLen=0;
while((start=s.indexOf('\n',start+1))!=-1){
thieLineStart= start;
preY++;
// s= s.substring(start);
//totalLen+=start;
}
preX = this.cursorPos-thieLineStart;
ShaderUtils.draw2dColor(new Vector4f(0,1,1,1),this.getInnerX()+ (int)(preX*this.getFontSize()),(int)(this.getInnerY()+preY*getFontSize()),index+0.0015f,2,(int)this.getFontSize());
}
}else{//没有换行
if(hasFocusOrPopup()){
//long nowTime = System.currentTimeMillis();
// if((nowTime-lastBlinkTime)% duration <flashTime){
ShaderUtils.draw2dColor(new Vector4f(0,0,0,1),this.getInnerX()+ (int)((this.cursorPos==0?0.2:this.cursorPos)*this.getFontSize()),this.getInnerY(),index+0.0015f,2,(int)this.getFontSize());
//}
} if(hasSelection() ){
//blink
ShaderUtils.draw2dColor(new Vector4f(0,1,1,1),this.getInnerX()+ (int)(this.selectionStart*this.getFontSize()),this.getInnerY(),index+0.002f,(selectionEnd-selectionStart)*(int)getFontSize(),(int)this.getFontSize());
}
}
}
float lastBlinkTime=0;
float duration=3*1000;
float flashTime=2*1000;
final EditFieldModel editBuffer =new DefaultEditFieldModel();
protected void insertChar(char ch) {
// don't add control characters
if(!readOnly && (!Character.isISOControl(ch) || (multiLine && ch == '\n'))) {
boolean update = false;
if(hasSelection()) {
deleteSelection();
update = true;
}
if(editBuffer.length() < maxTextLength) {
if(editBuffer.replace(cursorPos, 0, ch)) {
cursorPos++;
update = true;
}
}
if(update) {
updateText(true, false, Event.KEY_NONE);
}
}
}
protected void moveCursor(int dir, boolean select) {
setCursorPos(cursorPos + dir, select);
}
public boolean hasSelection() {
return selectionStart != selectionEnd;
}
private boolean readOnly;
protected void deletePrev() {
if(!readOnly) {
if(hasSelection()) {
deleteSelection();
// updateText(true, false, Event.KEY_DELETE);
} else if(cursorPos > 0) {
--cursorPos;
deleteNext();
}
}
}
protected void deleteNext() {
if(!readOnly) {
if(hasSelection()) {
deleteSelection();
updateText(true, false, Event.KEY_DELETE);
} else if(cursorPos < editBuffer.length()) {
//innerText= innerText.substring(0,cursorPos)+innerText.substring(cursorPos+1);
if(editBuffer.replace(cursorPos, 1, "") >= 0) {
updateText(true, false, Event.KEY_DELETE);
}
}
}
}
private void updateText(boolean updateAutoCompletion, boolean fromModel, int key) {
Document.needUpdate=true;
}
protected void deleteSelection() {
// innerText= innerText.substring(0,selectionStart)+innerText.substring(selectionEnd);
// Document.needUpdate=true;
if(editBuffer.replace(selectionStart, selectionEnd-selectionStart, "") >= 0) {
setCursorPos(selectionStart, false);
}
}
protected void selectWordFromMouse(int index) {
selectionStart = index;
selectionEnd = index;
while(selectionStart > 0 && !Character.isWhitespace(editBuffer.charAt(selectionStart-1))) {
selectionStart--;
}
while(selectionEnd < editBuffer.length() && !Character.isWhitespace(editBuffer.charAt(selectionEnd))) {
selectionEnd++;
}
updateSelection();
}
protected void setCursorPos(int pos, boolean select) {
pos = Math.max(0, Math.min(editBuffer.length(), pos));
if(!select) {
boolean hadSelection = hasSelection();
selectionStart = pos;
selectionEnd = pos;
if(hadSelection) {
updateSelection();
}
}
if(this.cursorPos != pos) {
if(select) {
if(hasSelection()) {
if(cursorPos == selectionStart) {
selectionStart = pos;
} else {
selectionEnd = pos;
}
} else {
selectionStart = cursorPos;
selectionEnd = pos;
}
if(selectionStart > selectionEnd) {
int t = selectionStart;
selectionStart = selectionEnd;
selectionEnd = t;
}
updateSelection();
}
if(this.cursorPos != pos) {
//getAnimationState().resetAnimationTime(STATE_CURSOR_MOVED);
}
this.cursorPos = pos;
scrollToCursor(false);
//updateAutoCompletion();
}
}
protected void scrollToCursor(boolean force) {
Document.needUpdate=true;
int renderWidth = (int)(editBuffer.length()*this.getFontSize()) ;
if(renderWidth <= 0) {
pendingScrollToCursor = true;
pendingScrollToCursorForce = force;
return;
}
pendingScrollToCursor = false;
int xpos = computeRelativeCursorPositionX(cursorPos);
if(xpos < scrollPos + 5) {
scrollPos = Math.max(0, xpos - 5);
} else if(force || xpos - scrollPos > renderWidth) {
scrollPos = Math.max(0, xpos - renderWidth);
}
if(multiLine) {
/* ScrollPane sp = ScrollPane.getContainingScrollPane(this);
if(sp != null) {
int lineHeight = getLineHeight();
int lineY = computeLineNumber(cursorPos) * lineHeight;
sp.validateLayout();
sp.scrollToAreaY(lineY, lineHeight, lineHeight/2);
}*/
}
}
protected int computeRelativeCursorPositionX(int cursorPos) {
int lineStart = 0;
if(multiLine) {
lineStart = computeLineStart(cursorPos);
}
return (int) ((cursorPos-lineStart)*getFontSize());
// return textRenderer.computeRelativeCursorPositionX(lineStart, cursorPos);
}
protected int computeLineStart(int cursorPos) {
if(!multiLine) {
return 0;
}
while(cursorPos > 0 && editBuffer.charAt(cursorPos-1) != '\n') {
cursorPos--;
}
return cursorPos;
}
public void selectAll() {
selectionStart = 0;
selectionEnd = editBuffer.length();
updateSelection();
}
public void pasteFromClipboard() {
String cbText = Clipboard.getClipboard();
if(cbText != null) {
if(!multiLine) {
cbText = TextUtil.stripNewLines(cbText);
}
insertText(cbText);
}
}
public String getSelectedText() {
return editBuffer.substring(selectionStart, selectionEnd);
}
public String getText() {
return editBuffer.toString();
}
public void copyToClipboard() {
String text;
if(hasSelection()) {
text = getSelectedText();
} else {
text = getText();
}
if(isPasswordMasking()) {
text = TextUtil.createString(passwordChar, text.length());
}
Clipboard.setClipboard(text);
}
static class PasswordMasker implements CharSequence {
final CharSequence base;
final char maskingChar;
public PasswordMasker(CharSequence base, char maskingChar) {
this.base = base;
this.maskingChar = maskingChar;
}
public int length() {
return base.length();
}
public char charAt(int index) {
return maskingChar;
}
public CharSequence subSequence(int start, int end) {
throw new UnsupportedOperationException("Not supported.");
}
}
private PasswordMasker passwordMasking;
public boolean isPasswordMasking() {
return passwordMasking != null;
}
public void insertText(String str) {
if(!readOnly) {
boolean update = false;
if(hasSelection()) {
deleteSelection();
update = true;
}
int insertLength = Math.min(str.length(), maxTextLength - editBuffer.length());
if(insertLength > 0) {
int inserted = editBuffer.replace(cursorPos, 0, str.substring(0, insertLength));
if(inserted > 0) {
cursorPos += inserted;
update = true;
}
}
if(update) {
updateText(true, false, Event.KEY_NONE);
}
}
}
public void cutToClipboard() {
String text;
if(!hasSelection()) {
selectAll();
}
text = getSelectedText();
if(!readOnly) {
deleteSelection();
updateText(true, false, Event.KEY_DELETE);
}
if(isPasswordMasking()) {
text = TextUtil.createString(passwordChar, text.length());
}
Clipboard.setClipboard(text);
}
public void duplicateLineDown() {
if(multiLine && !readOnly) {
int lineStart, lineEnd;
if(hasSelection()) {
lineStart = selectionStart;
lineEnd = selectionEnd;
} else {
lineStart = cursorPos;
lineEnd = cursorPos;
}
lineStart = computeLineStart(lineStart);
lineEnd = computeLineEnd(lineEnd);
String line = editBuffer.substring(lineStart, lineEnd);
line = "\n".concat(line);
editBuffer.replace(lineEnd, 0, line);
setCursorPos(cursorPos + line.length());
updateText(true, false, Event.KEY_NONE);
}
}
public void setCursorPos(int pos) {
if(pos < 0 || pos > editBuffer.length()) {
throw new IllegalArgumentException("pos");
}
setCursorPos(pos, false);
}
protected boolean hasFocusOrPopup() {
return hasKeyboardFocus() || hasOpenPopups();
}
/*protected class TextRenderer extends TextWidget {
int lastTextX;
int lastScrollPos;
AttributedStringFontCache cache;
boolean cacheDirty;
protected TextRenderer(AnimationState animState) {
super(animState);
}
@Override
protected void paintWidget(GUI gui) {
if(pendingScrollToCursor) {
scrollToCursor(pendingScrollToCursorForce);
}
lastScrollPos = hasFocusOrPopup() ? scrollPos : 0;
lastTextX = computeTextX();
Font font = getFont();
if(attributes != null && font instanceof Font2) {
paintWithAttributes((Font2)font);
} else if(hasSelection() && hasFocusOrPopup()) {//如果有选中或者获得焦点
if(multiLine) {
paintMultiLineWithSelection();
} else {
paintWithSelection(0, editBuffer.length(), computeTextY());
}
} else {
paintLabelText(getAnimationState());
}
}
protected void paintWithSelection(int lineStart, int lineEnd, int yoff) {
int selStart = selectionStart;
int selEnd = selectionEnd;
if(selectionImage != null && selEnd > lineStart && selStart <= lineEnd) {
int xpos0 = lastTextX + computeRelativeCursorPositionX(lineStart, selStart);
int xpos1 = (lineEnd < selEnd) ? getInnerRight() :
lastTextX + computeRelativeCursorPositionX(lineStart, Math.min(lineEnd, selEnd));
selectionImage.draw(getAnimationState(), xpos0, yoff,
xpos1 - xpos0, getFont().getLineHeight());
}
paintWithSelection(getAnimationState(), selStart, selEnd, lineStart, lineEnd, yoff);
}
protected void paintMultiLineWithSelection() {
final EditFieldModel eb = editBuffer;
int lineStart = 0;
int endIndex = eb.length();
int yoff = computeTextY();
int lineHeight = getLineHeight();
while(lineStart < endIndex) {
int lineEnd = computeLineEnd(lineStart);
paintWithSelection(lineStart, lineEnd, yoff);
yoff += lineHeight;
lineStart = lineEnd + 1;
}
}
protected void paintMultiLineSelectionBackground() {
int lineHeight = getLineHeight();
int lineStart = computeLineStart(selectionStart);
int lineNumber = computeLineNumber(lineStart);
int endIndex = selectionEnd;
int yoff = computeTextY() + lineHeight * lineNumber;
int xstart = lastTextX + computeRelativeCursorPositionX(lineStart, selectionStart);
while(lineStart < endIndex) {
int lineEnd = computeLineEnd(lineStart);
int xend;
if(lineEnd < endIndex) {
xend = getInnerRight();
} else {
xend = lastTextX + computeRelativeCursorPositionX(lineStart, endIndex);
}
selectionImage.draw(getAnimationState(), xstart, yoff, xend - xstart, lineHeight);
yoff += lineHeight;
lineStart = lineEnd + 1;
xstart = getInnerX();
}
}
protected void paintWithAttributes(Font2 font) {
if(selectionEnd > selectionStart && selectionImage != null) {
paintMultiLineSelectionBackground();
}
if(cache == null || cacheDirty) {
cacheDirty = false;
if(multiLine) {
cache = font.cacheMultiLineText(cache, attributes);
} else {
cache = font.cacheText(cache, attributes);
}
}
int y = computeTextY();
if(cache != null) {
cache.draw(lastTextX, y);
} else if(multiLine) {
font.drawMultiLineText(lastTextX, y, attributes);
} else {
font.drawText(lastTextX, y, attributes);
}
}
@Override
protected void sizeChanged() {
if(scrollToCursorOnSizeChange) {
scrollToCursor(true);
}
}
@Override
protected int computeTextX() {
int x = getInnerX();
int pos = getAlignment().hpos;
if(pos > 0) {
x += Math.max(0, getInnerWidth() - computeTextWidth()) * pos / 2;
}
return x - lastScrollPos;
}
@Override
public void destroy() {
super.destroy();
if(cache != null) {
cache.destroy();
cache = null;
}
}
}÷*/
public interface Callback {
/**
* Gets called for any change in the edit field, or when ESCAPE or RETURN was pressed
*
* @param key One of KEY_NONE, KEY_ESCAPE, KEY_RETURN, KEY_DELETE
* @see Event#KEY_NONE
* @see Event#KEY_ESCAPE
* @see Event#KEY_RETURN
* @see Event#KEY_DELETE
*/
public void callback(int key);
}
protected void doCallback(int key) {
if(callbacks != null) {
for(Callback cb : callbacks) {
cb.callback(key);
}
}
}
public void addCallback(Callback cb) {
callbacks = CallbackSupport.addCallbackToList(callbacks, cb, Callback.class);
}
private Callback[] callbacks;
}
| 34.626492 | 230 | 0.521487 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.