text
stringlengths 7
1.01M
|
|---|
package link.ebbinghaus.planning.ui.view.extension.fragment;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.yurikami.lib.base.BaseFragment;
import butterknife.Bind;
import butterknife.ButterKnife;
import link.ebbinghaus.planning.R;
import link.ebbinghaus.planning.ui.presenter.extension.ExtensionPresenter;
import link.ebbinghaus.planning.ui.presenter.extension.impl.ExtensionPresenterImpl;
import link.ebbinghaus.planning.ui.view.extension.ExtensionView;
import link.ebbinghaus.planning.ui.view.extension.activity.ExtensionReadActivity;
import link.ebbinghaus.planning.ui.view.extension.activity.ExtensionTaskStackActivity;
import link.ebbinghaus.planning.ui.view.extension.activity.ExtensionTimeSaverActivity;
public class ExtensionFragment extends BaseFragment implements ExtensionView,View.OnClickListener{
@Bind(R.id.tb_common_head) Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
@Bind(R.id.ll_extension_read) LinearLayout readLl;
@Bind(R.id.ll_extension_fragment_time_saver) LinearLayout timeSaverLl;
@Bind(R.id.ll_extension_task_stack) LinearLayout taskStackLl;
private ExtensionPresenter mPresenter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_extension, container, false);
ButterKnife.bind(this,v);
mPresenter = new ExtensionPresenterImpl(this);
configureToolbar();
initExtension();
return v;
}
private void configureToolbar() {
mActivity.setSupportActionBar(mToolbar);
mToolbar.setTitle(R.string.extension_title);
mToolbar.setNavigationIcon(R.drawable.common_navigation_menu);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
mDrawerLayout = (DrawerLayout) mActivity.findViewById(R.id.dl_main_whole);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void initExtension() {
readLl.setOnClickListener(this);
timeSaverLl.setOnClickListener(this);
taskStackLl.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.ll_extension_read:
startActivity(ExtensionReadActivity.class);
break;
case R.id.ll_extension_fragment_time_saver:
startActivity(ExtensionTimeSaverActivity.class);
break;
case R.id.ll_extension_task_stack:
startActivity(ExtensionTaskStackActivity.class);
}
}
}
|
package scraper.util.patterns;
import java.util.regex.Pattern;
class CommentBlockReplacer extends PatternReplacer {
CommentBlockReplacer() {
super.pattern = Pattern.compile("(```){1,}?(.+?)(```){1,}", Pattern.DOTALL | Pattern.MULTILINE);
super.replacement = "";
}
}
|
/*
* Copyright 2007 Google 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.google.javascript.jscomp;
import static com.google.javascript.rhino.Token.CALL;
import static com.google.javascript.rhino.Token.GETPROP;
import static com.google.javascript.rhino.Token.NAME;
import static com.google.javascript.rhino.Token.STRING;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NO_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.Visitor;
import com.google.javascript.rhino.Node;
import java.util.Map;
/**
* A reverse abstract interpreter (RAI) for specific closure patterns such as
* {@code goog.isDef}.
*
*
*/
class ClosureReverseAbstractInterpreter
extends ChainableReverseAbstractInterpreter {
/**
* For when {@code goog.isArray} returns true.
*/
private final Visitor<JSType> restrictToArrayVisitor =
new RestrictByTrueTypeOfResultVisitor() {
@Override
protected JSType caseTopType(JSType topType) {
// Ideally, we would like to return any subtype of Array.
// Since that's not possible, we don't restrict the type.
return topType;
}
@Override
public JSType caseObjectType(ObjectType type) {
JSType arrayType = getNativeType(ARRAY_TYPE);
return arrayType.isSubtype(type) ? arrayType : null;
}
};
/**
* For when {@code goog.isArray} returns false.
*/
private final Visitor<JSType> restrictToNotArrayVisitor =
new RestrictByFalseTypeOfResultVisitor() {
@Override
public JSType caseObjectType(ObjectType type) {
return type.isSubtype(getNativeType(ARRAY_TYPE)) ? null : type;
}
};
/**
* For when {@code goog.isObject} returns true. This includes functions, but
* not {@code null}.
*/
private final Visitor<JSType> restrictToObjectVisitor =
new RestrictByTrueTypeOfResultVisitor() {
@Override
protected JSType caseTopType(JSType topType) {
return getNativeType(NO_OBJECT_TYPE);
}
@Override
public JSType caseObjectType(ObjectType type) {
return type;
}
@Override
public JSType caseFunctionType(FunctionType type) {
return type;
}
};
/**
* For when {@code goog.isObject} returns false.
*/
private final Visitor<JSType> restrictToNotObjectVisitor =
new RestrictByFalseTypeOfResultVisitor() {
@Override
public JSType caseObjectType(ObjectType type) {
return null;
}
@Override
public JSType caseFunctionType(FunctionType type) {
return null;
}
};
/** Functions used to restrict types. */
private Map<String, Function<TypeRestriction, JSType>> restricters;
/**
* Creates a {@link ClosureReverseAbstractInterpreter}.
*/
ClosureReverseAbstractInterpreter(CodingConvention convention,
final JSTypeRegistry typeRegistry) {
super(convention, typeRegistry);
this.restricters =
new ImmutableMap.Builder<String, Function<TypeRestriction, JSType>>()
.put("isDef", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
if (p.outcome) {
return getRestrictedWithoutUndefined(p.type);
} else {
return null;
}
}
})
.put("isNull", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
if (p.outcome) {
return getNativeType(NULL_TYPE);
} else {
return getRestrictedWithoutNull(p.type);
}
}
})
.put("isDefAndNotNull", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
if (p.outcome) {
return getRestrictedWithoutUndefined(
getRestrictedWithoutNull(p.type));
} else {
return null;
}
}
})
.put("isString", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
return getRestrictedByTypeOfResult(p.type, "string", p.outcome);
}
})
.put("isBoolean", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
return getRestrictedByTypeOfResult(p.type, "boolean", p.outcome);
}
})
.put("isNumber", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
return getRestrictedByTypeOfResult(p.type, "number", p.outcome);
}
})
.put("isFunction", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
return getRestrictedByTypeOfResult(p.type, "function", p.outcome);
}
})
.put("isArray", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
if (p.type == null) {
return p.outcome ? getNativeType(ARRAY_TYPE) : null;
}
Visitor<JSType> visitor = p.outcome ? restrictToArrayVisitor :
restrictToNotArrayVisitor;
return p.type.visit(visitor);
}
})
.put("isObject", new Function<TypeRestriction, JSType>() {
public JSType apply(TypeRestriction p) {
if (p.type == null) {
return p.outcome ? getNativeType(OBJECT_TYPE) : null;
}
Visitor<JSType> visitor = p.outcome ? restrictToObjectVisitor :
restrictToNotObjectVisitor;
return p.type.visit(visitor);
}
})
.build();
}
@Override
public FlowScope getPreciserScopeKnowingConditionOutcome(Node condition,
FlowScope blindScope, boolean outcome) {
if (condition.getType() == CALL && condition.getChildCount() == 2) {
Node callee = condition.getFirstChild();
Node param = condition.getLastChild();
if (callee.getType() == GETPROP && param.isQualifiedName()) {
JSType paramType = getTypeIfRefinable(param, blindScope);
Node left = callee.getFirstChild();
Node right = callee.getLastChild();
if (left.getType() == NAME && "goog".equals(left.getString()) &&
right.getType() == STRING) {
Function<TypeRestriction, JSType> restricter =
restricters.get(right.getString());
if (restricter != null) {
return restrictParameter(param, paramType, blindScope, restricter,
outcome);
}
}
}
}
return nextPreciserScopeKnowingConditionOutcome(
condition, blindScope, outcome);
}
private FlowScope restrictParameter(Node parameter, JSType type,
FlowScope blindScope, Function<TypeRestriction, JSType> restriction,
boolean outcome) {
// restricting
type = restriction.apply(new TypeRestriction(type, outcome));
// changing the scope
if (type != null) {
FlowScope informed = blindScope.createChildFlowScope();
declareNameInScope(informed, parameter, type);
return informed;
} else {
return blindScope;
}
}
private static class TypeRestriction {
private final JSType type;
private final boolean outcome;
private TypeRestriction(JSType type, boolean outcome) {
this.type = type;
this.outcome = outcome;
}
}
}
|
package powermock.examples.logging;
import org.apache.log4j.Logger;
public class Log4jUserParent
{
protected static final Logger log = Logger.getLogger(Log4jUserParent.class);
}
|
package com.example.butterknife.functional;
import android.content.Context;
import android.view.View;
import androidx.test.InstrumentationRegistry;
import butterknife.BindArray;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.example.butterknife.test.R;
import org.junit.Test;
import static com.google.common.truth.Truth.assertThat;
public final class BindArrayTest {
private final Context context = InstrumentationRegistry.getContext();
private final View tree = ViewTree.create(1);
static class StringArrayTarget {
@BindArray(R.array.string_one_two_three) String[] actual;
}
@Test public void asStringArray() {
StringArrayTarget target = new StringArrayTarget();
String[] expected = context.getResources().getStringArray(R.array.string_one_two_three);
Unbinder unbinder = ButterKnife.bind(target, tree);
assertThat(target.actual).isEqualTo(expected);
unbinder.unbind();
assertThat(target.actual).isEqualTo(expected);
}
static class IntArrayTarget {
@BindArray(R.array.int_one_two_three) int[] actual;
}
@Test public void asIntArray() {
IntArrayTarget target = new IntArrayTarget();
int[] expected = context.getResources().getIntArray(R.array.int_one_two_three);
Unbinder unbinder = ButterKnife.bind(target, tree);
assertThat(target.actual).isEqualTo(expected);
unbinder.unbind();
assertThat(target.actual).isEqualTo(expected);
}
static class CharSequenceArrayTarget {
@BindArray(R.array.int_one_two_three) CharSequence[] actual;
}
@Test public void asCharSequenceArray() {
CharSequenceArrayTarget target = new CharSequenceArrayTarget();
CharSequence[] expected = context.getResources().getTextArray(R.array.int_one_two_three);
Unbinder unbinder = ButterKnife.bind(target, tree);
assertThat(target.actual).isEqualTo(expected);
unbinder.unbind();
assertThat(target.actual).isEqualTo(expected);
}
}
|
package com.socrata.datasync.deltaimporter2;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown=true)
public class DI2Error {
public ErrorType type;
public Map<String, Object> data;
@JsonDeserialize(using=ErrorTypeDeserializer.class)
public enum ErrorType {
NOT_A_COMMIT_DESCRIPTION("not-a-commit-description"),
FILENAME_BAD_CHARACTERS("filename-bad-characters"),
FILENAME_TOO_LONG("filename-too-long"),
IMPOSSIBLE_RELATIVE_TO("impossible-relative-to"),
UNDECODABLE_CONTROL("undecodable-control"),
NON_UNIFORM_CHUNK("non-uniform-chunk"),
NONEXISTANT_CHUNK("non-existant-chunk"),
SIZE_MISMATCH("size-mismatch");
public final String tag;
ErrorType(String tag) {
this.tag = tag;
}
}
public static class ErrorTypeDeserializer extends JsonDeserializer<ErrorType> {
private static final Map<String, ErrorType> errorTypes;
static {
Map<String, ErrorType> map = new HashMap<>();
for(ErrorType e : ErrorType.values()) {
map.put(e.tag, e);
}
errorTypes = Collections.unmodifiableMap(map);
}
@Override
public ErrorType deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
if(jsonParser.getCurrentToken() != JsonToken.VALUE_STRING) throw deserializationContext.wrongTokenException(jsonParser, JsonToken.VALUE_STRING, "Expected string");
String code = jsonParser.getText();
ErrorType result = errorTypes.get(code);
if(result == null) throw deserializationContext.weirdStringException(code, ErrorType.class, "Unknown error code");
return result;
}
}
}
|
package com.atguigu.gmall.wms.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import java.util.Map;
/**
* 商品库存
*
* @author 小伙 not bad
* @email xiaohubulaiya@163.com
* @date 2021-04-30 13:56:28
*/
public interface WareSkuService extends IService<WareSkuEntity> {
PageResultVo queryPage(PageParamVo paramVo);
}
|
package io.github.dipo33.gtmapaddon.storage;
import com.sinthoras.visualprospecting.Utils;
public class MinedChunk {
private final int chunkX;
private final int chunkZ;
private final int dimensionId;
private final String minedBy;
public MinedChunk(int chunkX, int chunkZ, int dimensionId, String minedBy) {
this.chunkX = chunkX;
this.chunkZ = chunkZ;
this.dimensionId = dimensionId;
this.minedBy = minedBy;
}
public int getChunkX() {
return chunkX;
}
public int getBlockX() {
return Utils.coordChunkToBlock(chunkX) + 8;
}
public int getChunkZ() {
return chunkZ;
}
public int getBlockZ() {
return Utils.coordChunkToBlock(chunkZ) + 8;
}
public int getDimensionId() {
return dimensionId;
}
public String getMinedBy() {
return minedBy;
}
}
|
/*
* 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.camel.impl.engine;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.Validator;
import org.apache.camel.spi.ValidatorRegistry;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.service.ServiceHelper;
import org.apache.camel.util.ObjectHelper;
/**
* Default implementation of {@link org.apache.camel.spi.ValidatorRegistry}.
*/
public class DefaultValidatorRegistry extends AbstractDynamicRegistry<ValidatorKey, Validator>
implements ValidatorRegistry<ValidatorKey> {
public DefaultValidatorRegistry(CamelContext context) {
super(context, CamelContextHelper.getMaximumValidatorCacheSize(context));
}
@Override
public Validator resolveValidator(ValidatorKey key) {
Validator answer = get(key);
if (answer == null && ObjectHelper.isNotEmpty(key.getType().getName())) {
answer = get(new ValidatorKey(new DataType(key.getType().getModel())));
}
return answer;
}
@Override
public boolean isStatic(DataType type) {
return isStatic(new ValidatorKey(type));
}
@Override
public boolean isDynamic(DataType type) {
return isDynamic(new ValidatorKey(type));
}
@Override
public String toString() {
return "ValidatorRegistry for " + context.getName() + ", capacity: " + maxCacheSize;
}
@Override
public Validator put(ValidatorKey key, Validator validator) {
// ensure validator is started before its being used
ServiceHelper.startService(validator);
return super.put(key, validator);
}
}
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.codeStyle;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
@State(name = "CodeStyleSettingsManager", storages = @Storage("code.style.schemes"))
public class AppCodeStyleSettingsManager extends CodeStyleSettingsManager {
}
|
package dev.vinothm.algorithms;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
class SubarrayDivisionTest {
@Test
void testBirthday() {
var divider = new SubarrayDivision();
assertEquals(divider.birthday(List.of(1, 2, 1, 3, 2), 3, 2), 2);
}
}
|
/* Copyright (c) 2017 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.robotcontroller.external.samples;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
/**
* This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either
* the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu
* of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode
* class is instantiated on the Robot Controller and executed.
*
* This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot
* It includes all the skeletal structure that all linear OpModes contain.
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@TeleOp(name="Test", group="Linear Opmode")
@Disabled
public class BasicOpMode_Linear extends LinearOpMode {
// Declare OpMode members.
private ElapsedTime runtime = new ElapsedTime();
private DcMotor leftDrive = null;
private DcMotor rightDrive = null;
@Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
telemetry.update();
// Initialize the hardware variables. Note that the strings used here as parameters
// to 'get' must correspond to the names assigned during the robot configuration
// step (using the FTC Robot Controller app on the phone).
leftDrive = hardwareMap.get(DcMotor.class, "left_drive");
rightDrive = hardwareMap.get(DcMotor.class, "right_drive");
// Most robots need the motor on one side to be reversed to drive forward
// Reverse the motor that runs backwards when connected directly to the battery
leftDrive.setDirection(DcMotor.Direction.FORWARD);
rightDrive.setDirection(DcMotor.Direction.REVERSE);
// Wait for the game to start (driver presses PLAY)
waitForStart();
runtime.reset();
// run until the end of the match (driver presses STOP)
while (opModeIsActive()) {
// Setup a variable for each drive wheel to save power level for telemetry
double leftPower;
double rightPower;
// Choose to drive using either Tank Mode, or POV Mode
// Comment out the method that's not used. The default below is POV.
// POV Mode uses left stick to go forward, and right stick to turn.
// - This uses basic math to combine motions and is easier to drive straight.
double drive = -gamepad1.left_stick_y;
double turn = gamepad1.right_stick_x;
leftPower = Range.clip(drive + turn, -1.0, 1.0) ;
rightPower = Range.clip(drive - turn, -1.0, 1.0) ;
// Tank Mode uses one stick to control each wheel.
// - This requires no math, but it is hard to drive forward slowly and keep straight.
// leftPower = -gamepad1.left_stick_y ;
// rightPower = -gamepad1.right_stick_y ;
// Send calculated power to wheels
leftDrive.setPower(leftPower);
rightDrive.setPower(rightPower);
// Show the elapsed game time and wheel power.
telemetry.addData("Status", "Run Time: " + runtime.toString());
telemetry.addData("Motors", "left (%.2f), right (%.2f)", leftPower, rightPower);
telemetry.update();
}
}
}
|
/**
* This file is part of the Iritgo/Aktario Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktario.core.logger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
/**
* A logger that prints logging messages to an output stream.
*/
public class OutputStreamLogger implements Logger
{
/** The current time. */
private Date currentTime;
/** Used to format the current time. */
private DateFormat timeFormat;
/** The output stream to log to. */
private PrintWriter out;
/**
* Create a new output stream logger.
*
* @param out The output stream to log to.
*/
public OutputStreamLogger(OutputStream out)
{
currentTime = new Date();
timeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
this.out = new PrintWriter(out);
}
/**
* Get the id of the Logger
*
* @return The logger id.
*/
public String getId()
{
return "OutputStream";
}
/**
* Initialize the logger.
*
* @param category The logger category.
*/
public void init(String category)
{
}
/**
* Free all logger resources.
*/
public void dispose()
{
}
/**
* Log a message.
*
* @param category The logger category.
* @param source The logging source.
* @param message The log message.
* @param level The logging level.
*/
public void log(String category, String source, String message, int level)
{
currentTime.setTime(System.currentTimeMillis());
out.println("" + timeFormat.format(currentTime) + " " + Log.logLevelName(level) + " [" + category + "] ["
+ source + "] " + message);
out.flush();
}
}
|
/*
* Copyright 2020-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work was partially supported by EC H2020 project METRO-HAUL (761727).
*/
package org.onosproject.drivers.odtn.openconfig;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range;
import gnmi.Gnmi;
import org.onosproject.gnmi.api.GnmiClient;
import org.onosproject.gnmi.api.GnmiController;
import org.onosproject.gnmi.api.GnmiUtils.GnmiPathBuilder;
import org.onosproject.grpc.utils.AbstractGrpcHandlerBehaviour;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.behaviour.PowerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
/**
* PowerConfig behaviour for gNMI and OpenConfig model based device.
*/
public class GnmiTerminalDevicePowerConfig<T>
extends AbstractGrpcHandlerBehaviour<GnmiClient, GnmiController>
implements PowerConfig<T> {
private static final Logger log = LoggerFactory.getLogger(GnmiTerminalDevicePowerConfig.class);
private static final int DEFAULT_OC_POWER_PRECISION = 2;
private static final Collection<Port.Type> OPTICAL_TYPES = ImmutableSet.of(Port.Type.FIBER,
Port.Type.PACKET,
Port.Type.ODUCLT,
Port.Type.OCH,
Port.Type.OMS,
Port.Type.OTU);
public GnmiTerminalDevicePowerConfig() {
super(GnmiController.class);
}
@Override
public Optional<Double> getTargetPower(PortNumber port, T component) {
if (!setupBehaviour("getTargetPower")) {
return Optional.empty();
}
if (!isOpticalPort(port)) {
return Optional.empty();
}
// path: /components/component[name=<name>]/optical-channel/config/target-output-power
return getValueFromPath(getOcName(port), "config/target-output-power");
}
@Override
public void setTargetPower(PortNumber port, T component, double power) {
if (!setupBehaviour("setTargetPower")) {
return;
}
if (!isOpticalPort(port)) {
return;
}
setValueToPath(getOcName(port), "config/target-output-power", power);
}
@Override
public Optional<Double> currentPower(PortNumber port, T component) {
if (!setupBehaviour("currentPower")) {
return Optional.empty();
}
if (!isOpticalPort(port)) {
return Optional.empty();
}
// path: /components/component[name=<name>]/optical-channel/state/output-power/instant
return getValueFromPath(getOcName(port), "state/output-power/instant");
}
@Override
public Optional<Double> currentInputPower(PortNumber port, T component) {
if (!setupBehaviour("currentInputPower")) {
return Optional.empty();
}
if (!isOpticalPort(port)) {
return Optional.empty();
}
// path: /components/component[name=<name>]/optical-channel/state/input-power/instant
return getValueFromPath(getOcName(port), "state/input-power/instant");
}
@Override
public Optional<Range<Double>> getTargetPowerRange(PortNumber port, Object component) {
if (!isOpticalPort(port)) {
return Optional.empty();
}
// From CassiniTerminalDevicePowerConfig
double targetMin = -30;
double targetMax = 1;
return Optional.of(Range.open(targetMin, targetMax));
}
@Override
public Optional<Range<Double>> getInputPowerRange(PortNumber port, Object component) {
if (!isOpticalPort(port)) {
return Optional.empty();
}
// From CassiniTerminalDevicePowerConfig
double targetMin = -30;
double targetMax = 1;
return Optional.of(Range.open(targetMin, targetMax));
}
private String getOcName(PortNumber portNumber) {
if (!setupBehaviour("getOcName")) {
return null;
}
return deviceService.getPort(deviceId, portNumber).annotations().value("oc-name");
}
private boolean isOpticalPort(PortNumber portNumber) {
if (!setupBehaviour("isOpticalPort")) {
return false;
}
return OPTICAL_TYPES.contains(deviceService.getPort(deviceId, portNumber).type());
}
private Optional<Double> getValueFromPath(String ocName, String subPath) {
Gnmi.GetRequest req = Gnmi.GetRequest.newBuilder()
.addPath(buildPathWithSubPath(ocName, subPath))
.setEncoding(Gnmi.Encoding.PROTO)
.build();
try {
Gnmi.GetResponse resp = client.get(req).get();
// Here we assume we have only one response
if (resp.getNotificationCount() == 0 || resp.getNotification(0).getUpdateCount() == 0) {
log.warn("Empty response for sub-path {}, component {}", subPath, ocName);
return Optional.empty();
}
Gnmi.Update update = resp.getNotification(0).getUpdate(0);
Gnmi.Decimal64 value = update.getVal().getDecimalVal();
return Optional.of(decimal64ToDouble(value));
} catch (ExecutionException | InterruptedException e) {
log.warn("Unable to get value from optical sub-path {} for component {}: {}",
subPath, ocName, e.getMessage());
return Optional.empty();
}
}
private void setValueToPath(String ocName, String subPath, Double value) {
Gnmi.TypedValue val = Gnmi.TypedValue.newBuilder()
.setDecimalVal(doubleToDecimal64(value, DEFAULT_OC_POWER_PRECISION))
.build();
Gnmi.Update update = Gnmi.Update.newBuilder()
.setPath(buildPathWithSubPath(ocName, subPath))
.setVal(val)
.build();
Gnmi.SetRequest req = Gnmi.SetRequest.newBuilder()
.addUpdate(update)
.build();
try {
client.set(req).get();
} catch (ExecutionException | InterruptedException e) {
log.warn("Unable to set optical sub-path {}, component {}, value {}: {}",
subPath, ocName, value, e.getMessage());
}
}
private Gnmi.Path buildPathWithSubPath(String ocName, String subPath) {
String[] elems = subPath.split("/");
GnmiPathBuilder pathBuilder = GnmiPathBuilder.newBuilder()
.addElem("components")
.addElem("component").withKeyValue("name", ocName)
.addElem("optical-channel");
for (String elem : elems) {
pathBuilder.addElem(elem);
}
return pathBuilder.build();
}
private Double decimal64ToDouble(Gnmi.Decimal64 value) {
double result = value.getDigits();
if (value.getPrecision() != 0) {
result = result / Math.pow(10, value.getPrecision());
}
return result;
}
private Gnmi.Decimal64 doubleToDecimal64(Double value, int precision) {
return Gnmi.Decimal64.newBuilder()
.setDigits((long) (value * Math.pow(10, precision)))
.setPrecision(precision)
.build();
}
}
|
package org.cocos2d.layers;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL10;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteSheet;
import org.cocos2d.nodes.CCTextureCache;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
import org.cocos2d.types.CGSize;
import org.cocos2d.utils.CCFormatter;
/*
* TMX Tiled Map support:
* http://www.mapeditor.org
*
*/
/** CCTMXLayer represents the TMX layer.
It is a subclass of CCSpriteSheet. By default the tiles are rendered using a CCTextureAtlas.
If you mofify a tile on runtime, then, that tile will become a CCSprite, otherwise no CCSprite objects are created.
The benefits of using CCSprite objects as tiles are:
- tiles (CCSprite) can be rotated/scaled/moved with a nice API
If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
glAlphaFunc( GL_GREATER, value )
"value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a differnt
value, like 0.5.
For further information, please see the programming guide:
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
@since v0.8.1
*/
public class CCTMXLayer extends CCSpriteSheet {
/** Tilset information for the layer */
public CCTMXTilesetInfo tileset;
/** name of the layer */
public String layerName;
/** size of the layer in tiles */
public CGSize layerSize;
/** size of the map's tile (could be differnt from the tile's size) */
public CGSize mapTileSize;
/** pointer to the map of tiles */
public IntBuffer tiles;
/** Layer orientation, which is the same as the map orientation */
public int layerOrientation_;
/** properties from the layer. They can be added using Tiled */
public HashMap<String, String> properties;
int opacity_; // TMX Layer supports opacity
int minGID_;
int maxGID_;
// Only used when vertexZ is used
int vertexZvalue_;
boolean useAutomaticVertexZ_;
float alphaFuncValue_;
// used for optimization
CCSprite reusedTile_;
ArrayList<Integer> atlasIndexArray_;
/** creates a CCTMXLayer with an tileset info, a layer info and a map info */
public static CCTMXLayer layer(CCTMXTilesetInfo tilesetInfo, CCTMXLayerInfo layerInfo, CCTMXMapInfo mapInfo) {
return new CCTMXLayer(tilesetInfo, layerInfo, mapInfo);
}
/** initializes a CCTMXLayer with a tileset info, a layer info and a map info */
protected CCTMXLayer(CCTMXTilesetInfo tilesetInfo, CCTMXLayerInfo layerInfo, CCTMXMapInfo mapInfo) {
super(tilesetInfo==null?null:CCTextureCache.sharedTextureCache().addImage(tilesetInfo.sourceImage),
(int) ((layerInfo.layerSize.width*layerInfo.layerSize.height)*0.35f + 1));
// layerInfo
layerName = layerInfo.name;
layerSize = layerInfo.layerSize;
tiles = layerInfo.tiles;
minGID_ = layerInfo.minGID;
maxGID_ = layerInfo.maxGID;
opacity_ = layerInfo.opacity;
properties = new HashMap<String, String>(layerInfo.properties);
// tilesetInfo
tileset = tilesetInfo;
// mapInfo
mapTileSize = mapInfo.tileSize;
layerOrientation_ = mapInfo.orientation;
// offset (after layer orientation is set);
CGPoint offset = calculateLayerOffset(layerInfo.offset);
setPosition(offset);
atlasIndexArray_ = new ArrayList<Integer>();
int totalNumberOfTiles = (int) ((layerInfo.layerSize.width*layerInfo.layerSize.height)*0.35f + 1);
atlasIndexArray_.ensureCapacity(totalNumberOfTiles);
setContentSize(CGSize.make(layerSize.width * mapTileSize.width, layerSize.height * mapTileSize.height ));
useAutomaticVertexZ_= false;
vertexZvalue_ = 0;
alphaFuncValue_ = 0;
}
/** dealloc the map that contains the tile position from memory.
Unless you want to know at runtime the tiles positions, you can safely call this method.
If you are going to call [layer tileGIDAt:] then, don't release the map
*/
public void releaseMap() {
if (tiles != null) {
tiles = null;
}
if (atlasIndexArray_ != null) {
atlasIndexArray_ = null;
}
}
/** returns the tile (CCSprite) at a given a tile coordinate.
The returned CCSprite will be already added to the CCTMXLayer. Don't add it again.
The CCSprite can be treated like any other CCSprite: rotated, scaled, translated, opacity, color, etc.
You can remove either by calling:
- [layer removeChild:sprite cleanup:cleanup];
- or [layer removeTileAt:ccp(x,y)];
*/
public CCSprite tileAt(CGPoint pos) {
assert(pos.x < layerSize.width && pos.y < layerSize.height && pos.x >=0 && pos.y >=0):"TMXLayer: invalid position";
assert(tiles!=null && atlasIndexArray_!=null):"TMXLayer: the tiles map has been released";
CCSprite tile = null;
int gid = tileGIDAt(pos);
// if GID == 0, then no tile is present
if (gid != 0) {
int z = (int) (pos.x + pos.y * layerSize.width);
tile = (CCSprite)getChildByTag(z);
// tile not created yet. create it
if (tile == null) {
CGRect rect = tileset.rectForGID(gid);
tile = CCSprite.sprite(this, rect);
tile.setPosition(positionAt(pos));
tile.setVertexZ(vertexZForPos(pos));
tile.setAnchorPoint(CGPoint.zero());
tile.setOpacity(opacity_);
int indexForZ = atlasIndexForExistantZ(z);
addSpriteWithoutQuad(tile, indexForZ, z);
}
}
return tile;
}
/** returns the tile gid at a given tile coordinate.
if it returns 0, it means that the tile is empty.
This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap])
*/
public int tileGIDAt(CGPoint pos) {
assert( pos.x < layerSize.width && pos.y < layerSize.height && pos.x >=0 && pos.y >=0): "TMXLayer: invalid position";
assert( tiles!=null && atlasIndexArray_!=null) :"TMXLayer: the tiles map has been released";
int idx = (int) (pos.x + pos.y * layerSize.width);
return tiles.get(idx);
}
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
*/
public void setTileGID(int gid, CGPoint pos) {
assert( pos.x < layerSize.width && pos.y < layerSize.height && pos.x >=0 && pos.y >=0): "TMXLayer: invalid position";
assert( tiles!=null && atlasIndexArray_!=null):"TMXLayer: the tiles map has been released";
int currentGID = tileGIDAt(pos);
if (currentGID != gid ) {
// setting gid=0 is equal to remove the tile
if( gid == 0 )
removeTileAt(pos);
// empty tile. create a new one
else if( currentGID == 0 )
insertTileForGID(gid, pos);
// modifying an existing tile with a non-empty tile
else {
int z = (int) (pos.x + pos.y * layerSize.width);
CCSprite sprite = (CCSprite) getChildByTag(z);
if (sprite != null) {
CGRect rect = tileset.rectForGID(gid);
sprite.setTextureRect(rect);
tiles.put(z, gid);
} else {
updateTileForGID(gid, pos);
}
}
}
}
/** removes a tile at given tile coordinate */
public void removeTileAt(CGPoint pos) {
assert(pos.x < layerSize.width && pos.y < layerSize.height && pos.x >=0 && pos.y >=0):"TMXLayer: invalid position";
assert(tiles!=null && atlasIndexArray_!=null):"TMXLayer: the tiles map has been released";
int gid = tileGIDAt(pos);
if (gid != 0) {
int z = (int) (pos.x + pos.y * layerSize.width);
int atlasIndex = atlasIndexForExistantZ(z);
// remove tile from GID map
tiles.put(z, 0);
// remove tile from atlas position array
atlasIndexArray_.remove(atlasIndex);
// remove it from sprites and/or texture atlas
CCSprite sprite = (CCSprite) getChildByTag(z);
if (sprite!=null)
super.removeChild(sprite, true);
else {
textureAtlas_.removeQuad(atlasIndex);
// update possible children
for (CCNode node : children_) {
CCSprite s = (CCSprite)node;
int ai = s.atlasIndex;
if( ai >= atlasIndex) {
s.atlasIndex = ai-1;
}
}
}
}
}
/** returns the position in pixels of a given tile coordinate */
public CGPoint positionAt(CGPoint pos) {
CGPoint ret = CGPoint.zero();
switch( layerOrientation_ ) {
case CCTMXTiledMap.CCTMXOrientationOrtho:
ret = positionForOrthoAt(pos);
break;
case CCTMXTiledMap.CCTMXOrientationIso:
ret = positionForIsoAt(pos);
break;
case CCTMXTiledMap.CCTMXOrientationHex:
ret = positionForHexAt(pos);
break;
}
return ret;
}
/** return the value for the specific property name */
public String propertyNamed(String propertyName) {
return properties.get(propertyName);
}
/** Creates the tiles */
public void setupTiles() {
// Optimization: quick hack that sets the image size on the tileset
tileset.imageSize = textureAtlas_.getTexture().getContentSize();
if (tileset.imageSize == null) {
tileset.imageSize = CGSize.zero();
}
// By default all the tiles are aliased
// pros:
// - easier to render
// cons:
// - difficult to scale / rotate / etc.
textureAtlas_.getTexture().setAliasTexParameters();
// Parse cocos2d properties
parseInternalProperties();
for (int y=0; y < layerSize.height; y++) {
for (int x=0; x < layerSize.width; x++) {
int pos = (int) (x + layerSize.width * y);
int gid = tiles.get(pos);
// gid are stored in little endian.
// if host is big endian, then swap
// Java is big endian
// if( o == CFByteOrderBigEndian )
gid = CCFormatter.swapIntToLittleEndian(gid);
// XXX: gid == 0 --> empty tile
if( gid != 0 ) {
appendTileForGID(gid, CGPoint.ccp(x,y));
// Optimization: update min and max GID rendered by the layer
minGID_ = (gid < minGID_? gid : minGID_);
maxGID_ = (gid > maxGID_? gid : maxGID_);
}
}
}
assert( maxGID_ >= tileset.firstGid &&
minGID_ >= tileset.firstGid): "TMX: Only 1 tilset per layer is supported";
}
/** CCTMXLayer doesn't support adding a CCSprite manually.
@warning addchild:z:tag: is not supported on CCTMXLayer. Instead of setTileGID:at:/tileAt:
*/
public CCNode addChild(CCNode node, int z, int tag) {
assert(false):"addChild: is not supported on CCTMXLayer. Instead use setTileGID:at:/tileAt:";
return null;
}
public void removeChild(CCNode node, boolean cleanup) {
// allows removing nil objects
if( node == null)
return;
assert(children_.contains(node)):"Tile does not belong to TMXLayer";
if (node instanceof CCSprite) {
CCSprite sprite = (CCSprite) node;
int atlasIndex = sprite.atlasIndex;
int zz = atlasIndexArray_.get(atlasIndex);
tiles.put(zz, 0);
atlasIndexArray_.remove(atlasIndex);
}
super.removeChild(node, true);
}
private CGPoint calculateLayerOffset(CGPoint pos) {
CGPoint ret = CGPoint.zero();
switch( layerOrientation_ ) {
case CCTMXTiledMap.CCTMXOrientationOrtho:
ret = CGPoint.ccp( pos.x * mapTileSize.width, -pos.y *mapTileSize.height);
break;
case CCTMXTiledMap.CCTMXOrientationIso:
ret = CGPoint.ccp( (mapTileSize.width /2) * (pos.x - pos.y),
(mapTileSize.height /2 ) * (-pos.x - pos.y) );
break;
case CCTMXTiledMap.CCTMXOrientationHex:
assert(CGPoint.equalToPoint(pos, CGPoint.zero())):"offset for hexagonal map not implemented yet";
break;
}
return ret;
}
private CGPoint positionForOrthoAt(CGPoint pos) {
int x = (int) (pos.x * mapTileSize.width + 0.49f);
int y = (int) ((layerSize.height - pos.y - 1) * mapTileSize.height + 0.49f);
return CGPoint.ccp(x,y);
}
private CGPoint positionForIsoAt(CGPoint pos) {
int x = (int) (mapTileSize.width /2 * ( layerSize.width + pos.x - pos.y - 1) + 0.49f);
int y = (int) (mapTileSize.height /2 * (( layerSize.height * 2 - pos.x - pos.y) - 2) + 0.49f);
return CGPoint.ccp(x, y);
}
private CGPoint positionForHexAt(CGPoint pos) {
float diffY = 0;
if( (int)pos.x % 2 == 1 )
diffY = -mapTileSize.height/2 ;
int x = (int) (pos.x * mapTileSize.width*3/4 + 0.49f);
int y = (int) ((layerSize.height - pos.y - 1) * mapTileSize.height + diffY + 0.49f);
return CGPoint.ccp(x,y);
}
private int vertexZForPos(CGPoint pos) {
int ret = 0;
int maxVal = 0;
if( useAutomaticVertexZ_ ) {
switch( layerOrientation_ ) {
case CCTMXTiledMap.CCTMXOrientationIso:
maxVal = (int) (layerSize.width + layerSize.height);
ret = (int) -(maxVal - (pos.x + pos.y));
break;
case CCTMXTiledMap.CCTMXOrientationOrtho:
ret = (int) -(layerSize.height-pos.y);
break;
case CCTMXTiledMap.CCTMXOrientationHex:
assert(false):"TMX Hexa zOrder not supported";
break;
default:
assert(false):"TMX invalid value";
break;
}
} else
ret = vertexZvalue_;
return ret;
}
/* optimization methos */
// used only when parsing the map. useless after the map was parsed
// since lot's of assumptions are no longer true
private CCSprite appendTileForGID(int gid, CGPoint pos) {
CGRect rect = tileset.rectForGID(gid);
int z = (int) (pos.x + pos.y * layerSize.width);
//if( reusedTile_ == null )
reusedTile_ = CCSprite.sprite(this, rect);
//else
// reusedTile_ initWithSpriteSheet:self rect:rect];
reusedTile_.setPosition(positionAt(pos));
reusedTile_.setVertexZ(vertexZForPos(pos));
reusedTile_.setAnchorPoint(CGPoint.zero());
reusedTile_.setOpacity(opacity_);
// optimization:
// The difference between appendTileForGID and insertTileforGID is that append is faster, since
// it appends the tile at the end of the texture atlas
int indexForZ = atlasIndexArray_.size();
// don't add it using the "standard" way.
addQuadFromSprite(reusedTile_, indexForZ);
// append should be after addQuadFromSprite since it modifies the quantity values
atlasIndexArray_.add(indexForZ, z);
return reusedTile_;
}
private CCSprite insertTileForGID(int gid, CGPoint pos) {
CGRect rect = tileset.rectForGID(gid);
int z = (int) (pos.x + pos.y * layerSize.width);
//if ( ! reusedTile_ )
reusedTile_ = CCSprite.sprite(this, rect);
//else
// [reusedTile_ initWithSpriteSheet:self rect:rect];
reusedTile_.setPosition(positionAt(pos));
reusedTile_.setVertexZ(vertexZForPos(pos));
reusedTile_.setAnchorPoint(CGPoint.zero());
reusedTile_.setOpacity(opacity_);
// get atlas index
int indexForZ = atlasIndexForNewZ(z);
// Optimization: add the quad without adding a child
addQuadFromSprite(reusedTile_, indexForZ);
// insert it into the local atlasindex array
atlasIndexArray_.add(indexForZ, z);
// update possible children
for (CCNode node : children_) {
CCSprite sprite = (CCSprite)node;
int ai = sprite.atlasIndex;
if( ai >= indexForZ)
sprite.atlasIndex = ai+1;
}
tiles.put(z, gid);
return reusedTile_;
}
private CCSprite updateTileForGID(int gid, CGPoint pos) {
CGRect rect = tileset.rectForGID(gid);
int z = (int) (pos.x + pos.y * layerSize.width);
//if( ! reusedTile_ )
reusedTile_ = CCSprite.sprite(this, rect);
//else
// [reusedTile_ initWithSpriteSheet:self rect:rect];
reusedTile_.setPosition(positionAt(pos));
reusedTile_.setVertexZ(vertexZForPos(pos));
reusedTile_.setAnchorPoint(CGPoint.zero());
reusedTile_.setOpacity(opacity_);
// get atlas index
int indexForZ = atlasIndexForExistantZ(z);
reusedTile_.atlasIndex = indexForZ;
reusedTile_.updateTransform();
tiles.put(z, gid);
return reusedTile_;
}
/* The layer recognizes some special properties, like cc_vertez */
private void parseInternalProperties() {
// if cc_vertex=automatic, then tiles will be rendered using vertexz
String vertexz = propertyNamed("cc_vertexz");
if( vertexz != null) {
if (vertexz.equals("automatic"))
useAutomaticVertexZ_ = true;
else
vertexZvalue_ = Integer.parseInt(vertexz);
}
String alphaFuncVal = propertyNamed("cc_alpha_func");
alphaFuncValue_ = alphaFuncVal==null?0.0f:Float.parseFloat(alphaFuncVal);
}
// index
private int atlasIndexForExistantZ(int z) {
// int key=z;
// int *item = bsearch((void*)&key, (void*)&atlasIndexArray_->arr[0], atlasIndexArray_->num, sizeof(void*), compareInts);
// assert(item!=null):"TMX atlas index not found. Shall not happen";
// int index = ((int)item - (int)atlasIndexArray_->arr) / sizeof(void*);
int index = atlasIndexArray_.indexOf(z);
return index;
}
private int atlasIndexForNewZ(int z) {
// XXX: This can be improved with a sort of binary search
int i=0;
for( i=0; i< atlasIndexArray_.size() ; i++) {
int val = (int) atlasIndexArray_.get(i);
if (z < val)
break;
}
return i;
}
public int compareInts (final int a, final int b) {
return (a - b );
}
@Override
public void draw(GL10 gl) {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if( useAutomaticVertexZ_ ) {
gl.glEnable(GL10.GL_ALPHA_TEST);
gl.glAlphaFunc(GL10.GL_GREATER, alphaFuncValue_);
}
super.draw(gl);
if( useAutomaticVertexZ_ ) {
gl.glDisable(GL10.GL_ALPHA_TEST);
}
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
}
}
|
/*
File: StructSdtB707_SD02_REG_MEMO_RTN
Description: B707_SD02_REG_MEMO_RTN
Author: GeneXus Java Generator version 10_3_3-92797
Generated on: July 3, 2017 17:20:58.13
Program type: Callable routine
Main DBMS: mysql
*/
import com.genexus.*;
public final class StructSdtB707_SD02_REG_MEMO_RTN implements Cloneable, java.io.Serializable
{
public StructSdtB707_SD02_REG_MEMO_RTN( )
{
gxTv_SdtB707_SD02_REG_MEMO_RTN_Result_cd = "" ;
gxTv_SdtB707_SD02_REG_MEMO_RTN_Err_msg = "" ;
}
public Object clone()
{
Object cloned = null;
try
{
cloned = super.clone();
}catch (CloneNotSupportedException e){ ; }
return cloned;
}
public String getResult_cd( )
{
return gxTv_SdtB707_SD02_REG_MEMO_RTN_Result_cd ;
}
public void setResult_cd( String value )
{
gxTv_SdtB707_SD02_REG_MEMO_RTN_Result_cd = value ;
}
public String getErr_msg( )
{
return gxTv_SdtB707_SD02_REG_MEMO_RTN_Err_msg ;
}
public void setErr_msg( String value )
{
gxTv_SdtB707_SD02_REG_MEMO_RTN_Err_msg = value ;
}
public short getMemo_no( )
{
return gxTv_SdtB707_SD02_REG_MEMO_RTN_Memo_no ;
}
public void setMemo_no( short value )
{
gxTv_SdtB707_SD02_REG_MEMO_RTN_Memo_no = value ;
}
protected short gxTv_SdtB707_SD02_REG_MEMO_RTN_Memo_no ;
protected String gxTv_SdtB707_SD02_REG_MEMO_RTN_Result_cd ;
protected String gxTv_SdtB707_SD02_REG_MEMO_RTN_Err_msg ;
}
|
package com.nadeem.app.kata.piece;
import com.nadeem.app.kata.Piece;
import com.nadeem.app.kata.Color;
import com.nadeem.app.kata.Position;
/**
* @author Nadeem Mohammad
*
*/
public class King extends Piece {
public King(int id, Color color) {
super(id, color);
}
@Override
public String getName() {
return "King";
}
@Override
public boolean validate(Position destination) {
return true;
}
}
|
package ch.rasc.ky;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Value {
private final String value;
@JsonCreator
public Value(@JsonProperty("value") String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
|
package com.fmi.se.dm.hw4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author Dimitar
*/
public class Tour implements Comparable<Tour> {
private List<City> tour;
private double distance;
public Tour() {
tour = new ArrayList<>();
}
public Tour(int size) {
tour = new ArrayList<>(Collections.nCopies(size, null));
}
public Tour(List<City> tour) {
setTour(tour);
}
public int getSize() {
return tour.size();
}
public City getCity(int index) {
return tour.get(index);
}
public void setCity(int index, City city) {
tour.set(index, city);
}
public boolean containsCity(City city) {
return tour.contains(city);
}
public List<City> getTour() {
return new ArrayList<>(tour);
}
public void setTour(List<City> tour) {
this.tour = new ArrayList<>(tour);
calculateDistance();
}
public double getDistance(){
return this.distance;
}
public double calculateDistance() {
double distance = 0;
for (int i = 0; i < this.tour.size() - 1; i++) {
distance += this.tour.get(i).distanceTo(this.tour.get(i + 1));
}
if (this.tour.size() > 1) {
distance += this.tour.get(this.tour.size() - 1).distanceTo(this.tour.get(0));
}
this.distance = distance;
return distance;
}
@Override
public int compareTo(Tour o) {
double result = this.distance - o.distance;
if (result == 0) {
return 0;
}
return result < 0 ? -1 : 1;
}
@Override
public String toString() {
return this.tour.toString();
}
}
|
package com.tencent.liteav.demo.videoediter;
import android.graphics.Bitmap;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.ugc.TXVideoEditConstants;
import com.tencent.ugc.TXVideoEditer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vinsonswang on 2017/10/26.
* <p>
* 由于SDK提供的TXVideoEditer为非单例模式
* 当您需要在多个Activity\Fragment 之间对同一个Video进行编辑的时候,可以在上层将其包装为一个单例
* <p>
* 需要注意:
* 完成一次视频编辑后,请务必调用{@link TCVideoEditerWrapper#clear()}晴空相关的一些配置
*/
public class TCVideoEditerWrapper {
private static final String TAG = "TCVideoEditerWrapper";
private static TCVideoEditerWrapper INSTANCE;
private TXVideoEditer mTXVideoEditer;
private TXVideoEditConstants.TXVideoInfo mTXVideoInfo;
public static final int mThumbnailCount = 10;//快速导入,默认显示10张缩略图
/**
* 缩略图相关
*/
private List<ThumbnailBitmapInfo> mThumbnailList; // 将已经加在好的Bitmap缓存起来
/**
* 预览相关
* <p>
* 由于SDK没有提供多个Listener的预览进度的回调,所以在上层包装一下
*/
private List<TXVideoPreviewListenerWrapper> mPreviewWrapperList;
private boolean mIsReverse;
private long mCutterDuration; // 裁剪的总时长
private long mCutterStartTime; // 裁剪开始的时间
private long mCutterEndTime; // 裁剪结束的时间
public static TCVideoEditerWrapper getInstance() {
if (INSTANCE == null) {
synchronized (TCVideoEditerWrapper.class) {
if (INSTANCE == null) {
INSTANCE = new TCVideoEditerWrapper();
}
}
}
return INSTANCE;
}
private TCVideoEditerWrapper() {
mThumbnailList = new ArrayList<>();
mPreviewWrapperList = new ArrayList<>();
mIsReverse = false;
}
public void setTXVideoInfo(TXVideoEditConstants.TXVideoInfo info) {
mTXVideoInfo = info;
}
/**
* 获取视频的信息
*
* @return
*/
public TXVideoEditConstants.TXVideoInfo getTXVideoInfo() {
return mTXVideoInfo;
}
public void setEditer(TXVideoEditer editer) {
mTXVideoEditer = editer;
if (mTXVideoEditer != null) {
mTXVideoEditer.setTXVideoPreviewListener(mPreviewListener);
}
}
public TXVideoEditer getEditer() {
return mTXVideoEditer;
}
public void clear() {
if (mTXVideoEditer != null) {
mTXVideoEditer.setTXVideoPreviewListener(null);
mTXVideoEditer = null;
}
mCutterDuration = 0;
mCutterStartTime = 0;
mCutterEndTime = 0;
mThumbnailList.clear();
synchronized (mPreviewWrapperList) {
mPreviewWrapperList.clear();
}
mIsReverse = false;
if (mTXVideoInfo != null) {
if (mTXVideoInfo.coverImage != null && !mTXVideoInfo.coverImage.isRecycled()) {
mTXVideoInfo.coverImage.recycle();
mTXVideoInfo.coverImage = null;
}
}
}
/**
* 裁剪后的时间
*
* @param newVideoDuration
*/
public void setCutterDuration(long newVideoDuration) {
mCutterDuration = newVideoDuration;
}
/**
* 获取裁剪后的时间
*
* @return
*/
public long geCutterDuration() {
return mCutterDuration;
}
public void setCutterStartTime(long startTime, long endTime) {
mCutterStartTime = startTime;
mCutterEndTime = endTime;
mCutterDuration = endTime - startTime;
}
public long getCutterStartTime() {
return mCutterStartTime;
}
public long getCutterEndTime() {
return mCutterEndTime;
}
/**
* ======================================================预览相关======================================================
*/
public void setReverse(boolean isReverse) {
mIsReverse = isReverse;
}
public boolean isReverse() {
return mIsReverse;
}
private TXVideoEditer.TXVideoPreviewListener mPreviewListener = new TXVideoEditer.TXVideoPreviewListener() {
@Override
public void onPreviewProgress(int time) {
int currentTimeMs = (int) (time / 1000);//转为ms值
synchronized (mPreviewWrapperList) {
for (TXVideoPreviewListenerWrapper wrapper : mPreviewWrapperList) {
wrapper.onPreviewProgressWrapper(currentTimeMs);
}
}
}
@Override
public void onPreviewFinished() {
TXCLog.i(TAG, "mPreviewListener, onPreviewFinished");
synchronized (mPreviewWrapperList) {
for (TXVideoPreviewListenerWrapper wrapper : mPreviewWrapperList) {
wrapper.onPreviewFinishedWrapper();
}
}
}
};
public void addTXVideoPreviewListenerWrapper(TXVideoPreviewListenerWrapper listener) {
synchronized (mPreviewWrapperList) {
if (mPreviewWrapperList.contains(listener)) {
return;
}
mPreviewWrapperList.add(listener);
}
}
public void removeTXVideoPreviewListenerWrapper(TXVideoPreviewListenerWrapper listener) {
synchronized (mPreviewWrapperList) {
mPreviewWrapperList.remove(listener);
}
}
/**
* 由于SDK没有提供多个界面的预览进度的回调,所以在上层包装一下
*/
public interface TXVideoPreviewListenerWrapper {
/**
* @param time
*/
void onPreviewProgressWrapper(int time);
void onPreviewFinishedWrapper();
}
/**
* ======================================================缩略图相关======================================================
*/
/**
* 获取已经加载的缩略图
*
* @return
*/
public List<Bitmap> getThumbnailList(long startPts, long endPts) {
List<Bitmap> list = new ArrayList<>();
for (ThumbnailBitmapInfo info : mThumbnailList) {
if (info.ptsMs >= startPts && info.ptsMs <= endPts) {
list.add(info.bitmap);
}
}
return list;
}
public List<Bitmap> getAllThumbnails() {
return getThumbnailList(0, mTXVideoInfo != null ? mTXVideoInfo.duration : 0);
}
public void addThumbnailBitmap(long timeMs, Bitmap bitmap) {
mThumbnailList.add(new ThumbnailBitmapInfo(timeMs, bitmap));
}
public void cleaThumbnails() {
for (ThumbnailBitmapInfo info : mThumbnailList) {
if (info != null && info.bitmap != null && !info.bitmap.isRecycled()) {
info.bitmap.recycle();
info.bitmap = null;
}
}
mThumbnailList.clear();
}
private class ThumbnailBitmapInfo {
public long ptsMs;
public Bitmap bitmap;
public ThumbnailBitmapInfo(long ptsMs, Bitmap bitmap) {
this.ptsMs = ptsMs;
this.bitmap = bitmap;
}
}
}
|
package de.undercouch.citeproc.tool;
import de.undercouch.citeproc.CSL;
import de.undercouch.citeproc.CSLBuilder;
import de.undercouch.citeproc.ItemDataProvider;
import de.undercouch.citeproc.helper.tool.ToolUtils;
import de.undercouch.citeproc.output.Bibliography;
import de.undercouch.underline.InputReader;
import de.undercouch.underline.Option.ArgumentType;
import de.undercouch.underline.OptionDesc;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* CLI command that generates a bibliography
* @author Michel Kraemer
*/
public class BibliographyCommand extends CitationIdsCommand {
private String style = "ieee";
private String locale = "en-US";
private String format = "text";
/**
* Sets the citation style (default: ieee)
* @param style the style
*/
@OptionDesc(longName = "style", shortName = "s",
description = "citation STYLE name (default: ieee)",
argumentName = "STYLE", argumentType = ArgumentType.STRING,
priority = 10)
public void setStyle(String style) {
this.style = style;
}
/**
* Sets the output format (default: text)
* @param format the format
*/
@OptionDesc(longName = "format", shortName = "f",
description = "output format: text (default), html, asciidoc, fo, rtf",
argumentName = "FORMAT", argumentType = ArgumentType.STRING,
priority = 20)
public void setFormat(String format) {
this.format = format;
}
/**
* Sets the citation locale (default: en-US)
* @param locale the locale
*/
@OptionDesc(longName = "locale", shortName = "l",
description = "citation LOCALE (default: en-US)",
argumentName = "LOCALE", argumentType = ArgumentType.STRING,
priority = 30)
public void setLocale(String locale) {
this.locale = locale;
}
@Override
public String getUsageName() {
return "bibliography";
}
@Override
public String getUsageDescription() {
return "Generate a bibliography from an input file";
}
@Override
public boolean checkArguments() {
// check output format
if (!format.equals("text") && !format.equals("html") &&
!format.equals("asciidoc") && !format.equals("fo") &&
!format.equals("rtf")) {
error("invalid output format: " + format);
return false;
}
return super.checkArguments();
}
/**
* Checks if the given style exists and output possible alternatives if
* it does not
* @param style the style
* @return true if the style exists, false otherwise
* @throws IOException if the style could not be loaded
*/
private boolean checkStyle(String style) throws IOException {
if (CSL.supportsStyle(style)) {
// style is supported
return true;
}
// style is not supported. look for alternatives.
String message = "Could not find style in classpath: " + style;
Set<String> availableStyles = CSL.getSupportedStyles();
// output alternative
if (!availableStyles.isEmpty()) {
String dyms = ToolUtils.getDidYouMeanString(availableStyles, style);
if (dyms != null && !dyms.isEmpty()) {
message += "\n\n" + dyms;
}
}
error(message);
return false;
}
@Override
public int doRun(String[] remainingArgs, InputReader in, PrintWriter out)
throws IOException {
int ret = super.doRun(remainingArgs, in, out);
if (ret != 0) {
return ret;
}
// run conversion
return generateCSL(style, locale, format, getCitationIds(),
getProvider(), out);
}
/**
* Performs CSL conversion and generates a bibliography
* @param style the CSL style
* @param locale the CSL locale
* @param format the output format
* @param citationIds the citation ids given on the command line
* @param provider a provider containing all citation item data
* @param out the print stream to write the output to
* @return the exit code
* @throws IOException if the CSL processor could not be initialized
*/
private int generateCSL(String style, String locale, String format,
List<String> citationIds, ItemDataProvider provider,
PrintWriter out) throws IOException {
if (!checkStyle(style)) {
return 1;
}
// initialize citation processor
try {
CSL citeproc = new CSLBuilder()
.itemDataProvider(provider)
.style(style)
.lang(locale)
.build();
// set output format
citeproc.setOutputFormat(format);
// register citation items
Collection<String> cids = citationIds;
if (cids.isEmpty()) {
cids = provider.getIds();
}
citeproc.registerCitationItems(cids);
// generate bibliography
doGenerateCSL(citeproc, cids, out);
} catch (FileNotFoundException e) {
error(e.getMessage());
return 1;
}
return 0;
}
/**
* Performs CSL conversion and generates a bibliography
* @param citeproc the CSL processor
* @param citationIds the citation IDs for which the bibliography
* should be generated (the CSL processor should already be prepared)
* @param out the stream to write the result to
*/
protected void doGenerateCSL(CSL citeproc, Collection<String> citationIds,
PrintWriter out) {
Bibliography bibl = citeproc.makeBibliography();
out.println(bibl.makeString());
}
}
|
/**
* @FileName: InitMonitorSide.java
* @Package com.asura.framework.monitor.springinit
*
* @author zhangshaobin
* @created 2013-1-9 下午8:52:15
*
* Copyright 2011-2015 asura
*/
package com.asura.framework.monitor.springinit;
import com.asura.framework.monitor.annotation.MBeanAnnotationProcessor;
import com.asura.framework.monitor.zkclient.MonitorZkClient;
/**
* <p>监控方启动</p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhangshaobin
* @since 1.0
* @version 1.0
*/
public final class InitMonitorSide {
private InitMonitorSide() {
}
/**
*
* 初始化
*
* @author zhangshaobin
* @created 2013-1-9 下午8:50:03
*
*/
public void init() {
MonitorZkClient.getInstance();
MBeanAnnotationProcessor.getInstance();
}
}
|
package org.motechproject.security.model;
import org.motechproject.security.domain.MotechRole;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Transfer Motech role data between representations.
* <p/>
* Role data transfer object facilitates exchange of role data among services,
* repository, and client user interface.
*/
public class RoleDto {
private String roleName;
private String originalRoleName;
private List<String> permissionNames;
private boolean deletable;
public RoleDto() {
this(null, new ArrayList<String>(), false);
}
public RoleDto(MotechRole motechRole) {
this(motechRole.getRoleName(), motechRole.getPermissionNames(), motechRole.isDeletable());
}
public RoleDto(String roleName, List<String> permissionNames) {
this(roleName, permissionNames, false);
}
public RoleDto(String roleName, List<String> permissionNames, boolean deletable) {
this.roleName = roleName;
this.permissionNames = permissionNames;
this.originalRoleName = roleName;
this.deletable = deletable;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<String> getPermissionNames() {
return permissionNames;
}
public void setPermissionNames(List<String> permissionNames) {
this.permissionNames = permissionNames;
}
public String getOriginalRoleName() {
return originalRoleName;
}
public void setOriginalRoleName(String originalRoleName) {
this.originalRoleName = originalRoleName;
}
public boolean isDeletable() {
return deletable;
}
public void setDeletable(boolean deletable) {
this.deletable = deletable;
}
@Override
public int hashCode() {
return Objects.hash(roleName, originalRoleName, permissionNames);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final RoleDto other = (RoleDto) obj;
return Objects.equals(this.roleName, other.roleName)
&& Objects.equals(this.originalRoleName, other.originalRoleName)
&& Objects.equals(this.permissionNames, other.permissionNames);
}
@Override
public String toString() {
return String.format(
"RoleDto{roleName='%s', originalRoleName='%s', permissionNames=%s}",
roleName, originalRoleName, permissionNames
);
}
}
|
package com.konstantinlevin77.hrms.entities.concretes;
import javax.persistence.*;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name="jobseeker_cvs")
public class JobseekerCv {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@ManyToOne
@JoinColumn(name="jobseeker_id")
private Jobseeker jobseeker;
@Column(name="github_link")
private String githubLink;
@Column(name="linkedin_link")
private String linkedinLink;
@Column(name="cover_letter")
private String coverLetter;
@OneToMany(mappedBy="jobseekerCv", fetch = FetchType.LAZY)
private List<JobseekerSchool> jobseekerSchools;
@OneToMany(mappedBy="jobseekerCv", fetch = FetchType.LAZY)
private List<JobseekerLanguage> jobseekerLanguages;
@OneToMany(mappedBy="jobseekerCv", fetch = FetchType.LAZY)
private List<JobseekerExperience> jobseekerExperiences;
@OneToMany(mappedBy="jobseekerCv", fetch = FetchType.LAZY)
private List<JobseekerTechnology> jobseekerTechnologies;
}
|
package test.io;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class TestNIO {
public static void main(String[] args) throws IOException {
File file = new File("Nio.java");
file.createNewFile();
FileInputStream fis = new FileInputStream(
new File("D:\\Project\\DUYI_EDU\\JdbcPool\\src\\com\\jdbc\\sqlsession\\SqlSessionFactory.java")
);
FileChannel inChannel = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
FileOutputStream fos = new FileOutputStream(file);
FileChannel channel = fos.getChannel();
while (inChannel.read(buffer) != -1) {
// 读完数据 切换模式 从写模式切换为读模式的重要方法(本质上更改了索引位置)
buffer.flip();
channel.write(buffer);
// 写完数据切换为读模式
buffer.flip();
}
inChannel.close();
fis.close();
channel.close();
fos.close();
BufferedOutputStream bos = new BufferedOutputStream(fos);
}
}
|
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.core;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.JetTestInstanceFactory;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.test.HazelcastParallelClassRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import static com.hazelcast.jet.core.TestUtil.executeAndPeel;
@RunWith(HazelcastParallelClassRunner.class)
public class OperationTimeoutTest extends JetTestSupport {
private static final int TIMEOUT_MILLIS = 8000;
@Rule
public ExpectedException expectedException = ExpectedException.none();
private JetTestInstanceFactory factory;
private JetConfig config;
@Before
public void setup() {
config = new JetConfig();
config.getHazelcastConfig().getProperties().put(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(),
Integer.toString(TIMEOUT_MILLIS));
factory = new JetTestInstanceFactory();
}
@After
public void tearDown() {
factory.terminateAll();
}
@Test
public void when_slowRunningOperationOnSingleNode_then_doesNotTimeout() throws Throwable {
// Given
JetInstance instance = factory.newMember(config);
DAG dag = new DAG();
dag.newVertex("slow", SlowProcessor::new);
// When
executeAndPeel(instance.newJob(dag));
}
@Test
public void when_slowRunningOperationOnMultipleNodes_doesNotTimeout() throws Throwable {
// Given
JetInstance instance = factory.newMember(config);
factory.newMember(config);
DAG dag = new DAG();
dag.newVertex("slow", SlowProcessor::new);
// When
executeAndPeel(instance.newJob(dag));
}
private static class SlowProcessor extends AbstractProcessor {
@Override
public boolean complete() {
sleepMillis(2 * TIMEOUT_MILLIS);
return true;
}
}
}
|
/*
* Copyright IBM Corp. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.example;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.LocalDateTime;
import io.grpc.Channel;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import org.hyperledger.fabric.client.Contract;
import org.hyperledger.fabric.client.Gateway;
import org.hyperledger.fabric.client.Network;
import org.hyperledger.fabric.client.identity.*;
public class Sample
{
private static final String mspID = "Org1MSP";
private static final Path cryptoPath = Paths.get("..","..", "scenario", "fixtures", "crypto-material", "crypto-config", "peerOrganizations", "org1.example.com");
private static final Path certPath = cryptoPath.resolve(Paths.get("users", "User1@org1.example.com", "msp", "signcerts", "User1@org1.example.com-cert.pem"));
private static final Path keyPath = cryptoPath.resolve(Paths.get("users", "User1@org1.example.com", "msp", "keystore", "key.pem"));
private static final Path tlsCertPath = cryptoPath.resolve(Paths.get("peers", "peer0.org1.example.com", "tls", "ca.crt"));
public static void main( String[] args ) throws Exception
{
// make a gRPC connection to the gateway peer
X509Certificate tlsCert = Identities.readX509Certificate(new FileReader(tlsCertPath.toFile()));
Channel channel = NettyChannelBuilder.forTarget("localhost:7051")
.sslContext(GrpcSslContexts.forClient().trustManager(tlsCert).build())
.overrideAuthority("peer0.org1.example.com")
.build();
X509Certificate certificate = Identities.readX509Certificate(new FileReader(certPath.toFile()));
PrivateKey privateKey = Identities.readPrivateKey(new FileReader(keyPath.toFile()));
Identity identity = new X509Identity(mspID, certificate);
Signer signer = Signers.newPrivateKeySigner(privateKey);
try (Gateway gateway = Gateway.newInstance()
.identity(identity)
.signer(signer)
.connection(channel)
.connect()) {
Network network = gateway.getNetwork("mychannel");
Contract contract = network.getContract("basic");
String time = LocalDateTime.now().toString();
System.out.println("Submitting transaction to basic chaincode with value " + time + "...");
byte[] result = contract.submitTransaction("put", "time", time);
System.out.println("Submit result = " + new String(result));
System.out.println("Evaluating query...");
result = contract.evaluateTransaction("get", "time");
System.out.println("Query result = " + new String(result));
}
}
}
|
/*
* Copyright (c) Sematext International
* All Rights Reserved
*
* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Sematext International
* The copyright notice above does not evidence any
* actual or intended publication of such source code.
*/
package org.apache.solr.handler.component;
import static org.apache.solr.common.params.CommonParams.PATH;
import org.apache.lucene.util.Version;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.ShardParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.search.SolrQueryTimeoutImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sematext.solr.handler.component.ReSearcherRequestContext;
import com.sematext.solr.handler.component.ReSearcherUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class ReSearcherHandler {
private static final Logger LOG = LoggerFactory.getLogger(SolrCore.class);
public long handleSuggestionHitsRequest(ReSearcherRequestContext ctx, String query, Set<String> componentNames) throws Exception {
ModifiableSolrParams params = new ModifiableSolrParams(ctx.getParams());
params.set(CommonParams.ROWS, "0");
for(String componentName : componentNames) {
params.set(componentName, "false");
}
params.set(CommonParams.Q, query);
SolrQueryRequest req = new SolrQueryRequestBase(ctx.getCore(), params) {};
SolrQueryResponse rsp = new SolrQueryResponse();
ResponseBuilder rb = new ResponseBuilder(req, rsp, ctx.getQueryOnlyComponents());
try {
handleSuggestionRequest(ctx, rb, ctx.getQueryOnlyComponents(), true);
} finally {
req.close();
}
return ReSearcherUtils.extractOriginalQueryHits(rb);
}
public SolrQueryResponse handleSuggestionResponseRequest(ReSearcherRequestContext ctx, String query, String componentName, ResponseBuilder originalRb) throws Exception {
ModifiableSolrParams newParams = new ModifiableSolrParams(originalRb.req.getParams());
newParams.set(CommonParams.Q, query);
newParams.set(componentName, "false");
SolrQueryRequest req = new SolrQueryRequestBase(ctx.getCore(), newParams) {};
SolrQueryResponse rsp = new SolrQueryResponse();
ResponseBuilder rb = new ResponseBuilder(req, rsp, originalRb.components);
try {
handleSuggestionRequest(ctx, rb, originalRb.components, false);
} finally {
req.close();
}
return rsp;
}
public SolrQueryResponse handleSuggestionResponseRequest(ReSearcherRequestContext ctx, ModifiableSolrParams params, String componentName, ResponseBuilder rb) throws Exception {
params.set(componentName, "false");
rb.req.setParams(params);
handleSuggestionRequest(ctx, rb, ctx.getQueryOnlyComponents(), false);
return rb.rsp;
}
public SolrQueryResponse handleSuggestionResponseRequest(ReSearcherRequestContext ctx, ModifiableSolrParams params, String componentName, List<SearchComponent> components) throws Exception {
params.set(componentName, "false");
SolrQueryRequest req = new SolrQueryRequestBase(ctx.getCore(), params) {};
SolrQueryResponse rsp = new SolrQueryResponse();
ResponseBuilder rb = new ResponseBuilder(req, rsp, components);
try {
handleSuggestionRequest(ctx, rb, components, false);
} finally {
req.close();
}
return rsp;
}
private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb, ShardHandlerFactory shardHandlerFactory) {
ShardHandler shardHandler = null;
boolean isZkAware = false;
CoreContainer cc = null;
if (req.getCore() != null) {
cc = req.getCore().getCoreContainer();
isZkAware = cc.isZooKeeperAware();
}
rb.isDistrib = req.getParams().getBool("distrib", isZkAware);
if (!rb.isDistrib) {
// for back compat, a shards param with URLs like localhost:8983/solr will mean that this
// search is distributed.
final String shards = req.getParams().get(ShardParams.SHARDS);
rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0));
}
if (rb.isDistrib) {
shardHandler = shardHandlerFactory.getShardHandler();
shardHandler.prepDistributed(rb);
if (!rb.isDistrib) {
shardHandler = null; // request is not distributed after all and so the shard handler is not needed
}
}
if(isZkAware) {
ZkController zkController = cc.getZkController();
NamedList<Object> headers = rb.rsp.getResponseHeader();
if(headers != null) {
headers.add("zkConnected",
zkController != null
? !zkController.getZkClient().getConnectionManager().isLikelyExpired()
: false);
}
}
return shardHandler;
}
@SuppressWarnings({ "deprecation", "unchecked" })
private void handleSuggestionRequest(ReSearcherRequestContext ctx, ResponseBuilder rb, List<SearchComponent> components, boolean ignoreOutput) throws Exception {
ShardHandler shardHandler1 = null;
try {
shardHandler1 = getAndPrepShardHandler(rb.req, rb, ctx.getShardHandlerFactory());
} catch (Throwable e) {
e.printStackTrace();
Field field = ResponseBuilder.class.getDeclaredField("isDistrib");
LOG.error("isDistrib = " + Modifier.toString(field.getModifiers()));
LOG.error("Current Lucene version " + Version.LATEST.toString());
}
if (components != null) {
for (SearchComponent c : components) {
c.prepare(rb);
}
}
if (!rb.isDistrib) {
long timeAllowed = rb.req.getParams().getLong(CommonParams.TIME_ALLOWED, -1L);
if (timeAllowed > 0L) {
SolrQueryTimeoutImpl.set(timeAllowed);
}
try {
if (components != null) {
for (SearchComponent c : components) {
c.process(rb);
}
}
} finally {
SolrQueryTimeoutImpl.reset();
}
} else {
if (rb.outgoing == null) {
rb.outgoing = new LinkedList<ShardRequest>();
}
rb.finished = new ArrayList<ShardRequest>();
int nextStage = 0;
do {
rb.stage = nextStage;
nextStage = ResponseBuilder.STAGE_DONE;
// the next stage is the minimum of what all components report
if (components != null) {
for (SearchComponent c : components) {
nextStage = Math.min(nextStage, c.distributedProcess(rb));
}
}
// check the outgoing queue and send requests
while (rb.outgoing.size() > 0) {
// submit all current request tasks at once
while (rb.outgoing.size() > 0) {
ShardRequest sreq = rb.outgoing.remove(0);
sreq.actualShards = sreq.shards;
if (sreq.actualShards == ShardRequest.ALL_SHARDS) {
sreq.actualShards = rb.shards;
}
sreq.responses = new ArrayList<ShardResponse>(sreq.actualShards.length);
for (String shard : sreq.actualShards) {
ModifiableSolrParams params = new ModifiableSolrParams(sreq.params);
params.remove(ShardParams.SHARDS); // not a top-level request
params.set(CommonParams.DISTRIB, "false"); // not a top-level request
params.remove("indent");
params.remove(CommonParams.HEADER_ECHO_PARAMS);
params.set(ShardParams.IS_SHARD, true); // a sub (shard) request
params.set(ShardParams.SHARDS_PURPOSE, sreq.purpose);
params.set(ShardParams.SHARD_URL, shard); // so the shard knows what was asked
String shardQt = params.get(ShardParams.SHARDS_QT);
if (shardQt == null) {
// for distributed queries that don't include shards.qt, use the original path
// as the default but operators need to update their luceneMatchVersion to enable
// this behavior since it did not work this way prior to 5.1
if (rb.req.getCore().getSolrConfig().luceneMatchVersion.onOrAfter(Version.LUCENE_6_0_0)) {
String reqPath = (String) rb.req.getContext().get(PATH);
if (!"/select".equals(reqPath)) {
params.set(CommonParams.QT, reqPath);
} // else if path is /select, then the qt gets passed through if set
} else {
// this is the pre-5.1 behavior, which translates to sending the shard request to /select
params.remove(CommonParams.QT);
}
} else {
params.set(CommonParams.QT, shardQt);
}
shardHandler1.submit(sreq, shard, params);
}
}
// now wait for replies, but if anyone puts more requests on
// the outgoing queue, send them out immediately (by exiting
// this loop)
boolean tolerant = rb.req.getParams().getBool(ShardParams.SHARDS_TOLERANT, false);
while (rb.outgoing.size() == 0) {
ShardResponse srsp = tolerant ? shardHandler1.takeCompletedIncludingErrors() : shardHandler1
.takeCompletedOrError();
if (srsp == null)
break; // no more requests to wait for
// Was there an exception?
if (srsp.getException() != null) {
// If things are not tolerant, abort everything and rethrow
if (!tolerant) {
shardHandler1.cancelAll();
if (srsp.getException() instanceof SolrException) {
throw (SolrException) srsp.getException();
} else {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, srsp.getException());
}
} else {
if(rb.rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY) == null) {
rb.rsp.getResponseHeader().add(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY, Boolean.TRUE);
}
}
}
rb.finished.add(srsp.getShardRequest());
// let the components see the responses to the request
if (components != null) {
for (SearchComponent c : components) {
c.handleResponses(rb, srsp.getShardRequest());
}
}
}
}
if (components != null) {
for (SearchComponent c : components) {
c.finishStage(rb);
}
}
// we are done when the next stage is MAX_VALUE
} while (nextStage != Integer.MAX_VALUE);
}
// SOLR-5550: still provide shards.info if requested even for a short circuited distrib request
if(!rb.isDistrib && rb.req.getParams().getBool(ShardParams.SHARDS_INFO, false) && rb.shortCircuitedURL != null) {
NamedList<Object> shardInfo = new SimpleOrderedMap<Object>();
SimpleOrderedMap<Object> nl = new SimpleOrderedMap<Object>();
if (rb.rsp.getException() != null) {
Throwable cause = rb.rsp.getException();
if (cause instanceof SolrServerException) {
cause = ((SolrServerException)cause).getRootCause();
} else {
if (cause.getCause() != null) {
cause = cause.getCause();
}
}
nl.add("error", cause.toString() );
StringWriter trace = new StringWriter();
cause.printStackTrace(new PrintWriter(trace));
nl.add("trace", trace.toString() );
}
else {
nl.add("numFound", rb.getResults().docList.matches());
nl.add("maxScore", rb.getResults().docList.maxScore());
}
nl.add("shardAddress", rb.shortCircuitedURL);
nl.add("time", rb.req.getRequestTimer().getTime()); // elapsed time of this request so far
int pos = rb.shortCircuitedURL.indexOf("://");
String shardInfoName = pos != -1 ? rb.shortCircuitedURL.substring(pos+3) : rb.shortCircuitedURL;
shardInfo.add(shardInfoName, nl);
rb.rsp.getValues().add(ShardParams.SHARDS_INFO,shardInfo);
}
}
}
|
package com.arrow.pegasus.data.event;
public enum EventType {
Normal, Encrypted
}
|
package org.nutz.qq.bean.graph.resp;
/**
* Created by Jianghao on 2020/4/14
*
* @author Freshplay Inc.
*/
public class GetUserInfoResp {
private Integer ret;
public Integer getRet() {
return ret;
}
public void setRet(Integer ret) {
this.ret = ret;
}
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
private Integer is_lost;
public Integer getIs_lost() {
return is_lost;
}
public void setIs_lost(Integer is_lost) {
this.is_lost = is_lost;
}
private String nickname;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
private String gender;
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
private int gender_type;
public int getGender_type() {
return gender_type;
}
public void setGender_type(int gender_type) {
this.gender_type = gender_type;
}
private String province;
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
private String year;
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
private String constellation;
public String getConstellation() {
return constellation;
}
public void setConstellation(String constellation) {
this.constellation = constellation;
}
private String figureurl;
public String getFigureurl() {
return figureurl;
}
public void setFigureurl(String figureurl) {
this.figureurl = figureurl;
}
private String figureurl_1;
public String getFigureurl_1() {
return figureurl_1;
}
public void setFigureurl_1(String figureurl_1) {
this.figureurl_1 = figureurl_1;
}
private String figureurl_2;
public String getFigureurl_2() {
return figureurl_2;
}
public void setFigureurl_2(String figureurl_2) {
this.figureurl_2 = figureurl_2;
}
private String figureurl_qq_1;
public String getFigureurl_qq_1() {
return figureurl_qq_1;
}
public void setFigureurl_qq_1(String figureurl_qq_1) {
this.figureurl_qq_1 = figureurl_qq_1;
}
private String figureurl_qq_2;
public String getFigureurl_qq_2() {
return figureurl_qq_2;
}
public void setFigureurl_qq_2(String figureurl_qq_2) {
this.figureurl_qq_2 = figureurl_qq_2;
}
private String figureurl_qq;
public String getFigureurl_qq() {
return figureurl_qq;
}
public void setFigureurl_qq(String figureurl_qq) {
this.figureurl_qq = figureurl_qq;
}
private String figureurl_type;
public String getFigureurl_type() {
return figureurl_type;
}
public void setFigureurl_type(String figureurl_type) {
this.figureurl_type = figureurl_type;
}
private String is_yellow_vip;
public String getIs_yellow_vip() {
return is_yellow_vip;
}
public void setIs_yellow_vip(String is_yellow_vip) {
this.is_yellow_vip = is_yellow_vip;
}
private String vip;
public String getVip() {
return vip;
}
public void setVip(String vip) {
this.vip = vip;
}
private String yellow_vip_level;
public String getYellow_vip_level() {
return yellow_vip_level;
}
public void setYellow_vip_level(String yellow_vip_level) {
this.yellow_vip_level = yellow_vip_level;
}
private String level;
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
private String is_yellow_year_vip;
public String getIs_yellow_year_vip() {
return is_yellow_year_vip;
}
public void setIs_yellow_year_vip(String is_yellow_year_vip) {
this.is_yellow_year_vip = is_yellow_year_vip;
}
}
|
package ru.job4j.chess;
import org.junit.Test;
import ru.job4j.chess.firuges.Cell;
import ru.job4j.chess.firuges.black.BishopBlack;
import ru.job4j.chess.firuges.black.PawnBlack;
import static org.junit.Assert.*;
public class LogicTest {
@Test
public void moveFigureWhenWayNotEmpty() {
Logic logic = new Logic();
logic.add(new BishopBlack(Cell.C1));
logic.add(new PawnBlack(Cell.B2));
boolean result = logic.move(Cell.C1, Cell.B2);
assertFalse(result);
}
@Test
public void moveFigureWhenWayFree() {
Logic logic = new Logic();
logic.add(new BishopBlack(Cell.C1));
boolean result = logic.move(Cell.C1, Cell.D2);
assertTrue(result);
}
}
|
package ghost.framework.web.module.event.servlet.context;
import ghost.framework.web.module.event.servlet.WebServletEventTargetHandle;
import javax.servlet.ServletContextEvent;
/**
* package: ghost.framework.web.module.event.servlet.context
*
* @Author: 郭树灿{gsc-e590}
* @link: 手机:13715848993, QQ 27048384
* @Description:
* @Date: 2020/1/27:20:05
*/
public class WebServletContextEventTargetHandle<O, T extends ServletContextEvent> extends WebServletEventTargetHandle<O, T> implements IWebServletContextEventTargetHandle<O, T>{
/**
* 初始化事件不表处理头
*
* @param owner 设置事件目标对象拥有者
* @param target 设置目标对象
*/
public WebServletContextEventTargetHandle(O owner, T target) {
super(owner, target);
}
}
|
/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zuluindia.watchpresenter.tutorial;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
import com.zuluindia.watchpresenter.R;
import org.codepond.wizardroid.WizardStep;
/**
* Created by pablogil on 5/24/15.
*/
public class TutorialStep2 extends WizardStep {
public TutorialStep2() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tutorial_layout, container, false);
WebView wv = (WebView) v.findViewById(R.id.mainWebView);
wv.loadUrl("file:///android_asset/tutorial/tutorial2.html");
return v;
}
@Override
public void onExit(int exitCode) {
super.onExit(exitCode);
}
}
|
/*
* Copyright 2013-2018 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 com.amazonaws.services.apigateway.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Get an <a>SdkType</a> instance.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetSdkTypeRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The identifier of the queried <a>SdkType</a> instance.
* </p>
*/
private String id;
/**
* <p>
* The identifier of the queried <a>SdkType</a> instance.
* </p>
*
* @param id
* The identifier of the queried <a>SdkType</a> instance.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The identifier of the queried <a>SdkType</a> instance.
* </p>
*
* @return The identifier of the queried <a>SdkType</a> instance.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The identifier of the queried <a>SdkType</a> instance.
* </p>
*
* @param id
* The identifier of the queried <a>SdkType</a> instance.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetSdkTypeRequest withId(String id) {
setId(id);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: ").append(getId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetSdkTypeRequest == false)
return false;
GetSdkTypeRequest other = (GetSdkTypeRequest) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
return hashCode;
}
@Override
public GetSdkTypeRequest clone() {
return (GetSdkTypeRequest) super.clone();
}
}
|
/*
* 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.camel.component.file;
import java.io.File;
import java.lang.invoke.MethodHandles;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* This class tests an issue where an input file is not picked up due to a
* dynamic doneFileName using the simple syntax and containing two dots.
*/
public class FileConsumeSimpleDynamicDoneFileNameWithTwoDotsTest extends ContextTestSupport {
private static final String TARGET_DIR_NAME = "target/data/" + MethodHandles.lookup().lookupClass().getSimpleName();
@Override
@BeforeEach
public void setUp() throws Exception {
deleteDirectory(TARGET_DIR_NAME);
super.setUp();
}
@Test
public void testSimpleDynamicDoneFileNameContainingTwoDots() throws Exception {
NotifyBuilder notify = new NotifyBuilder(context).whenDone(1).create();
getMockEndpoint("mock:result").expectedBodiesReceivedInAnyOrder("input-body");
template.sendBodyAndHeader("file:" + TARGET_DIR_NAME, "input-body", Exchange.FILE_NAME, "test.twodot.txt");
template.sendBodyAndHeader("file:" + TARGET_DIR_NAME, "done-body", Exchange.FILE_NAME, "test.twodot.done");
assertMockEndpointsSatisfied();
assertTrue(notify.matchesMockWaitTime());
assertFalse(new File(TARGET_DIR_NAME, "test.twodot.txt").exists(), "Input file should be deleted");
assertFalse(new File(TARGET_DIR_NAME, "test.twodot.done").exists(), "Done file should be deleted");
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("file:" + TARGET_DIR_NAME + "?doneFileName=$simple{file:name.noext}.done&initialDelay=0").to("mock:result");
}
};
}
}
|
package top.one.jiemo.service;
import top.one.jiemo.model.Favorite;
import top.one.jiemo.model.VideoEntity;
import java.io.IOException;
import java.util.List;
public interface VideoUpload {
List<VideoEntity> findylVideos();//主页展示视频:yl,yx,dh*8
List<VideoEntity> findyxVideos();
List<VideoEntity> finddhVideos();
List<VideoEntity> findRSideVideos();
List<VideoEntity> findRank1();
List<VideoEntity> findRank2();
List<VideoEntity> findRank3();
void addVideo(VideoEntity video);
VideoEntity findVideoM3u8(String url);
void paVideo() throws IOException;
long getCreateTime();
int updateCreateTime(long ctime);
List<String> getAllUrl();
int updateFieldM3u8(String m3u8, String url);//更新m3u8
int getVideoCount();
void delErrorVideo();
List<VideoEntity> serachVideo(String key);
int addVideoFavorite(String username, String videourl,String title,String img,String click);//添加收藏
int delVideoFavorite(String username, String videourl);//删除收藏
List<Favorite> findVideoFavorite(String username);//查询收藏
}
|
package com.mutool.javafx.core.util;
/**
* @ClassName: AttributeConvertUtil
* @Description: 类属性转换工具类
* @author: xufeng
* @date: 2017年7月11日 下午1:20:05
*/
public class AttributeConvertUtil {
public static String getAttributeNameByXml(String str) {
StringBuilder stringBuilder = new StringBuilder();
String[] strings = str.split("_");
for (int i = 0; i < strings.length; i++) {
if (i == 0) {
stringBuilder.append(Character.toLowerCase(strings[i].charAt(0)));
} else {
stringBuilder.append(Character.toUpperCase(strings[i].charAt(0)));
}
stringBuilder.append(strings[i].substring(1));
}
return stringBuilder.toString();
}
public static String getAttributeSetNameByXml(String str) {
StringBuilder stringBuilder = new StringBuilder();
String[] strings = str.split("_");
for (int i = 0; i < strings.length; i++) {
stringBuilder.append(Character.toUpperCase(strings[i].charAt(0)));
stringBuilder.append(strings[i].substring(1));
}
return stringBuilder.toString();
}
/**
* @Title: humpToLine
* @Description: 驼峰转下横线写法互转
*/
public static String humpToLine(String param) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
sb.append(param.charAt(0));
for (int i = 1; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c) && Character.isLowerCase(param.charAt(i-1))) {
sb.append("_");
}
sb.append(c);
}
return sb.toString().toUpperCase();
}
}
|
package com.hdq.gulimall.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 属性&属性分组关联
*
* @author huangdaoquan
* @email 1758398270@qq.com
* @date 2022-01-23 23:36:29
*/
@Data
@TableName("pms_attr_attrgroup_relation")
public class AttrAttrgroupRelationEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 属性id
*/
private Long attrId;
/**
* 属性分组id
*/
private Long attrGroupId;
/**
* 属性组内排序
*/
private Integer attrSort;
}
|
package org.primftpd.filesystem;
import android.content.ContentResolver;
import androidx.documentfile.provider.DocumentFile;
import org.apache.sshd.common.Session;
import org.apache.sshd.common.file.SshFile;
import org.primftpd.services.PftpdService;
import java.util.List;
public class SafSshFile extends SafFile<SshFile> implements SshFile {
private final Session session;
private final SafSshFileSystemView fileSystemView;
public SafSshFile(
ContentResolver contentResolver,
DocumentFile parentDocumentFile,
DocumentFile documentFile,
String absPath,
PftpdService pftpdService,
Session session,
SafSshFileSystemView fileSystemView) {
super(contentResolver, parentDocumentFile, documentFile, absPath, pftpdService);
this.session = session;
this.fileSystemView = fileSystemView;
}
public SafSshFile(
ContentResolver contentResolver,
DocumentFile parentDocumentFile,
String name,
String absPath,
PftpdService pftpdService,
Session session,
SafSshFileSystemView fileSystemView) {
super(contentResolver, parentDocumentFile, name, absPath, pftpdService);
this.session = session;
this.fileSystemView = fileSystemView;
}
@Override
protected SshFile createFile(
ContentResolver contentResolver,
DocumentFile parentDocumentFile,
DocumentFile documentFile,
String absPath,
PftpdService pftpdService) {
return new SafSshFile(contentResolver, parentDocumentFile, documentFile, absPath, pftpdService, session, fileSystemView);
}
@Override
public String getClientIp() {
return SshUtils.getClientIp(session);
}
@Override
public boolean move(SshFile target) {
logger.trace("move()");
return super.move((SafFile)target);
}
@Override
public String getOwner() {
logger.trace("[{}] getOwner()", name);
return session.getUsername();
}
@Override
public SshFile getParentFile() {
logger.trace("[{}] getParentFile()", name);
String parentPath = Utils.parent(absPath);
if (parentPath.length() == 0) {
// in SAF we don't keep track of home dir
parentPath = "/";
}
logger.trace("[{}] getParentFile() -> {}", name, parentPath);
return fileSystemView.getFile(parentPath);
}
@Override
public List<SshFile> listSshFiles() {
return listFiles();
}
}
|
package com.navercorp.study1.code04;
import static org.junit.Assert.assertEquals;
import java.sql.SQLException;
import org.junit.Test;
import com.navercorp.study1.code04.dao.UserDao;
import com.navercorp.study1.domain.User;
public class Code04Test {
@Test
public void test() throws ClassNotFoundException, SQLException {
/**
* 관심사에 해당하는 구현체가 내부에서 생성된다.
* 내부에서는 구현클래스 생성과 데이터 엑세스 작업에 대한 책임을 모두 가진다.
*
* (Composition 관계이므로 다형성 구현이 불가능)
*/
UserDao dao = new UserDao();
// 조회
User user = dao.get("1");
System.out.println(user.getName());
assertEquals("홍길동", user.getName());
}
}
|
/*
* Tencent is pleased to support the open source community by making Tinker available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 tinker.sample.android.app;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.tencent.tinker.lib.tinker.Tinker;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.shareutil.ShareConstants;
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals;
import tinker.sample.android.R;
import tinker.sample.android.util.Utils;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Tinker.MainActivity";
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "i am on onCreate classloader:" + MainActivity.class.getClassLoader().toString());
//test resource change
Log.e(TAG, "i am on onCreate string:" + getResources().getString(R.string.test_resource));
// Log.e(TAG, "i am on patch onCreate");
Button loadPatchButton = (Button) findViewById(R.id.loadPatch);
final TextView tvPatch = (TextView) findViewById(R.id.tv_patch);
Button patch_btn = (Button) findViewById(R.id.patch_btn);
patch_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvPatch.setText("The count is " + count++);
}
});
loadPatchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");
}
});
Button loadLibraryButton = (Button) findViewById(R.id.loadLibrary);
loadLibraryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//for lib/armeabi, just use TinkerInstaller.loadLibrary
TinkerInstaller.loadArmLibrary(getApplicationContext(), "stlport_shared");
// TinkerInstaller.loadLibraryFromTinker(getApplicationContext(), "assets/x86", "stlport_shared");
}
});
Button cleanPatchButton = (Button) findViewById(R.id.cleanPatch);
cleanPatchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Tinker.with(getApplicationContext()).cleanPatch();
}
});
Button killSelfButton = (Button) findViewById(R.id.killSelf);
killSelfButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ShareTinkerInternals.killAllOtherProcess(getApplicationContext());
android.os.Process.killProcess(android.os.Process.myPid());
}
});
Button buildInfoButton = (Button) findViewById(R.id.showInfo);
buildInfoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showInfo(MainActivity.this);
}
});
}
public boolean showInfo(Context context) {
// add more Build Info
final StringBuilder sb = new StringBuilder();
Tinker tinker = Tinker.with(getApplicationContext());
if (tinker.isTinkerLoaded()) {
sb.append(String.format("[patch is loaded] \n"));
sb.append(String.format("[buildConfig TINKER_ID] %s \n", BuildInfo.TINKER_ID));
sb.append(String.format("[buildConfig BASE_TINKER_ID] %s \n", BaseBuildInfo.BASE_TINKER_ID));
sb.append(String.format("[buildConfig MESSSAGE] %s \n", BuildInfo.MESSAGE));
sb.append(String.format("[TINKER_ID] %s \n", tinker.getTinkerLoadResultIfPresent().getPackageConfigByName(ShareConstants.TINKER_ID)));
sb.append(String.format("[packageConfig patchMessage] %s \n", tinker.getTinkerLoadResultIfPresent().getPackageConfigByName("patchMessage")));
sb.append(String.format("[TINKER_ID Rom Space] %d k \n", tinker.getTinkerRomSpace()));
} else {
sb.append(String.format("[patch is not loaded] \n"));
sb.append(String.format("[buildConfig TINKER_ID] %s \n", BuildInfo.TINKER_ID));
sb.append(String.format("[buildConfig BASE_TINKER_ID] %s \n", BaseBuildInfo.BASE_TINKER_ID));
sb.append(String.format("[buildConfig MESSSAGE] %s \n", BuildInfo.MESSAGE));
sb.append(String.format("[TINKER_ID] %s \n", ShareTinkerInternals.getManifestTinkerID(getApplicationContext())));
}
sb.append(String.format("[BaseBuildInfo Message] %s \n", BaseBuildInfo.TEST_MESSAGE));
final TextView v = new TextView(context);
v.setText(sb);
v.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
v.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
v.setTextColor(0xFF000000);
v.setTypeface(Typeface.MONOSPACE);
final int padding = 16;
v.setPadding(padding, padding, padding, padding);
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setView(v);
final AlertDialog alert = builder.create();
alert.show();
return true;
}
@Override
protected void onResume() {
Log.e(TAG, "i am on onResume");
// Log.e(TAG, "i am on patch onResume");
super.onResume();
Utils.setBackground(false);
}
@Override
protected void onPause() {
super.onPause();
Utils.setBackground(true);
}
}
|
package huoShan.AnZhuo.JiBen;
public class rg_YingYongChengXu extends android.app.Application {
protected java.util.HashMap<String, java.lang.Object> rg_QuanJuBianLiangBiao = new java.util.HashMap<String, java.lang.Object> ();
private static rg_YingYongChengXu ms_objApp;
protected rg_QuanJuShuJuCunChuQiLei rg_QuanJuShuJuCunChuQi = new rg_QuanJuShuJuCunChuQiLei ();
protected rg_UIDongZuoZhiHangQiLei rg_DongZuoZhiHangQi = new rg_UIDongZuoZhiHangQiLei ();
public void onCreate () {
super.onCreate ();
sPermitDiskAndNetworkOperInsideUIThread ();
ms_objApp = this;
rg_DongZuoZhiHangQi.init ();
rg_TongZhi_BeiChuangJian3 ();
}
public static void sPermitDiskAndNetworkOperInsideUIThread () {
android.os.StrictMode.setThreadPolicy (new android.os.StrictMode.ThreadPolicy.Builder ().permitAll ().build ());
}
public static void sRunOnUiThread (Runnable action) {
ms_objApp.rg_DongZuoZhiHangQi.RunOnUiThread (action);
}
public static rg_YingYongChengXu sGetApp () {
return ms_objApp;
}
public static rg_QuanJuShuJuCunChuQiLei sGetGlobalDataCache () {
return ms_objApp.rg_QuanJuShuJuCunChuQi;
}
public static boolean sIsUiThread () {
return ms_objApp.rg_DongZuoZhiHangQi.IsUiThread ();
}
private void CleanupGlobalData () {
rg_TongZhi_QingLiQuanJuShuJu ();
rg_QuanJuBianLiangBiao.clear ();
rg_QuanJuShuJuCunChuQi.Cleanup ();
}
private int m_nStartupState = 0;
private static int ms_nStartupState = 0;
public static void sOnStartupClassEnter () {
ms_objApp.m_nStartupState = ms_nStartupState = 1;
ms_objApp.CleanupGlobalData ();
}
public static boolean sCheckRestart (android.content.Context context) {
if (ms_objApp.m_nStartupState == 1 && ms_nStartupState == 1)
return true;
Class<?> clsStartup = com.qqq.WXhongbao.rg_QiDongLei.class;
if (android.app.Activity.class.isAssignableFrom (clsStartup)) {
try {
android.content.Intent intent = new android.content.Intent (context, clsStartup);
intent.addFlags (android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP |
android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK |
android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity (intent);
} catch (Exception e) { }
}
return false;
}
public static void sForceRestart () {
ms_objApp.m_nStartupState = ms_nStartupState = -1;
}
private static final String cs_strServiceStartUserData = "@service_start_user_data";
public static int sGetServiceStartUserData (android.content.Intent objIntent) {
return objIntent.getIntExtra (cs_strServiceStartUserData, 0);
}
public static final String cs_strServiceStartParams = "@service_start_params";
public static boolean sMyStartService (Class clsService, android.os.Bundle bundle, Object... params) {
rg_QuanJuShuJuCunChuQiLei objCache = sGetGlobalDataCache ();
int nParamDataIdentifier = 0;
try {
android.content.Intent objIntent = new android.content.Intent (ms_objApp, clsService);
if (bundle != null)
objIntent.putExtras (bundle);
if (params != null && params.length > 0) {
nParamDataIdentifier = objCache.Push (params);
objIntent.putExtra (cs_strServiceStartParams, nParamDataIdentifier);
}
if (ms_objApp.startService (objIntent) != null)
return true;
} catch (Exception e) { }
objCache.Remove (nParamDataIdentifier);
return false;
}
public static boolean sMyStopService (Class clsService) {
android.content.Intent objIntent = new android.content.Intent (ms_objApp, clsService);
try {
return ms_objApp.stopService (objIntent);
} catch (Exception e) {
return false;
}
}
public void rg_TongZhi_BeiChuangJian3 () {
}
public void rg_TongZhi_QingLiQuanJuShuJu () {
}
public static rg_YingYongChengXu rg_QuChengXu () {
return ms_objApp;
}
public static void rg_DiShiKuang (final String rg_YuXianShiDeWenBen, final boolean rg_ChangShiJianXianShi) {
if (rg_YingYongChengXu.sIsUiThread ()) {
try {
android.widget.Toast.makeText (ms_objApp, rg_YuXianShiDeWenBen,
(rg_ChangShiJianXianShi ? android.widget.Toast.LENGTH_LONG : android.widget.Toast.LENGTH_SHORT)).show ();
} catch (Exception e) { }
} else {
rg_YingYongChengXu.sRunOnUiThread (new Runnable () {
@Override public void run () {
try {
android.widget.Toast.makeText (ms_objApp, rg_YuXianShiDeWenBen,
(rg_ChangShiJianXianShi ? android.widget.Toast.LENGTH_LONG : android.widget.Toast.LENGTH_SHORT)).show ();
} catch (Exception e) { }
} } );
}
}
public static android.content.res.Resources rg_QuZiYuanGuanLiQi () {
return ms_objApp.getResources ();
}
public static android.content.res.AssetManager rg_QuZiChanGuanLiQi () {
return ms_objApp.getAssets ();
}
public static android.content.SharedPreferences rg_QuChengXuPeiZhiBiao (String rg_ChengXuPeiZhiBiaoMingChen, boolean rg_ShiFouWeiTianJiaXieChu) {
return ms_objApp.getSharedPreferences (rg_ChengXuPeiZhiBiaoMingChen,
(rg_ShiFouWeiTianJiaXieChu ? (android.content.Context.MODE_APPEND | android.content.Context.MODE_PRIVATE) : android.content.Context.MODE_PRIVATE));
}
}
|
package ConditionalStatementsAdvanced.exercise;
import java.util.Scanner;
public class FishingBoat {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int budjet = Integer.parseInt(scanner.nextLine());
String season = scanner.nextLine();
int numFishers = Integer.parseInt(scanner.nextLine());
double rent = 0;
if (season.equals("Spring")){
rent = 3000;
if (numFishers <= 6){
rent = rent * 0.9;
}else if (numFishers <= 11){
rent = rent * 0.85;
}else {
rent = rent * 0.75;
}
}else if(season.equals("Summer")){
rent = 4200;
if (numFishers <= 6){
rent = rent * 0.9;
}else if (numFishers <= 11){
rent = rent * 0.85;
}else {
rent = rent * 0.75;
}
}else if(season.equals("Autumn")){
rent = 4200;
if (numFishers <= 6){
rent = rent * 0.9;
}else if (numFishers <= 11){
rent = rent * 0.85;
}else {
rent = rent * 0.75;
}
}else if (season.equals("Winter")){
rent = 2600;
if (numFishers <= 6){
rent = rent * 0.9;
}else if (numFishers <= 11){
rent = rent * 0.85;
}else {
rent = rent * 0.75;
}
} if (numFishers % 2 == 0 && !season.equals("Autumn")){
rent = rent * 0.95;
}if (budjet >= rent){
double rest = budjet - rent;
System.out.printf("Yes! You have %.2f leva left.", rest);
}else {
double notrest = rent - budjet;
System.out.printf("Not enough money! You need %.2f leva.", notrest);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.csw.extranjeros.resources;
import co.edu.uniandes.csw.extranjeros.dtos.ViviendaDTO;
import co.edu.uniandes.csw.extranjeros.dtos.ViviendaDetailDTO;
import co.edu.uniandes.csw.extranjeros.ejb.ArrendatarioLogic;
import co.edu.uniandes.csw.extranjeros.ejb.ServicioLogic;
import co.edu.uniandes.csw.extranjeros.ejb.ValoracionLogic;
import co.edu.uniandes.csw.extranjeros.ejb.ViviendaLogic;
import co.edu.uniandes.csw.extranjeros.entities.ServicioEntity;
import co.edu.uniandes.csw.extranjeros.entities.ValoracionEntity;
import co.edu.uniandes.csw.extranjeros.entities.ViviendaEntity;
import co.edu.uniandes.csw.extranjeros.exceptions.BusinessLogicException;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
/**
*"arrendatarios/{arrendatarioId: \\\\d+}/viviendas"
* @author jd.arango
*/
@Path("viviendas")
@Produces("application/json")
@Consumes("application/json")
@RequestScoped
public class ViviendaResource {
@Inject
private ViviendaLogic logic;
@Inject
private ArrendatarioLogic arrendatarioLO;
@Inject
private ServicioLogic serviLogic;
@Inject
private ValoracionLogic valLogic;
/**
* Convierte una lista de ViviendaEntity a una lista de ViviendaDetailDTO.
*
* @param entityList Lista de AuthorEntity a convertir.
* @return Lista de AuthorDetailDTO convertida.
*
*/
private List<ViviendaDetailDTO> listEntity2DTO(List<ViviendaEntity> entityList) {
List<ViviendaDetailDTO> list = new ArrayList<>();
for (ViviendaEntity entity : entityList) {
list.add(new ViviendaDetailDTO(entity));
}
return list;
}
/**
* <h1>POST /api/viviendas : Crear una vivienda.</h1>
*
* <pre>Cuerpo de petición: JSON {@link ViviendaDetailDTO}.
*
* Crea una nueva vivienda con la informacion que se recibe en el cuerpo
* de la petición y se regresa un objeto identico con un id auto-generado
* por la base de datos.
*
* Codigos de respuesta:
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Creo la nueva vivienda .
* </code>
* </pre>
* @param vivi {@link ViviendaDetailDTO} - La vivienda que se desea guardar.
* @return JSON {@link ViviendaDetailDTO} - La vivienda guardada con el atributo id autogenerado.
*/
@POST
public ViviendaDetailDTO createVivienda(ViviendaDetailDTO vivi) {
return new ViviendaDetailDTO(logic.createVivienda(vivi.toEntity()));
}
/**
* <h1>GET /api/viviendas : Obtener todas las viviendas.</h1>
*
* <pre>Busca y devuelve todas las viviendas que existen en la aplicacion.
*
* Codigos de respuesta:
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Devuelve todas las viviendass de la aplicacion.</code>
* </pre>
* @return JSONArray {@link AuthorDetailDTO} -las viviendas encontrados en la aplicación. Si no hay ninguna retorna una lista vacía.
*/
@GET
public List<ViviendaDetailDTO> getViviendas(@QueryParam("filter") String filter){
List<ViviendaEntity> lista=logic.getViviendas();
if(filter!=null)
{
String[] filtros=filter.split(",");
if(filtros[0].equals("1:1"))
lista=logic.viviendaOrdenadaPorPrecios(lista);
if(filtros[1].startsWith("2:"))
lista=logic.viviendaPorPrecio(lista, Double.parseDouble(filtros[1].substring(2,filtros[1].length())));
if(filtros[2].startsWith("3:"))
lista=logic.viviendaPorServicios(lista, filtros[2].replace("3:", ""));
if(filtros[3].startsWith("4:"))
lista=logic.viviendaPorUniversidad(lista,Long.valueOf(filtros[3].replace("4:", "")).longValue());
if(filtros[4].startsWith("5:"))
lista=logic.viviendasPorFecha(filtros[4].replace("5:", ""));
}
return listEntity2DTO(lista);
}
/**
* <h1>GET /api/viviendas/{id} : Obtener vivienda por id.</h1>
*
* <pre>Busca la vivienda con el id asociado recibido en la URL y la devuelve.
*
* Codigos de respuesta:
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Devuelve la vivienda correspondiente al id.
* </code>
* <code style="color: #c7254e; background-color: #f9f2f4;">
* 404 Not Found No existe una vivienda con el id dado.
* </code>
* </pre>
* @param id Identificador de la vivienda que se esta buscando. Este debe ser una cadena de dígitos.
* @return JSON {@link ViviendaDetailDTO} - La vivienda buscada
* @throws WebApplicationException {@link WebApplicationExceptionMapper} - Error de lógica que se genera cuando no se encuentra el autor.
*/
@GET
@Path("{id: \\d+}")
public ViviendaDetailDTO getVivienda(@PathParam("id") Long id) {
ViviendaEntity entity = logic.getVivienda(id);
if (entity == null) {
throw new WebApplicationException("La vivienda no existe", 404);
}
return new ViviendaDetailDTO(entity);
}
/**
* <h1>PUT /api/viviendas/{id} : Actualizar vivienda con el id dado.</h1>
* <pre>Cuerpo de petición: JSON {@link ViviendaDetailDTO}.
*
* Actualiza la vivienda con el id recibido en la URL con la información que se recibe en el cuerpo de la petición.
*
* Codigos de respuesta:
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Actualiza la vivienda con el id dado con la información enviada como parámetro. Retorna un objeto identico.</code>
* <code style="color: #c7254e; background-color: #f9f2f4;">
* 404 Not Found. No existe una vivienda con el id dado.
* </code>
* </pre>
* @param id Identificador del autor que se desea actualizar. Este debe ser una cadena de dígitos.
* @param author {@link ViviendaDetailDTO} La vivienda que se desea guardar.
* @return JSON {@link ViviendaDetailDTO} - La vivienda guardada.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} - Error de lógica que se genera cuando no se encuentra la vivienda a actualizar.
*/
@PUT
@Path("{id: \\d+}")
public ViviendaDetailDTO updateVivienda(@PathParam("id") Long id, ViviendaDetailDTO vivienda) throws BusinessLogicException {
ViviendaEntity entity = vivienda.toEntity();
return new ViviendaDetailDTO(logic.updateVivienda(entity));
}
/**
* <h1>DELETE /api/viviendas/{id} : Borrar vivienda por id.</h1>
*
* <pre>Borra la vivienda con el id asociado recibido en la URL.
*
* Códigos de respuesta:<br>
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Elimina la vivienda correspondiente al id dado.</code>
* <code style="color: #c7254e; background-color: #f9f2f4;">
* 404 Not Found. No existe una vivienda con el id dado.
* </code>
* </pre>
* @param id Identificador de la vivienda que se desea borrar. Este debe ser una cadena de dígitos.
*/
@DELETE
@Path("{id: \\d+}")
public void deleteVivienda(@PathParam("id") Long id) {
ViviendaEntity entity = logic.getVivienda(id);
if (entity == null) {
throw new WebApplicationException("La vivienda no existe", 404);
}
logic.deleteVivienda(id);
}
}
|
/*
* Copyright 2010-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.k2js.analyze;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.BuiltinsScopeExtensionMode;
import org.jetbrains.jet.lang.DefaultModuleConfiguration;
import org.jetbrains.jet.lang.PlatformToKotlinClassMap;
import org.jetbrains.jet.lang.ModuleConfiguration;
import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor;
import org.jetbrains.jet.lang.psi.JetImportDirective;
import org.jetbrains.jet.lang.psi.JetPsiFactory;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.BindingTrace;
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
import org.jetbrains.jet.lang.resolve.ImportPath;
import org.jetbrains.jet.lang.resolve.name.FqName;
import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
import org.jetbrains.jet.lang.types.lang.JetStandardClasses;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.jetbrains.jet.lang.resolve.DescriptorUtils.isRootNamespace;
/**
* @author Pavel Talanov
*/
public final class JsConfiguration implements ModuleConfiguration {
@NotNull
private static final List<ImportPath> DEFAULT_IMPORT_PATHS = Arrays.asList(new ImportPath("js.*"), new ImportPath("java.lang.*"),
new ImportPath(JetStandardClasses.STANDARD_CLASSES_FQNAME,
true),
new ImportPath("kotlin.*"));
@NotNull
private final Project project;
/*
* Adds a possibility to inject some preanalyzed files to speed up tests.
* */
@Nullable
private final BindingContext preanalyzedContext;
JsConfiguration(@NotNull Project project, @Nullable BindingContext preanalyzedContext) {
this.project = project;
this.preanalyzedContext = preanalyzedContext;
}
@Override
public void addDefaultImports(@NotNull Collection<JetImportDirective> directives) {
for (ImportPath path : DEFAULT_IMPORT_PATHS) {
directives.add(JetPsiFactory.createImportDirective(project, path));
}
}
@Override
public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor,
@NotNull WritableScope namespaceMemberScope) {
DefaultModuleConfiguration.createStandardConfiguration(project, BuiltinsScopeExtensionMode.ALL)
.extendNamespaceScope(trace, namespaceDescriptor, namespaceMemberScope);
if (hasPreanalyzedContextForTests()) {
extendScopeWithPreAnalyzedContextForTests(namespaceDescriptor, namespaceMemberScope);
}
}
private boolean hasPreanalyzedContextForTests() {
return preanalyzedContext != null;
}
/*NOTE: this code is wrong. Check it if you have tests failing for frontend reasons*/
@SuppressWarnings("ConstantConditions")
private void extendScopeWithPreAnalyzedContextForTests(@NotNull NamespaceDescriptor namespaceDescriptor,
@NotNull WritableScope namespaceMemberScope) {
if (isNamespaceImportedByDefault(namespaceDescriptor) || isRootNamespace(namespaceDescriptor)) {
FqName descriptorName = DescriptorUtils.getFQName(namespaceDescriptor).toSafe();
NamespaceDescriptor alreadyAnalyzedNamespace = preanalyzedContext.get(BindingContext.FQNAME_TO_NAMESPACE_DESCRIPTOR, descriptorName);
namespaceMemberScope.importScope(alreadyAnalyzedNamespace.getMemberScope());
}
}
private static boolean isNamespaceImportedByDefault(@NotNull NamespaceDescriptor namespaceDescriptor) {
for (ImportPath path : DEFAULT_IMPORT_PATHS) {
if (path.fqnPart().equals(DescriptorUtils.getFQName(namespaceDescriptor).toSafe())) {
return true;
}
}
return false;
}
@NotNull
@Override
public PlatformToKotlinClassMap getPlatformToKotlinClassMap() {
return PlatformToKotlinClassMap.EMPTY;
}
}
|
/*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.event;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.entity.EntityLivingBase;
public abstract class RenderLivingEvent<T extends EntityLivingBase> extends Event {
private final EntityLivingBase entity;
private final RenderLivingBase<T> renderer;
private final float partialRenderTick;
private final double x;
private final double y;
private final double z;
@Deprecated
public RenderLivingEvent(EntityLivingBase entity, RenderLivingBase<T> renderer, double x, double y, double z) {
this(entity, renderer, 1, x, y, z);
}
public RenderLivingEvent(EntityLivingBase entity, RenderLivingBase<T> renderer, float partialRenderTick, double x, double y, double z) {
this.entity = entity;
this.renderer = renderer;
this.partialRenderTick = partialRenderTick;
this.x = x;
this.y = y;
this.z = z;
}
public EntityLivingBase getEntity() {
return entity;
}
public RenderLivingBase<T> getRenderer() {
return renderer;
}
public float getPartialRenderTick() {
return partialRenderTick;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
@Cancelable
public static class Pre<T extends EntityLivingBase> extends RenderLivingEvent<T> {
@Deprecated
public Pre(EntityLivingBase entity, RenderLivingBase<T> renderer, double x, double y, double z) {
super(entity, renderer, x, y, z);
}
public Pre(EntityLivingBase entity, RenderLivingBase<T> renderer, float partialRenderTick, double x, double y, double z) {
super(entity, renderer, partialRenderTick, x, y, z);
}
}
public static class Post<T extends EntityLivingBase> extends RenderLivingEvent<T> {
@Deprecated
public Post(EntityLivingBase entity, RenderLivingBase<T> renderer, double x, double y, double z) {
super(entity, renderer, x, y, z);
}
public Post(EntityLivingBase entity, RenderLivingBase<T> renderer, float partialRenderTick, double x, double y, double z) {
super(entity, renderer, partialRenderTick, x, y, z);
}
}
public abstract static class Specials<T extends EntityLivingBase> extends RenderLivingEvent<T> {
public Specials(EntityLivingBase entity, RenderLivingBase<T> renderer, double x, double y, double z) {
super(entity, renderer, 0, x, y, z);
}
@Cancelable
public static class Pre<T extends EntityLivingBase> extends Specials<T> {
public Pre(EntityLivingBase entity, RenderLivingBase<T> renderer, double x, double y, double z) {
super(entity, renderer, x, y, z);
}
}
public static class Post<T extends EntityLivingBase> extends Specials<T> {
public Post(EntityLivingBase entity, RenderLivingBase<T> renderer, double x, double y, double z) {
super(entity, renderer, x, y, z);
}
}
}
}
|
package com.sonnata.sonnata;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class rythmeCours extends AppCompatActivity {
Button boutRetour = null;
ImageButton boutLARonde = null;
ImageButton boutLABlanche = null;
ImageButton boutLANoire = null;
ImageButton boutLA2croches = null;
ImageButton boutLA4doubles = null;
ImageButton boutLAnoirePoint = null;
ImageButton boutLAcrochepoint = null;
ImageButton boutLAdoubleCroche = null;
ImageButton boutLAtriolet = null;
ImageButton boutLAcroche2doubles = null;
ImageButton boutLA2doublesCroche = null;
ImageButton boutLAsyncope = null;
ImageButton boutLAsyncopette = null;
MediaPlayer son = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rythme_cours);
boutRetour = (Button) findViewById(R.id.buttonRetour);
boutLARonde = (ImageButton) findViewById(R.id.imageButtonLARonde);
boutLABlanche = (ImageButton) findViewById(R.id.imageButtonLABlanche);
boutLANoire = (ImageButton) findViewById(R.id.imageButtonLANoire);
boutLA2croches = (ImageButton) findViewById(R.id.imageButtonLA2croches);
boutLA4doubles = (ImageButton) findViewById(R.id.imageButtonLA4doubles);
boutLAnoirePoint = (ImageButton) findViewById(R.id.imageButtonLANoirePoint);
boutLAcrochepoint = (ImageButton) findViewById(R.id.imageButtonLACrochePoint);
boutLAdoubleCroche = (ImageButton) findViewById(R.id.imageButtonLADoubleCrochePoint);
boutLAtriolet = (ImageButton) findViewById(R.id.imageButtonLATriolet);
boutLAcroche2doubles = (ImageButton) findViewById(R.id.imageButtonLACroche2doubles);
boutLA2doublesCroche = (ImageButton) findViewById(R.id.imageButtonLA2doubleCroche);
boutLAsyncope = (ImageButton) findViewById(R.id.imageButtonLASyncope);
boutLAsyncopette = (ImageButton) findViewById(R.id.imageButtonLASyncopette);
boutRetour.setOnClickListener(boutRetourListener);
boutLARonde.setOnClickListener(boutLARondeListener);
boutLABlanche.setOnClickListener(boutLABlancheListener);
boutLANoire.setOnClickListener(boutLANoireListener);
boutLA2croches.setOnClickListener(boutLA2crochesListener);
boutLA4doubles.setOnClickListener(boutLA4doublesListener);
boutLAnoirePoint.setOnClickListener(boutLANoirePointListener);
boutLAcrochepoint.setOnClickListener(boutLAcrochePointListener);
boutLAdoubleCroche.setOnClickListener(boutLAdoubleCrochePointListener);
boutLAtriolet.setOnClickListener(boutLAtrioletListener);
boutLAcroche2doubles.setOnClickListener(boutLAcroche2doublesListener);
boutLA2doublesCroche.setOnClickListener(boutLA2doublesCrocheListener);
boutLAsyncope.setOnClickListener(boutLAsyncopeListener);
boutLAsyncopette.setOnClickListener(boutLAsyncopetteListener);
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_ronde);
}
//Uniquement si le bouton Retour est appuie
private View.OnClickListener boutRetourListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
Intent menu = new Intent(rythmeCours.this, Rythme.class);
startActivity(menu);
finish();
}
};
private View.OnClickListener boutLARondeListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_ronde);
son.start();
}
};
private View.OnClickListener boutLABlancheListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_blanche);
son.start();
}
};
private View.OnClickListener boutLANoireListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_noire);
son.start();
}
};
private View.OnClickListener boutLA2crochesListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_deux_croches);
son.start();
}
};
private View.OnClickListener boutLA4doublesListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_quatre_double_croches);
son.start();
}
};
private View.OnClickListener boutLANoirePointListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_noire_pointee_croche);
son.start();
}
};
private View.OnClickListener boutLAcrochePointListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_croche_pointee_double);
son.start();
}
};
private View.OnClickListener boutLAdoubleCrochePointListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_double_croche_pointee);
son.start();
}
};
private View.OnClickListener boutLAtrioletListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_triolet);
son.start();
}
};
private View.OnClickListener boutLAcroche2doublesListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_croche_deux_doubles);
son.start();
}
};
private View.OnClickListener boutLA2doublesCrocheListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this, R.raw.piano_la_440_deux_doubles_croche);
son.start();
}
};
private View.OnClickListener boutLAsyncopeListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_syncope);
son.start();
}
};
private View.OnClickListener boutLAsyncopetteListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
son.release();
son = MediaPlayer.create(rythmeCours.this,R.raw.piano_la_440_syncopette);
son.start();
}
};
}
|
package com.lexisnexis.platform.eclwatch;
//import autoitx4java.AutoItX;
//import autoit-0.1.13;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.openqa.selenium.By;
import com.lexisnexis.platform.eclwatch.testharness.Timeout;
import com.lexisnexis.platform.eclwatch.testharness.Timeout.Group;
@RunWith(BlockJUnit4ClassRunner.class)
public class LogicalFileOpenLinkTest extends TestBaseBocaDev {
@Test
@Timeout(group = Group.SLOW)
public void testLogicalFileOpenTest() throws Exception {
String expectedTitle = "ECL Watch";
// Login to Ecl Watch
driver.navigate().to(appUrl);
Thread.sleep(3000);
// Login
driver.findElement(By.id("username")).sendKeys(properties.getProperty("Username"));
driver.findElement(By.id("password")).sendKeys(properties.getProperty("Password"));
driver.findElement(By.id("button")).click();
Thread.sleep(2000);
// Click Files Icon
driver.findElement(By.xpath(".//*[@id='stubStackController_stub_Files']/span[1]")).click();
Thread.sleep(5000);
System.out.println("Files Icon Clicked");
// Click on Filter Drop Down
driver.findElement(By.id("stub_Files-DL_LogicalFiles-DLFilterFilterDropDown")).click();
Thread.sleep(2000);
System.out.println("Filter Icon Clicked");
// waitForLogicalFileFilterBoxToLoad();
System.out.println("Filter Box Loaded");
// Enter Name in Filter Box
driver.findElement(By.id("stub_Files-DL_LogicalFiles-DLName")).sendKeys(properties.getProperty("LogicalFile"));
Thread.sleep(2000);
// Click on Apply
driver.findElement(By.id("stub_Files-DL_LogicalFiles-DLFilterFilterApply_label")).click();
waitForLogicalFileFilterNameToLoad();
Thread.sleep(2000);
// assertEquals("thor::platform_test::test_13264_xml_fixed_compressed (hthor__dev_eclagent_1)",
// driver.findElement(By.xpath("//*[@id=\"stub_Main-DL_Search-DLGrid-row-2\"]/table/tr/td[4]/a")).getText().trim());
Thread.sleep(2000);
// Select logical file
driver.findElement(By.xpath("//*[@id=\"stub_Files-DL_LogicalFiles-DLWorkunitsGrid-row-hthor__dev_eclagent_1--thor::platform_test::test_13264_xml_fixed_compressed\"]/table/tr/td[1]/input")).click();
System.out.println("Logical File Selected");
Thread.sleep(2000);
// Click on Open link button
driver.findElement(By.id("stub_Files-DL_LogicalFiles-DLOpen_label")).click();
waitForAlphaDevLogicalFilesOpenSummaryToLoad();
Thread.sleep(2000);
assertEquals("thor::platform_test::test_13264_xml_fixed_compressed", driver.findElement(By.id("stub_Files-DL_LogicalFiles-DL_hthorxxdevxeclagentx1xxthorxxplatformxtestxxtestx13264xxmlxfixedxcompressed-DLName")).getText().trim());
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.common.implementation;
import com.azure.common.annotations.BodyParam;
import com.azure.common.annotations.GET;
import com.azure.common.annotations.Host;
import com.azure.common.annotations.PUT;
import com.azure.common.entities.AccessPolicy;
import com.azure.common.entities.SignedIdentifierInner;
import com.azure.common.entities.SignedIdentifiersWrapper;
import com.azure.common.entities.Slideshow;
import com.azure.common.http.HttpClient;
import com.azure.common.http.HttpHeaders;
import com.azure.common.http.HttpMethod;
import com.azure.common.http.HttpPipeline;
import com.azure.common.http.HttpRequest;
import com.azure.common.http.HttpResponse;
import com.azure.common.http.MockHttpResponse;
import com.azure.common.http.ProxyOptions;
import com.azure.common.implementation.serializer.SerializerEncoding;
import com.azure.common.implementation.serializer.jackson.JacksonAdapter;
import com.azure.common.implementation.util.FluxUtil;
import org.junit.Test;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class RestProxyXMLTests {
static class MockXMLHTTPClient implements HttpClient {
private HttpResponse response(HttpRequest request, String resource) throws IOException, URISyntaxException {
URL url = getClass().getClassLoader().getResource(resource);
byte[] bytes = Files.readAllBytes(Paths.get(url.toURI()));
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/xml");
HttpResponse res = new MockHttpResponse(request, 200, headers, bytes);
return res;
}
@Override
public Mono<HttpResponse> send(HttpRequest request) {
try {
if (request.url().toString().endsWith("GetContainerACLs")) {
return Mono.just(response(request, "GetContainerACLs.xml"));
} else if (request.url().toString().endsWith("GetXMLWithAttributes")) {
return Mono.just(response(request, "GetXMLWithAttributes.xml"));
} else {
return Mono.<HttpResponse>just(new MockHttpResponse(request, 404));
}
} catch (IOException | URISyntaxException e) {
return Mono.error(e);
}
}
@Override
public HttpClient proxy(Supplier<ProxyOptions> proxyOptions) {
throw new IllegalStateException("MockHttpClient.proxy");
}
@Override
public HttpClient wiretap(boolean enableWiretap) {
throw new IllegalStateException("MockHttpClient.wiretap");
}
@Override
public HttpClient port(int port) {
throw new IllegalStateException("MockHttpClient.port");
}
}
@Host("http://unused")
interface MyXMLService {
@GET("GetContainerACLs")
SignedIdentifiersWrapper getContainerACLs();
@PUT("SetContainerACLs")
void setContainerACLs(@BodyParam("application/xml") SignedIdentifiersWrapper signedIdentifiers);
}
@Test
public void canReadXMLResponse() throws Exception {
//
final HttpPipeline pipeline = new HttpPipeline(new MockXMLHTTPClient());
//
MyXMLService myXMLService = RestProxy.create(MyXMLService.class,
pipeline,
new JacksonAdapter());
List<SignedIdentifierInner> identifiers = myXMLService.getContainerACLs().signedIdentifiers();
assertNotNull(identifiers);
assertNotEquals(0, identifiers.size());
}
static class MockXMLReceiverClient implements HttpClient {
byte[] receivedBytes = null;
@Override
public Mono<HttpResponse> send(HttpRequest request) {
if (request.url().toString().endsWith("SetContainerACLs")) {
return FluxUtil.collectBytesInByteBufStream(request.body(), false)
.map(bytes -> {
receivedBytes = bytes;
return new MockHttpResponse(request, 200);
});
} else {
return Mono.<HttpResponse>just(new MockHttpResponse(request, 404));
}
}
@Override
public HttpClient proxy(Supplier<ProxyOptions> proxyOptions) {
throw new IllegalStateException("MockHttpClient.proxy");
}
@Override
public HttpClient wiretap(boolean enableWiretap) {
throw new IllegalStateException("MockHttpClient.wiretap");
}
@Override
public HttpClient port(int port) {
throw new IllegalStateException("MockHttpClient.port");
}
}
@Test
public void canWriteXMLRequest() throws Exception {
URL url = getClass().getClassLoader().getResource("GetContainerACLs.xml");
byte[] bytes = Files.readAllBytes(Paths.get(url.toURI()));
HttpRequest request = new HttpRequest(HttpMethod.PUT, new URL("http://unused/SetContainerACLs"));
request.withBody(bytes);
SignedIdentifierInner si = new SignedIdentifierInner();
si.withId("MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=");
AccessPolicy ap = new AccessPolicy();
ap.withStart(OffsetDateTime.parse("2009-09-28T08:49:37.0000000Z"));
ap.withExpiry(OffsetDateTime.parse("2009-09-29T08:49:37.0000000Z"));
ap.withPermission("rwd");
si.withAccessPolicy(ap);
List<SignedIdentifierInner> expectedAcls = Collections.singletonList(si);
JacksonAdapter serializer = new JacksonAdapter();
MockXMLReceiverClient httpClient = new MockXMLReceiverClient();
//
final HttpPipeline pipeline = new HttpPipeline(httpClient);
//
MyXMLService myXMLService = RestProxy.create(MyXMLService.class,
pipeline,
serializer);
SignedIdentifiersWrapper wrapper = new SignedIdentifiersWrapper(expectedAcls);
myXMLService.setContainerACLs(wrapper);
SignedIdentifiersWrapper actualAclsWrapped = serializer.deserialize(
new String(httpClient.receivedBytes, StandardCharsets.UTF_8),
SignedIdentifiersWrapper.class,
SerializerEncoding.XML);
List<SignedIdentifierInner> actualAcls = actualAclsWrapped.signedIdentifiers();
// Ideally we'd just check for "things that matter" about the XML-- e.g. the tag names, structure, and attributes needs to be the same,
// but it doesn't matter if one document has a trailing newline or has UTF-8 in the header instead of utf-8, or if comments are missing.
assertEquals(expectedAcls.size(), actualAcls.size());
assertEquals(expectedAcls.get(0).id(), actualAcls.get(0).id());
assertEquals(expectedAcls.get(0).accessPolicy().expiry(), actualAcls.get(0).accessPolicy().expiry());
assertEquals(expectedAcls.get(0).accessPolicy().start(), actualAcls.get(0).accessPolicy().start());
assertEquals(expectedAcls.get(0).accessPolicy().permission(), actualAcls.get(0).accessPolicy().permission());
}
@Host("http://unused")
public interface MyXMLServiceWithAttributes {
@GET("GetXMLWithAttributes")
Slideshow getSlideshow();
}
@Test
public void canDeserializeXMLWithAttributes() throws Exception {
JacksonAdapter serializer = new JacksonAdapter();
//
final HttpPipeline pipeline = new HttpPipeline(new MockXMLHTTPClient());
//
MyXMLServiceWithAttributes myXMLService = RestProxy.create(
MyXMLServiceWithAttributes.class,
pipeline,
serializer);
Slideshow slideshow = myXMLService.getSlideshow();
assertEquals("Sample Slide Show", slideshow.title());
assertEquals("Date of publication", slideshow.date());
assertEquals("Yours Truly", slideshow.author());
assertEquals(2, slideshow.slides().length);
assertEquals("all", slideshow.slides()[0].type());
assertEquals("Wake up to WonderWidgets!", slideshow.slides()[0].title());
assertNull(slideshow.slides()[0].items());
assertEquals("all", slideshow.slides()[1].type());
assertEquals("Overview", slideshow.slides()[1].title());
assertEquals(3, slideshow.slides()[1].items().length);
assertEquals("Why WonderWidgets are great", slideshow.slides()[1].items()[0]);
assertEquals("", slideshow.slides()[1].items()[1]);
assertEquals("Who buys WonderWidgets", slideshow.slides()[1].items()[2]);
String xml = serializer.serialize(slideshow, SerializerEncoding.XML);
Slideshow newSlideshow = serializer.deserialize(xml, Slideshow.class, SerializerEncoding.XML);
String newXML = serializer.serialize(newSlideshow, SerializerEncoding.XML);
assertEquals(xml, newXML);
}
}
|
/*
* (C) Copyright IBM Corp. 2021.
*
* 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.ibm.cloud.mdm.v1.model;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* The createMatchingMatchJob options.
*/
public class CreateMatchingMatchJobOptions extends GenericModel {
protected String recordType;
protected String entityType;
protected Boolean doForce;
protected Boolean doDeduplicate;
protected Boolean doAnalytics;
protected Boolean doReplicate;
protected Long executorCount;
protected String executorMemory;
protected Long executorCoreCount;
protected String logCosEndpoint;
protected String logCosBucket;
protected String logCosAccessKey;
protected String logCosSecretKey;
/**
* Builder.
*/
public static class Builder {
private String recordType;
private String entityType;
private Boolean doForce;
private Boolean doDeduplicate;
private Boolean doAnalytics;
private Boolean doReplicate;
private Long executorCount;
private String executorMemory;
private Long executorCoreCount;
private String logCosEndpoint;
private String logCosBucket;
private String logCosAccessKey;
private String logCosSecretKey;
private Builder(CreateMatchingMatchJobOptions createMatchingMatchJobOptions) {
this.recordType = createMatchingMatchJobOptions.recordType;
this.entityType = createMatchingMatchJobOptions.entityType;
this.doForce = createMatchingMatchJobOptions.doForce;
this.doDeduplicate = createMatchingMatchJobOptions.doDeduplicate;
this.doAnalytics = createMatchingMatchJobOptions.doAnalytics;
this.doReplicate = createMatchingMatchJobOptions.doReplicate;
this.executorCount = createMatchingMatchJobOptions.executorCount;
this.executorMemory = createMatchingMatchJobOptions.executorMemory;
this.executorCoreCount = createMatchingMatchJobOptions.executorCoreCount;
this.logCosEndpoint = createMatchingMatchJobOptions.logCosEndpoint;
this.logCosBucket = createMatchingMatchJobOptions.logCosBucket;
this.logCosAccessKey = createMatchingMatchJobOptions.logCosAccessKey;
this.logCosSecretKey = createMatchingMatchJobOptions.logCosSecretKey;
}
/**
* Instantiates a new builder.
*/
public Builder() {
}
/**
* Builds a CreateMatchingMatchJobOptions.
*
* @return the new CreateMatchingMatchJobOptions instance
*/
public CreateMatchingMatchJobOptions build() {
return new CreateMatchingMatchJobOptions(this);
}
/**
* Set the recordType.
*
* @param recordType the recordType
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder recordType(String recordType) {
this.recordType = recordType;
return this;
}
/**
* Set the entityType.
*
* @param entityType the entityType
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder entityType(String entityType) {
this.entityType = entityType;
return this;
}
/**
* Set the doForce.
*
* @param doForce the doForce
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder doForce(Boolean doForce) {
this.doForce = doForce;
return this;
}
/**
* Set the doDeduplicate.
*
* @param doDeduplicate the doDeduplicate
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder doDeduplicate(Boolean doDeduplicate) {
this.doDeduplicate = doDeduplicate;
return this;
}
/**
* Set the doAnalytics.
*
* @param doAnalytics the doAnalytics
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder doAnalytics(Boolean doAnalytics) {
this.doAnalytics = doAnalytics;
return this;
}
/**
* Set the doReplicate.
*
* @param doReplicate the doReplicate
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder doReplicate(Boolean doReplicate) {
this.doReplicate = doReplicate;
return this;
}
/**
* Set the executorCount.
*
* @param executorCount the executorCount
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder executorCount(long executorCount) {
this.executorCount = executorCount;
return this;
}
/**
* Set the executorMemory.
*
* @param executorMemory the executorMemory
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder executorMemory(String executorMemory) {
this.executorMemory = executorMemory;
return this;
}
/**
* Set the executorCoreCount.
*
* @param executorCoreCount the executorCoreCount
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder executorCoreCount(long executorCoreCount) {
this.executorCoreCount = executorCoreCount;
return this;
}
/**
* Set the logCosEndpoint.
*
* @param logCosEndpoint the logCosEndpoint
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder logCosEndpoint(String logCosEndpoint) {
this.logCosEndpoint = logCosEndpoint;
return this;
}
/**
* Set the logCosBucket.
*
* @param logCosBucket the logCosBucket
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder logCosBucket(String logCosBucket) {
this.logCosBucket = logCosBucket;
return this;
}
/**
* Set the logCosAccessKey.
*
* @param logCosAccessKey the logCosAccessKey
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder logCosAccessKey(String logCosAccessKey) {
this.logCosAccessKey = logCosAccessKey;
return this;
}
/**
* Set the logCosSecretKey.
*
* @param logCosSecretKey the logCosSecretKey
* @return the CreateMatchingMatchJobOptions builder
*/
public Builder logCosSecretKey(String logCosSecretKey) {
this.logCosSecretKey = logCosSecretKey;
return this;
}
}
protected CreateMatchingMatchJobOptions(Builder builder) {
recordType = builder.recordType;
entityType = builder.entityType;
doForce = builder.doForce;
doDeduplicate = builder.doDeduplicate;
doAnalytics = builder.doAnalytics;
doReplicate = builder.doReplicate;
executorCount = builder.executorCount;
executorMemory = builder.executorMemory;
executorCoreCount = builder.executorCoreCount;
logCosEndpoint = builder.logCosEndpoint;
logCosBucket = builder.logCosBucket;
logCosAccessKey = builder.logCosAccessKey;
logCosSecretKey = builder.logCosSecretKey;
}
/**
* New builder.
*
* @return a CreateMatchingMatchJobOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the recordType.
*
* The data type identifier of source records, ie. person, organization, contract.
*
* @return the recordType
*/
public String recordType() {
return recordType;
}
/**
* Gets the entityType.
*
* The data type identifier of entity, ie. person_entity, organization_entity, household_entity.
*
* @return the entityType
*/
public String entityType() {
return entityType;
}
/**
* Gets the doForce.
*
* Force to re-match all records, default is false.
*
* @return the doForce
*/
public Boolean doForce() {
return doForce;
}
/**
* Gets the doDeduplicate.
*
* Deduplicate pairs, default is false.
*
* @return the doDeduplicate
*/
public Boolean doDeduplicate() {
return doDeduplicate;
}
/**
* Gets the doAnalytics.
*
* collect analysis report, default is false.
*
* @return the doAnalytics
*/
public Boolean doAnalytics() {
return doAnalytics;
}
/**
* Gets the doReplicate.
*
* Replicate entity id, default is false.
*
* @return the doReplicate
*/
public Boolean doReplicate() {
return doReplicate;
}
/**
* Gets the executorCount.
*
* The number of spark executors.
*
* @return the executorCount
*/
public Long executorCount() {
return executorCount;
}
/**
* Gets the executorMemory.
*
* Amount of memory to use per executor process.
*
* @return the executorMemory
*/
public String executorMemory() {
return executorMemory;
}
/**
* Gets the executorCoreCount.
*
* The number of cores to use on each executor.
*
* @return the executorCoreCount
*/
public Long executorCoreCount() {
return executorCoreCount;
}
/**
* Gets the logCosEndpoint.
*
* IBM COS end point for job log storage.
*
* @return the logCosEndpoint
*/
public String logCosEndpoint() {
return logCosEndpoint;
}
/**
* Gets the logCosBucket.
*
* IBM COS bucket for job log storage.
*
* @return the logCosBucket
*/
public String logCosBucket() {
return logCosBucket;
}
/**
* Gets the logCosAccessKey.
*
* IBM COS access key for spark log storage.
*
* @return the logCosAccessKey
*/
public String logCosAccessKey() {
return logCosAccessKey;
}
/**
* Gets the logCosSecretKey.
*
* IBM COS secret key for spark log storage.
*
* @return the logCosSecretKey
*/
public String logCosSecretKey() {
return logCosSecretKey;
}
}
|
package contest.acm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class ACM_Foxling_Feeding_Frenzy {
static final int MOD = 1000000007;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
public static void main(String[] args) throws IOException {
for (int t = readInt(); t > 0; t--) {
int n = readInt();
int m = readInt();
int sumOfHi = 0;
Interval[] i = new Interval[n + 1];
for (int x = 1; x <= n; x++) {
int a = readInt();
int b = readInt();
m -= a;
b -= a;
a -= a;
sumOfHi += b;
i[x] = new Interval(a, b);
}
if (m < 0 || m > sumOfHi) {
System.out.println(0);
continue;
}
long[][] dp = new long[n + 1][m + 1];
for (int x = 0; x < n + 1; x++)
for (int y = 1; y < m + 1; y++)
dp[x][y] = -1;
dp[0][0] = 0;
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= m; y++) {
long sum = Integer.MIN_VALUE;
for (int z = 0; z <= i[x].hi; z++) {
if (y - z >= 0) {
if (dp[x - 1][y - z] >= 0)
sum = (Math.max(sum, 0) + dp[x - 1][y - z]) % MOD;
}
}
if (y - i[x].hi <= 0)
dp[x][y] = sum + 1;
else
dp[x][y] = sum;
}
}
System.out.println(dp[n][m] % MOD);
}
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static String readLine() throws IOException {
return br.readLine().trim();
}
static class Interval {
int lo, hi;
Interval(int lo, int hi) {
this.lo = lo;
this.hi = hi;
}
}
}
|
package com.sequenceiq.cloudbreak.core.flow2.chain;
import static com.sequenceiq.cloudbreak.core.flow2.cluster.downscale.ClusterDownscaleEvent.DECOMMISSION_EVENT;
import static com.sequenceiq.cloudbreak.core.flow2.stack.downscale.StackDownscaleEvent.STACK_DOWNSCALE_EVENT;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.cloud.event.Selectable;
import com.sequenceiq.cloudbreak.common.type.ScalingType;
import com.sequenceiq.cloudbreak.core.flow2.event.ClusterAndStackDownscaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.ClusterDownscaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.ClusterScaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.StackDownscaleTriggerEvent;
import com.sequenceiq.cloudbreak.core.flow2.event.StackScaleTriggerEvent;
import com.sequenceiq.cloudbreak.domain.Constraint;
import com.sequenceiq.cloudbreak.domain.stack.cluster.host.HostGroup;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceGroup;
import com.sequenceiq.cloudbreak.domain.view.StackView;
import com.sequenceiq.cloudbreak.service.hostgroup.HostGroupService;
import com.sequenceiq.cloudbreak.service.stack.StackService;
@Component
public class DownscaleFlowEventChainFactory implements FlowEventChainFactory<ClusterAndStackDownscaleTriggerEvent> {
@Inject
private StackService stackService;
@Inject
private HostGroupService hostGroupService;
@Override
public String initEvent() {
return FlowChainTriggers.FULL_DOWNSCALE_TRIGGER_EVENT;
}
@Override
public Queue<Selectable> createFlowTriggerEventQueue(ClusterAndStackDownscaleTriggerEvent event) {
Queue<Selectable> flowEventChain = new ConcurrentLinkedQueue<>();
ClusterScaleTriggerEvent cste;
if (event.getPrivateIds() == null) {
cste = new ClusterDownscaleTriggerEvent(DECOMMISSION_EVENT.event(), event.getStackId(), event.getHostGroupName(),
event.getAdjustment(), event.accepted(), event.getDetails());
} else {
cste = new ClusterDownscaleTriggerEvent(DECOMMISSION_EVENT.event(), event.getStackId(), event.getHostGroupName(),
event.getPrivateIds(), event.accepted(), event.getDetails());
}
flowEventChain.add(cste);
if (event.getScalingType() == ScalingType.DOWNSCALE_TOGETHER) {
StackView stackView = stackService.getViewByIdWithoutAuth(event.getStackId());
HostGroup hostGroup = hostGroupService.getByClusterIdAndName(stackView.getClusterView().getId(), event.getHostGroupName());
Constraint hostGroupConstraint = hostGroup.getConstraint();
String instanceGroupName = Optional.ofNullable(hostGroupConstraint.getInstanceGroup()).map(InstanceGroup::getGroupName).orElse(null);
StackScaleTriggerEvent sste;
if (event.getPrivateIds() == null) {
sste = new StackDownscaleTriggerEvent(STACK_DOWNSCALE_EVENT.event(), event.getStackId(), instanceGroupName, event.getAdjustment());
} else {
sste = new StackDownscaleTriggerEvent(STACK_DOWNSCALE_EVENT.event(), event.getStackId(), instanceGroupName, event.getPrivateIds());
}
flowEventChain.add(sste);
}
return flowEventChain;
}
}
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt
*
* 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.jvnet.hudson.test;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.FilePath;
import hudson.remoting.Which;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
/**
* Ensures that {@code jenkins.war} is exploded.
*
* <p>
* Depending on where the test is run (for example, inside Maven vs IDE), this code attempts to
* use jenkins.war from the right place, thereby improving the productivity.
*
* @author Kohsuke Kawaguchi
*/
public final class WarExploder {
private static final Logger LOGGER = Logger.getLogger(WarExploder.class.getName());
public static final String JENKINS_WAR_PATH_PROPERTY_NAME = "jth.jenkins-war.path";
@CheckForNull
private static final String JENKINS_WAR_PATH = System.getProperty(JENKINS_WAR_PATH_PROPERTY_NAME);
public static synchronized File getExplodedDir() throws Exception {
if (EXPLODE_DIR == null) {
EXPLODE_DIR = explode();
}
return EXPLODE_DIR;
}
private static File EXPLODE_DIR;
static File findJenkinsWar() throws Exception {
File war;
if (JENKINS_WAR_PATH != null) {
war = new File(JENKINS_WAR_PATH).getAbsoluteFile();
LOGGER.log(Level.INFO, "Using a predefined WAR file {0} define by the {1} system property",
new Object[] {war, JENKINS_WAR_PATH_PROPERTY_NAME});
if (!war.exists()) {
throw new IOException("A Predefined WAR file path does not exist: " + war);
} else if (!war.isFile()) {
throw new IOException("A Predefined WAR file path does not point to a file: " + war);
}
} else {
// locate jenkins.war
URL winstone = WarExploder.class.getResource("/winstone.jar");
if (winstone != null) {
war = Which.jarFile(Class.forName("executable.Executable"));
} else {
// JENKINS-45245: work around incorrect test classpath in IDEA. Note that this will not correctly handle timestamped snapshots; in that case use `mvn test`.
File core = Which.jarFile(Jenkins.class); // will fail with IllegalArgumentException if have neither jenkins-war.war nor jenkins-core.jar in ${java.class.path}
String version = core.getParentFile().getName();
if (core.getName().equals("jenkins-core-" + version + ".jar") && core.getParentFile().getParentFile().getName().equals("jenkins-core")) {
war = new File(new File(new File(core.getParentFile().getParentFile().getParentFile(), "jenkins-war"), version), "jenkins-war-" + version + ".war");
if (!war.isFile()) {
throw new AssertionError(war + " does not yet exist. Prime your development environment by running `mvn validate`.");
}
LOGGER.log(Level.FINE, "{0} is the continuation of the classpath by other means", war);
} else {
throw new AssertionError(core + " is not in the expected location, and jenkins-war-*.war was not in " + System.getProperty("java.class.path"));
}
}
}
return war;
}
/**
* Explodes jenkins.war, if necessary, and returns its root dir.
*/
private static File explode() throws Exception {
// are we in the Jenkins main workspace? If so, pick up hudson/main/war/resources
// this saves the effort of packaging a war file and makes the debug cycle faster
File d = new File(".").getAbsoluteFile();
for( ; d!=null; d=d.getParentFile()) {
if(new File(d,".jenkins").exists()) {
File dir = new File(d,"war/target/jenkins");
if(dir.exists()) {
LOGGER.log(Level.INFO, "Using jenkins.war resources from {0}", dir);
return dir;
}
}
}
final File war = findJenkinsWar();
// TODO this assumes that the CWD of the Maven process is the plugin ${basedir}, which may not be the case
File buildDirectory = new File(System.getProperty("buildDirectory", "target"));
File explodeDir = new File(buildDirectory, "jenkins-for-test").getAbsoluteFile();
explodeDir.getParentFile().mkdirs();
while (new File(explodeDir + ".exploding").isFile()) {
explodeDir = new File(explodeDir + "x");
}
File timestamp = new File(explodeDir,".timestamp");
if(!timestamp.exists() || (timestamp.lastModified()!=war.lastModified())) {
LOGGER.log(Level.INFO, "Exploding {0} into {1}", new Object[] {war, explodeDir});
new FileOutputStream(explodeDir + ".exploding").close();
new FilePath(explodeDir).deleteRecursive();
new FilePath(war).unzip(new FilePath(explodeDir));
if(!explodeDir.exists()) // this is supposed to be impossible, but I'm investigating HUDSON-2605
throw new IOException("Failed to explode "+war);
new FileOutputStream(timestamp).close();
timestamp.setLastModified(war.lastModified());
new File(explodeDir + ".exploding").delete();
} else {
LOGGER.log(Level.INFO, "Picking up existing exploded jenkins.war at {0}", explodeDir.getAbsolutePath());
}
return explodeDir;
}
private WarExploder() {}
}
|
package de.smartformer.articlesapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ArticlesApiApplication {
public static void main(String[] args) {
SpringApplication.run(ArticlesApiApplication.class, args);
}
}
|
package org.mage.test.cards.abilities.keywords;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* @author BetaSteward
*/
public class ConspireTest extends CardTestPlayerBase {
/**
* 702.77. Conspire 702.77a Conspire is a keyword that represents two
* abilities. The first is a static ability that functions while the spell
* with conspire is on the stack. The second is a triggered ability that
* functions while the spell with conspire is on the stack. “Conspire” means
* “As an additional cost to cast this spell, you may tap two untapped
* creatures you control that each share a color with it” and “When you cast
* this spell, if its conspire cost was paid, copy it. If the spell has any
* targets, you may choose new targets for the copy.” Paying a spell's
* conspire cost follows the rules for paying additional costs in rules
* 601.2b and 601.2e–g.
*
* 702.77b If a spell has multiple instances of conspire, each is paid
* separately and triggers based on its own payment, not any other instance
* of conspire
*
*/
/**
* Burn Trail Sorcery, 3R (4) Burn Trail deals 3 damage to target creature
* or player.
* <p>
* Conspire (As you cast this spell, you may tap two untapped creatures you
* control that share a color with it. When you do, copy it and you may
* choose a new target for the copy.)
*/
@Test
public void testConspire() {
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 4);
addCard(Zone.BATTLEFIELD, playerA, "Goblin Roughrider");
addCard(Zone.BATTLEFIELD, playerA, "Raging Goblin");
addCard(Zone.HAND, playerA, "Burn Trail");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Burn Trail", playerB);
setChoice(playerA, true);
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertLife(playerB, 20 - 3 - 3);
assertGraveyardCount(playerA, "Burn Trail", 1);
assertTapped("Goblin Roughrider", true);
assertTapped("Raging Goblin", true);
}
@Test
public void testConspireNotUsed() {
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 4);
addCard(Zone.BATTLEFIELD, playerA, "Goblin Roughrider");
addCard(Zone.BATTLEFIELD, playerA, "Raging Goblin");
addCard(Zone.HAND, playerA, "Burn Trail");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Burn Trail", playerB);
setChoice(playerA, false);
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertLife(playerB, 20 - 3);
assertGraveyardCount(playerA, "Burn Trail", 1);
assertTapped("Goblin Roughrider", false);
assertTapped("Raging Goblin", false);
}
@Test
public void testWortTheRaidmother() {
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 7);
// When Wort, the Raidmother enters the battlefield, put two 1/1 red and green Goblin Warrior creature tokens onto the battlefield.
// Each red or green instant or sorcery spell you cast has conspire.
// (As you cast the spell, you may tap two untapped creatures you control that share a color with it. When you do, copy it and you may choose new targets for the copy.)
addCard(Zone.HAND, playerA, "Wort, the Raidmother");
addCard(Zone.HAND, playerA, "Lightning Bolt");
// prepare goblins
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Wort, the Raidmother");// {4}{R/G}{R/G}
// cast with conspire
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Lightning Bolt", playerB);
setChoice(playerA, true); // use conspire
setChoice(playerA, "Goblin Warrior Token");
setChoice(playerA, "Goblin Warrior Token");
setChoice(playerA, false); // keep targets
setStrictChooseMode(true);
setStopAt(1, PhaseStep.END_TURN);
execute();
assertAllCommandsUsed();
assertPermanentCount(playerA, "Wort, the Raidmother", 1);
assertGraveyardCount(playerA, "Lightning Bolt", 1);
assertLife(playerB, 20 - 3 - 3);
}
@Test
public void testWortTheRaidmotherTwoSpells() {
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
addCard(Zone.BATTLEFIELD, playerA, "Raging Goblin", 2);
// When Wort, the Raidmother enters the battlefield, put two 1/1 red and green Goblin Warrior creature tokens onto the battlefield.
// Each red or green instant or sorcery spell you cast has conspire.
// (As you cast the spell, you may tap two untapped creatures you control that share a color with it. When you do, copy it and you may choose new targets for the copy.)
addCard(Zone.HAND, playerA, "Wort, the Raidmother");
addCard(Zone.HAND, playerA, "Lightning Bolt");
addCard(Zone.HAND, playerA, "Shock");
// prepare goblins
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Wort, the Raidmother");// {4}{R/G}{R/G}
// cast with conspire
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Lightning Bolt", playerB);
setChoice(playerA, true); // use conspire
setChoice(playerA, "Goblin Warrior Token");
setChoice(playerA, "Goblin Warrior Token");
setChoice(playerA, false); // keep targets
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Shock", playerB);
setChoice(playerA, false); // don't use conspire
setStrictChooseMode(true);
setStopAt(1, PhaseStep.END_TURN);
execute();
assertAllCommandsUsed();
assertPermanentCount(playerA, "Wort, the Raidmother", 1);
assertGraveyardCount(playerA, "Lightning Bolt", 1);
assertTapped("Raging Goblin", false);
assertLife(playerB, 20 - 3 - 3 - 2);
}
@Test
public void testWortTheRaidmotherWithConspireSpellOnce() {
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 10);
// When Wort, the Raidmother enters the battlefield, put two 1/1 red and green Goblin Warrior creature tokens onto the battlefield.
// Each red or green instant or sorcery spell you cast has conspire.
// (As you cast the spell, you may tap two untapped creatures you control that share a color with it. When you do, copy it and you may choose new targets for the copy.)
addCard(Zone.HAND, playerA, "Wort, the Raidmother");
addCard(Zone.HAND, playerA, "Burn Trail");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Wort, the Raidmother"); // {4}{R/G}{R/G}
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Burn Trail", playerB);
setChoice(playerA, true); // use Conspire from Burn Trail itself
setChoice(playerA, false); // don't use Conspire gained from Wort, the Raidmother
setStopAt(1, PhaseStep.END_TURN);
execute();
assertPermanentCount(playerA, "Wort, the Raidmother", 1);
assertLife(playerB, 20 - 3 - 3);
assertLife(playerA, 20);
assertGraveyardCount(playerA, "Burn Trail", 1);
}
@Test
public void testWortTheRaidmotherWithConspireSpellTwice() {
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 10);
addCard(Zone.BATTLEFIELD, playerA, "Raging Goblin", 2);
// When Wort, the Raidmother enters the battlefield, put two 1/1 red and green Goblin Warrior creature tokens onto the battlefield.
// Each red or green instant or sorcery spell you cast has conspire.
// (As you cast the spell, you may tap two untapped creatures you control that share a color with it. When you do, copy it and you may choose new targets for the copy.)
addCard(Zone.HAND, playerA, "Wort, the Raidmother");
addCard(Zone.HAND, playerA, "Burn Trail");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Wort, the Raidmother"); // {4}{R/G}{R/G}
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Burn Trail", playerB);
setChoice(playerA, true); // use Conspire from Burn Trail itself
setChoice(playerA, true); // use Conspire gained from Wort, the Raidmother
setStopAt(1, PhaseStep.END_TURN);
execute();
assertPermanentCount(playerA, "Wort, the Raidmother", 1);
assertLife(playerB, 20 - 3 - 3 - 3);
assertLife(playerA, 20);
assertGraveyardCount(playerA, "Burn Trail", 1);
}
@Test
public void testWortTheRaidmotherWithSakashimaOnce() {
addCard(Zone.BATTLEFIELD, playerA, "Volcanic Island", 11);
// When Wort, the Raidmother enters the battlefield, put two 1/1 red and green Goblin Warrior creature tokens onto the battlefield.
// Each red or green instant or sorcery spell you cast has conspire.
// (As you cast the spell, you may tap two untapped creatures you control that share a color with it. When you do, copy it and you may choose new targets for the copy.)
addCard(Zone.HAND, playerA, "Wort, the Raidmother");
addCard(Zone.HAND, playerA, "Sakashima the Impostor");
addCard(Zone.HAND, playerA, "Lightning Bolt");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Wort, the Raidmother"); // {4}{R/G}{R/G}
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Sakashima the Impostor"); // {2}{U}{U}
setChoice(playerA, "Wort, the Raidmother");
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Lightning Bolt", playerB);
setChoice(playerA, true); // use Conspire gained from Wort, the Raidmother
setChoice(playerA, false); // don't use Conspire gained from Sakashima the Imposter
setStopAt(1, PhaseStep.END_TURN);
execute();
assertPermanentCount(playerA, "Wort, the Raidmother", 1);
assertPermanentCount(playerA, "Sakashima the Impostor", 1);
assertLife(playerB, 20 - 3 - 3);
assertLife(playerA, 20);
assertGraveyardCount(playerA, "Lightning Bolt", 1);
}
@Test
public void testWortTheRaidmotherWithSakashimaTwice() {
addCard(Zone.BATTLEFIELD, playerA, "Volcanic Island", 11);
// When Wort, the Raidmother enters the battlefield, put two 1/1 red and green Goblin Warrior creature tokens onto the battlefield.
// Each red or green instant or sorcery spell you cast has conspire.
// (As you cast the spell, you may tap two untapped creatures you control that share a color with it. When you do, copy it and you may choose new targets for the copy.)
addCard(Zone.HAND, playerA, "Wort, the Raidmother");
addCard(Zone.HAND, playerA, "Sakashima the Impostor");
addCard(Zone.HAND, playerA, "Lightning Bolt");
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Wort, the Raidmother"); // {4}{R/G}{R/G}
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Sakashima the Impostor"); // {2}{U}{U}
setChoice(playerA, "Wort, the Raidmother");
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Lightning Bolt", playerB);
setChoice(playerA, true); // use Conspire gained from Wort, the Raidmother
setChoice(playerA, true); // use Conspire gained from Sakashima the Imposter
setStopAt(1, PhaseStep.END_TURN);
execute();
assertPermanentCount(playerA, "Wort, the Raidmother", 1);
assertPermanentCount(playerA, "Sakashima the Impostor", 1);
assertLife(playerB, 20 - 3 - 3 - 3);
assertLife(playerA, 20);
assertGraveyardCount(playerA, "Lightning Bolt", 1);
}
@Test
public void testConspire_User() {
// Burn Trail deals 3 damage to any target.
// Conspire (As you cast this spell, you may tap two untapped creatures you control that share a color with it.
// When you do, copy it and you may choose a new target for the copy.)
addCard(Zone.HAND, playerA, "Burn Trail", 1); // {3}{R}
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 4);
addCard(Zone.BATTLEFIELD, playerA, "Goblin Assailant", 2);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Burn Trail");
addTarget(playerA, playerB);
setChoice(playerA, true); // use conspire
setChoice(playerA, "Goblin Assailant^Goblin Assailant");
setChoice(playerA, false); // don't change target 1
setStrictChooseMode(true);
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertAllCommandsUsed();
assertGraveyardCount(playerA, "Burn Trail", 1);
assertLife(playerB, 20 - 3 - 3);
assertTapped("Goblin Assailant", true);
}
@Test
public void testConspire_AI_can() {
// Burn Trail deals 3 damage to any target.
// Conspire (As you cast this spell, you may tap two untapped creatures you control that share a color with it.
// When you do, copy it and you may choose a new target for the copy.)
addCard(Zone.HAND, playerA, "Burn Trail", 1); // {3}{R}
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 4);
addCard(Zone.BATTLEFIELD, playerA, "Goblin Assailant", 2);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Burn Trail");
addTarget(playerA, playerB);
//setChoice(playerA, true); // use conspire - AI must choose
//setChoice(playerA, "Goblin Assailant^Goblin Assailant"); - AI must choose
//setChoice(playerA, false); // don't change target 1 - AI must choose
//setStrictChooseMode(true); - AI must choose
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertAllCommandsUsed();
assertGraveyardCount(playerA, "Burn Trail", 1);
assertLife(playerB, 20 - 3 - 3);
assertTapped("Goblin Assailant", true);
}
@Test
public void testConspire_AI_cannot() {
// Burn Trail deals 3 damage to any target.
// Conspire (As you cast this spell, you may tap two untapped creatures you control that share a color with it.
// When you do, copy it and you may choose a new target for the copy.)
addCard(Zone.HAND, playerA, "Burn Trail", 1); // {3}{R}
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 4);
addCard(Zone.BATTLEFIELD, playerA, "Goblin Assailant", 2 - 1); // AI can't pay additional cost, must use simple mode
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Burn Trail");
addTarget(playerA, playerB);
//setChoice(playerA, true); // use conspire - AI must choose
//setChoice(playerA, "Goblin Assailant^Goblin Assailant"); - AI must choose
//setChoice(playerA, false); // don't change target 1 - AI must choose
//setStrictChooseMode(true); - AI must choose
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertAllCommandsUsed();
assertGraveyardCount(playerA, "Burn Trail", 1);
assertLife(playerB, 20 - 3); // simple cast
assertTapped("Goblin Assailant", false);
}
}
|
package com.nhpatt.androidm.activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.nhpatt.androidm.R;
public class PermissionsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permissions);
}
}
|
package net.evilcult.scenic.block;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.IWaterLoggable;
import net.minecraft.fluid.FluidState;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.pathfinding.PathType;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Objects;
/**
* Flat Block
* Scenic-Mod - net.evilcult.scenic.block.FlatBlock
*
* To allow blocks using builtin/generated models to sit flat on the ground.
*
* @author Patrick "Vaelzan" Beasley (vaelzan@evilcult.net)
* @version 1.16.5-0.1.3
* @since 2020-06-20
*/
public class FlatBlock extends Block implements IWaterLoggable {
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
protected static final VoxelShape SHAPE = Block.makeCuboidShape(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D);
// protected static final Vector3d OFFSET = new Vector3d(0d, -0.46875d, 0d);
public FlatBlock(Block.Properties properties) {
super(properties);
this.setDefaultState((this.stateContainer.getBaseState()).with(WATERLOGGED, false));
}
@SuppressWarnings("deprecation")
@Nonnull
public VoxelShape getShape(BlockState state, IBlockReader world, BlockPos pos, ISelectionContext context) {
return SHAPE;
}
@SuppressWarnings("deprecation")
public boolean allowsMovement(@Nonnull BlockState state, @Nonnull IBlockReader world, @Nonnull BlockPos position, @Nonnull PathType type) {
return type == PathType.AIR && !this.canCollide || super.allowsMovement(state, world, position, type);
}
protected boolean isValidGround(BlockState state, IBlockReader world, BlockPos position) {
return !state.getCollisionShape(world, position).project(Direction.UP).isEmpty();
}
@SuppressWarnings("deprecation")
@Override
public boolean isValidPosition(BlockState state, IWorldReader world, BlockPos position) {
BlockPos blockPos = position.down();
return this.isValidGround(world.getBlockState(blockPos), world, blockPos);
}
@Override
public boolean propagatesSkylightDown(@Nonnull BlockState state, @Nonnull IBlockReader reader, @Nonnull BlockPos position) {
return true;
}
// @SuppressWarnings("deprecation")
// @Nonnull
//// @Override
// public Vector3d getOffset(@Nonnull BlockState state, @Nonnull IBlockReader world, @Nonnull BlockPos position) {
// return OFFSET;
// }
@Nullable
@Override
public BlockState getStateForPlacement(BlockItemUseContext context) {
FluidState fluidState = context.getWorld().getFluidState(context.getPos());
boolean isWaterLogged = fluidState.isTagged(FluidTags.WATER) && fluidState.getLevel() == 8;
return Objects.requireNonNull(super.getStateForPlacement(context)).with(WATERLOGGED, isWaterLogged);
}
@SuppressWarnings("deprecation")
@Nonnull
@Override
public FluidState getFluidState(@Nonnull BlockState state) {
return state.get(WATERLOGGED) ? Fluids.WATER.getStillFluidState(false) : super.getFluidState(state);
}
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> stateBuilder) {
stateBuilder.add(WATERLOGGED);
}
@Nonnull
@SuppressWarnings("deprecation")
@Override
public BlockState updatePostPlacement(BlockState state, Direction direction, BlockState facingState, IWorld world, BlockPos position, BlockPos facing) {
if (!state.isValidPosition(world, position)) {
return Blocks.AIR.getDefaultState();
} else {
if (state.get(WATERLOGGED)) {
world.getPendingFluidTicks().scheduleTick(position, Fluids.WATER, Fluids.WATER.getTickRate(world));
}
return super.updatePostPlacement(state, direction, facingState, world, position, facing);
}
}
}
|
/*
* Decompiled with CFR 0.150.
*/
package me.wintware.client.module.visual;
import me.wintware.client.event.EventTarget;
import me.wintware.client.event.impl.Event3D;
import me.wintware.client.event.impl.EventPreMotionUpdate;
import me.wintware.client.module.Category;
import me.wintware.client.module.Module;
public class Chams
extends Module {
public Chams() {
super("Chams", Category.Visuals);
}
@EventTarget
public void onUpdate(EventPreMotionUpdate event) {
}
@EventTarget
public void onEvent(Event3D eventRender3D) {
}
}
|
/*
*
* 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.royale.compiler.internal.codegen.as;
import org.apache.royale.compiler.codegen.as.IASEmitter;
import org.apache.royale.compiler.tree.ASTNodeID;
import org.apache.royale.compiler.tree.as.IASNode;
import org.apache.royale.compiler.tree.as.IContainerNode;
import org.apache.royale.compiler.tree.as.IContainerNode.ContainerType;
import org.apache.royale.compiler.visitor.IASNodeStrategy;
/**
* A concrete implementation of the {@link IASNodeStrategy} that allows
* {@link IASNode} processing before the current node handler.
*
* @author Michael Schmalle
*/
public class ASBeforeNodeStrategy implements IASNodeStrategy
{
private final IASEmitter emitter;
public ASBeforeNodeStrategy(IASEmitter emitter)
{
this.emitter = emitter;
}
@Override
public void handle(IASNode node)
{
if (node.getNodeID() == ASTNodeID.BlockID)
{
IASNode parent = node.getParent();
IContainerNode container = (IContainerNode) node;
ContainerType type = container.getContainerType();
if (parent.getNodeID() != ASTNodeID.LabledStatementID)
{
if (node.getChildCount() != 0)
emitter.indentPush();
}
// switch cases are SYNTHESIZED
if (type != ContainerType.IMPLICIT
&& type != ContainerType.SYNTHESIZED)
{
emitter.emitBlockOpen(container);
}
if (parent.getNodeID() != ASTNodeID.LabledStatementID)
{
emitter.writeNewline();
}
}
}
}
|
/* 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.flowable.engine.impl.persistence.entity;
import java.util.List;
import java.util.Map;
import org.flowable.engine.common.impl.persistence.entity.data.DataManager;
import org.flowable.engine.history.HistoricDetail;
import org.flowable.engine.impl.HistoricDetailQueryImpl;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.history.HistoryLevel;
import org.flowable.engine.impl.persistence.entity.data.HistoricDetailDataManager;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class HistoricDetailEntityManagerImpl extends AbstractEntityManager<HistoricDetailEntity> implements HistoricDetailEntityManager {
protected HistoricDetailDataManager historicDetailDataManager;
public HistoricDetailEntityManagerImpl(ProcessEngineConfigurationImpl processEngineConfiguration, HistoricDetailDataManager historicDetailDataManager) {
super(processEngineConfiguration);
this.historicDetailDataManager = historicDetailDataManager;
}
@Override
protected DataManager<HistoricDetailEntity> getDataManager() {
return historicDetailDataManager;
}
@Override
public HistoricFormPropertyEntity insertHistoricFormPropertyEntity(ExecutionEntity execution,
String propertyId, String propertyValue, String taskId) {
HistoricFormPropertyEntity historicFormPropertyEntity = historicDetailDataManager.createHistoricFormProperty();
historicFormPropertyEntity.setProcessInstanceId(execution.getProcessInstanceId());
historicFormPropertyEntity.setExecutionId(execution.getId());
historicFormPropertyEntity.setTaskId(taskId);
historicFormPropertyEntity.setPropertyId(propertyId);
historicFormPropertyEntity.setPropertyValue(propertyValue);
historicFormPropertyEntity.setTime(getClock().getCurrentTime());
HistoricActivityInstanceEntity historicActivityInstance = getHistoryManager().findActivityInstance(execution, true, false);
if (historicActivityInstance != null) {
historicFormPropertyEntity.setActivityInstanceId(historicActivityInstance.getId());
}
insert(historicFormPropertyEntity);
return historicFormPropertyEntity;
}
@Override
public HistoricDetailVariableInstanceUpdateEntity copyAndInsertHistoricDetailVariableInstanceUpdateEntity(VariableInstanceEntity variableInstance) {
HistoricDetailVariableInstanceUpdateEntity historicVariableUpdate = historicDetailDataManager.createHistoricDetailVariableInstanceUpdate();
historicVariableUpdate.setProcessInstanceId(variableInstance.getProcessInstanceId());
historicVariableUpdate.setExecutionId(variableInstance.getExecutionId());
historicVariableUpdate.setTaskId(variableInstance.getTaskId());
historicVariableUpdate.setTime(getClock().getCurrentTime());
historicVariableUpdate.setRevision(variableInstance.getRevision());
historicVariableUpdate.setName(variableInstance.getName());
historicVariableUpdate.setVariableType(variableInstance.getType());
historicVariableUpdate.setTextValue(variableInstance.getTextValue());
historicVariableUpdate.setTextValue2(variableInstance.getTextValue2());
historicVariableUpdate.setDoubleValue(variableInstance.getDoubleValue());
historicVariableUpdate.setLongValue(variableInstance.getLongValue());
if (variableInstance.getBytes() != null) {
historicVariableUpdate.setBytes(variableInstance.getBytes());
}
insert(historicVariableUpdate);
return historicVariableUpdate;
}
@Override
public void delete(HistoricDetailEntity entity, boolean fireDeleteEvent) {
super.delete(entity, fireDeleteEvent);
if (entity instanceof HistoricDetailVariableInstanceUpdateEntity) {
HistoricDetailVariableInstanceUpdateEntity historicDetailVariableInstanceUpdateEntity = ((HistoricDetailVariableInstanceUpdateEntity) entity);
if (historicDetailVariableInstanceUpdateEntity.getByteArrayRef() != null) {
historicDetailVariableInstanceUpdateEntity.getByteArrayRef().delete();
}
}
}
@Override
public void deleteHistoricDetailsByProcessInstanceId(String historicProcessInstanceId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.AUDIT)) {
List<HistoricDetailEntity> historicDetails = historicDetailDataManager.findHistoricDetailsByProcessInstanceId(historicProcessInstanceId);
for (HistoricDetailEntity historicDetail : historicDetails) {
delete(historicDetail);
}
}
}
@Override
public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) {
return historicDetailDataManager.findHistoricDetailCountByQueryCriteria(historicVariableUpdateQuery);
}
@Override
public List<HistoricDetail> findHistoricDetailsByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) {
return historicDetailDataManager.findHistoricDetailsByQueryCriteria(historicVariableUpdateQuery);
}
@Override
public void deleteHistoricDetailsByTaskId(String taskId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.FULL)) {
List<HistoricDetailEntity> details = historicDetailDataManager.findHistoricDetailsByTaskId(taskId);
for (HistoricDetail detail : details) {
delete((HistoricDetailEntity) detail);
}
}
}
@Override
public List<HistoricDetail> findHistoricDetailsByNativeQuery(Map<String, Object> parameterMap) {
return historicDetailDataManager.findHistoricDetailsByNativeQuery(parameterMap);
}
@Override
public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) {
return historicDetailDataManager.findHistoricDetailCountByNativeQuery(parameterMap);
}
public HistoricDetailDataManager getHistoricDetailDataManager() {
return historicDetailDataManager;
}
public void setHistoricDetailDataManager(HistoricDetailDataManager historicDetailDataManager) {
this.historicDetailDataManager = historicDetailDataManager;
}
}
|
/****************************************************************
* 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.james.mailbox.model;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import org.apache.commons.text.RandomStringGenerator;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
public class AttachmentId {
public static final RandomStringGenerator RANDOM_STRING_GENERATOR = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
public static AttachmentId from(BlobId blobId) {
return new AttachmentId(blobId.asString());
}
public static AttachmentId random() {
return new AttachmentId(RANDOM_STRING_GENERATOR.generate(20));
}
public static AttachmentId from(String id) {
Preconditions.checkNotNull(id);
Preconditions.checkArgument(!id.isEmpty());
return new AttachmentId(id);
}
private final String id;
private AttachmentId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public UUID asUUID() {
return UUID.nameUUIDFromBytes(id.getBytes(StandardCharsets.UTF_8));
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AttachmentId) {
AttachmentId other = (AttachmentId) obj;
return Objects.equal(id, other.id);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return MoreObjects
.toStringHelper(this)
.add("id", id)
.toString();
}
}
|
// Pecan 1.0 operators. Free and open source. See licence.txt.
package pecan;
/* Op constants represent parsing expression operators, and are used to classify
nodes. */
public enum Op {
Error, // Parse error, with message in note field
Temp, // Temporary node used during parsing
List, // Linked list of rules
Empty, // Empty linked list
Rule, // Definition, name = rhs
Id, // Identifier, with cross-reference to its definition
Or, // Choice, x / y, right associative
And, // Sequence, x y, right associative
Opt, // Optional, x?
Any, // Zero or more, x*
Some, // One or more, x+
See, // Lookahead, [e]
Has, // Positive lookahead, e&
Not, // Negative lookahead, e!
Mark, // Error annotation, x #e
Text, // Character sequence, "abc"
Set, // Choice of characters, 'abc'
Split, // Lookahead for text less than or equal to string, <...>
Char, // Single character, "a" or 'a'
Point, // Any Unicode character (code point)
Success, // Always succeed, ""
Fail, // Always fail, ''
Eot, // End of text or tokens, <>
Range, // Character range, 'x..y'
Cat, // Unicode category, e.g. Lu
Tag, // Match a type of token.
Drop, // Drop unused matched characters, e.g. @ or @3
Act; // Carry out an action, e.g. @2add
// No testing.
public static void main(String[] args) {
System.out.println("Op class OK");
}
}
|
package Practica3.principalpack;
import java.io.*;
import java.net.*;
public class MetPrincipal {
public String principal(String host) {
try {
Socket socket = new Socket(host, 80);
InputStream input = socket.getInputStream();
return input + "";
} catch (Exception e) {
System.out.println("Error " + e.getMessage());
}
return null;
}
}
|
package com.hy.micro.service.dingding.utils;
import org.springframework.beans.BeanUtils;
import com.hy.micro.service.dingding.dto.OrderDTO;
import com.hy.micro.service.dingding.entity.OrderMaster;
import java.util.List;
import java.util.stream.Collectors;
/**
* Convert master order to DTO order
*
* @Author: Eddie.Wei
* @Date: 2018-10-08
* @github: https://github.com/weixuan2008
*/
public class ConvertOrderMaster2OrderDTO {
public static OrderDTO convert(OrderMaster orderMaster) {
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster, orderDTO);
return orderDTO;
}
public static List<OrderDTO> convert(List<OrderMaster> orderMasterList) {
return orderMasterList.stream().map(e -> convert(e)).collect(Collectors.toList());
}
}
|
/*
* Copyright 2012-present Facebook, 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.facebook.buck.android;
import static com.facebook.buck.rules.BuildableProperties.Kind.ANDROID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeBuildContext;
import com.facebook.buck.rules.FakeBuildableContext;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.MoreAsserts;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Optional;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class NdkLibraryTest {
private ExecutionContext executionContext;
private String ndkBuildCommand;
private ProjectFilesystem projectFilesystem;
@Before
public void setUp() {
AssumeAndroidPlatform.assumeNdkIsAvailable();
projectFilesystem = new ProjectFilesystem(Paths.get(".").toAbsolutePath());
AndroidDirectoryResolver resolver = new DefaultAndroidDirectoryResolver(
projectFilesystem.getRootPath().getFileSystem(),
ImmutableMap.copyOf(System.getenv()),
Optional.<String>absent(),
Optional.<String>absent());
AndroidPlatformTarget androidPlatformTarget = AndroidPlatformTarget.getDefaultPlatformTarget(
resolver,
Optional.<Path>absent());
executionContext = TestExecutionContext.newBuilder()
.setAndroidPlatformTargetSupplier(Suppliers.ofInstance(androidPlatformTarget))
.build();
ndkBuildCommand = new ExecutableFinder().getOptionalExecutable(
Paths.get("ndk-build"),
resolver.getNdkOrAbsent().get()).get().toAbsolutePath().toString();
}
@Test
public void testSimpleNdkLibraryRule() throws Exception {
BuildRuleResolver ruleResolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
BuildContext context = FakeBuildContext.NOOP_CONTEXT;
String basePath = "java/src/com/facebook/base";
BuildTarget target = BuildTargetFactory.newInstance(String.format("//%s:base", basePath));
NdkLibrary ndkLibrary =
(NdkLibrary) new NdkLibraryBuilder(target)
.setFlags(ImmutableList.of("flag1", "flag2"))
.setIsAsset(true)
.build(ruleResolver, projectFilesystem);
assertEquals("ndk_library", ndkLibrary.getType());
assertTrue(ndkLibrary.getProperties().is(ANDROID));
assertTrue(ndkLibrary.isAsset());
assertEquals(
projectFilesystem.getBuckPaths().getGenDir().resolve(basePath).resolve("__libbase"),
ndkLibrary.getLibraryPath());
List<Step> steps = ndkLibrary.getBuildSteps(context, new FakeBuildableContext());
String libbase =
projectFilesystem.getBuckPaths().getScratchDir().resolve(basePath).resolve("__libbase")
.toString();
MoreAsserts.assertShellCommands(
"ndk_library() should invoke ndk-build on the given path with some -j value",
ImmutableList.of(
String.format(
"%s -j %d -C %s flag1 flag2 " +
"APP_PROJECT_PATH=%s " +
"APP_BUILD_SCRIPT=%s " +
"NDK_OUT=%s " +
"NDK_LIBS_OUT=%s " +
"BUCK_PROJECT_DIR=../../../../.. " +
"host-echo-build-step=%s " +
"--silent",
ndkBuildCommand,
Runtime.getRuntime().availableProcessors(),
Paths.get(basePath).toString(),
/* APP_PROJECT_PATH */ projectFilesystem.resolve(libbase) + File.separator,
/* APP_BUILD_SCRIPT */ projectFilesystem.resolve(
NdkLibraryDescription.getGeneratedMakefilePath(target, projectFilesystem)),
/* NDK_OUT */ projectFilesystem.resolve(libbase) + File.separator,
/* NDK_LIBS_OUT */ projectFilesystem.resolve(Paths.get(libbase, "libs")),
/* host-echo-build-step */ Platform.detect() == Platform.WINDOWS ? "@REM" : "@#")
),
steps.subList(3, 4),
executionContext);
}
}
|
package AST;
import AST.Visitor.Visitor;
import java_cup.runtime.ComplexSymbolFactory.Location;
public class True extends Exp {
public True(Location pos) {
super(pos);
}
public void accept(Visitor v) {
v.visit(this);
}
}
|
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */
package io.annot8.common.data.tuple;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class Tuple1Test {
@Test
void getA() {
Tuple1<String> t = new Tuple1<>("a");
assertEquals("a", t.getA());
}
@Test
void append() {
Tuple1<String> t = new Tuple1<>("a");
Tuple2<String, String> t2 = t.append("b");
assertEquals(new Tuple2<>("a", "b"), t2);
}
@Test
void hashEqualString() {
Tuple1<String> a = new Tuple1<>("a");
Tuple1<String> b = new Tuple1<>("b");
Tuple1<String> a2 = new Tuple1<>("a");
assertNotEquals(a, b);
assertNotEquals(a.hashCode(), b.hashCode());
assertNotEquals(a.toString(), b.toString());
assertEquals(a, a2);
assertEquals(a.hashCode(), a2.hashCode());
assertEquals(a.toString(), a2.toString());
}
}
|
package com.zcc.smarthome.activity;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OSUtils;
public class BaseActivity extends AppCompatActivity {
public ImmersionBar mImmersionBar;
private static final String NAVIGATIONBAR_IS_MIN = "navigationbar_is_min";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//初始化沉浸式
initImmersionBar();
//解决华为emui3.0与3.1手机手动隐藏底部导航栏时,导航栏背景色未被隐藏的问题
if (OSUtils.isEMUI3_1()) {
//第一种
getContentResolver().registerContentObserver(Settings.System.getUriFor
(NAVIGATIONBAR_IS_MIN), true, mNavigationStatusObserver);
}
}
private void initImmersionBar() {
//在BaseActivity里初始化
mImmersionBar = ImmersionBar.with(this);
mImmersionBar.init();
}
@Override
protected void onDestroy() {
super.onDestroy();
mImmersionBar.destroy(); //在BaseActivity里销毁
}
private ContentObserver mNavigationStatusObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
int navigationBarIsMin = Settings.System.getInt(getContentResolver(),
NAVIGATIONBAR_IS_MIN, 0);
if (navigationBarIsMin == 1) {
//导航键隐藏了
mImmersionBar.transparentNavigationBar().init();
} else {
//导航键显示了
mImmersionBar.navigationBarColor(android.R.color.black) //隐藏前导航栏的颜色
.fullScreen(false)
.init();
}
}
};
}
|
package ltd.newbee.mall.dao;
import ltd.newbee.mall.entity.NewBeeMallOrderItem;
import ltd.newbee.mall.util.PageQueryUtil;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NewBeeMallOrderItemMapper {
int deleteByPrimaryKey(Long orderItemId);
int insert(NewBeeMallOrderItem record);
int insertSelective(NewBeeMallOrderItem record);
NewBeeMallOrderItem selectByPrimaryKey(Long orderItemId);
/**
* 根据订单id获取订单项列表
*
* @param orderId
* @return
*/
List<NewBeeMallOrderItem> selectByOrderId(Long orderId);
/**
* 根据订单ids获取订单项列表
*
* @param orderIds
* @return
*/
List<NewBeeMallOrderItem> selectByOrderIds(@Param("orderIds") List<Long> orderIds);
/**
* 批量insert订单项数据
*
* @param orderItems
* @return
*/
int insertBatch(@Param("orderItems") List<NewBeeMallOrderItem> orderItems);
int updateByPrimaryKeySelective(NewBeeMallOrderItem record);
int updateByPrimaryKey(NewBeeMallOrderItem record);
int getTotalNewBeeMallOrderItems(PageQueryUtil pageUtil);
}
|
/*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gigaspaces.server;
/**
* @author Niv
* @since 12.0
*/
public abstract class SpaceCustomComponent {
public abstract String getSpaceComponentKey();
public abstract String getServiceDetailAttributeName();
public abstract Object getServiceDetailAttributeValue();
}
|
package com.k8swatcher;
import javax.enterprise.context.Dependent;
import io.fabric8.kubernetes.api.model.rbac.RoleBinding;
@Dependent
public class RoleBindingWatcher extends ResourceWatcher<RoleBinding> {
public RoleBindingWatcher(WatchConfig config, NotificationPublisher notificationPublisher) {
super(config, notificationPublisher);
}
@Override
public void eventReceived(Action action, RoleBinding resource) {
super.eventReceived(action, resource);
}
}
|
package hr.vkeglevic.doomsdayterminal.ui.dialogs;
import com.googlecode.lanterna.gui2.AnimatedLabel;
import com.googlecode.lanterna.gui2.Borders;
import static com.googlecode.lanterna.gui2.Borders.*;
import com.googlecode.lanterna.gui2.Button;
import com.googlecode.lanterna.gui2.Direction;
import com.googlecode.lanterna.gui2.EmptySpace;
import com.googlecode.lanterna.gui2.Label;
import com.googlecode.lanterna.gui2.LinearLayout;
import static com.googlecode.lanterna.gui2.LinearLayout.*;
import static com.googlecode.lanterna.gui2.LinearLayout.Alignment.*;
import com.googlecode.lanterna.gui2.Panel;
import com.googlecode.lanterna.gui2.ProgressBar;
import com.googlecode.lanterna.gui2.WindowBasedTextGUI;
import com.googlecode.lanterna.gui2.dialogs.DialogWindow;
import hr.vkeglevic.doomsdayterminal.model.events.WorkProgressEvent;
import java.util.Collections;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang3.StringUtils;
import static org.apache.commons.lang3.StringUtils.*;
/**
*
* @author vanja
*/
public class ProgressDialog extends DialogWindow implements Observer {
private static final int progressBarLength = 30;
private final Button abortBTN;
private Optional<ProgressBar> determinateProgressBar = Optional.empty();
private Optional<Label> progressMessageLabel = Optional.empty();
private ProgressDialog(String title, String text, boolean determinateProgress) {
super(title);
Panel panel = new Panel(new LinearLayout(Direction.VERTICAL));
panel.addComponent(new EmptySpace(), createLayoutData(Center));
panel.addComponent(new Label(text), createLayoutData(Center));
if (determinateProgress) {
ProgressBar progressBar = new ProgressBar();
progressBar.setPreferredWidth(progressBarLength);
panel.addComponent(progressBar.withBorder(singleLine()), createLayoutData(Center));
determinateProgressBar = Optional.of(progressBar);
Label progressMsg = new Label("");
panel.addComponent(progressMsg, createLayoutData(Center));
progressMessageLabel = Optional.of(progressMsg);
} else {
panel.addComponent(createSwingLikeProgressBar().withBorder(singleLine()), createLayoutData(Center));
}
abortBTN = new Button("Abort");
panel.addComponent(abortBTN.withBorder(Borders.singleLineBevel()), createLayoutData(Center));
panel.addComponent(new EmptySpace(), createLayoutData(Center));
setComponent(panel);
}
private AnimatedLabel createSwingLikeProgressBar() {
// first we'll generate all the frames
final String movingBar = "▉▉▉▉▉▉▉";
final String empty = " ";
List<String> frames = IntStream.range(0, progressBarLength)
.mapToObj((index) -> repeat(empty, index)
+ movingBar
+ repeat(empty, progressBarLength - movingBar.length() - index)
).collect(Collectors.toList());
// now we add them first from left to right, then the opposite
AnimatedLabel animatedLabel = new AnimatedLabel(frames.get(0));
IntStream.range(1, frames.size())
.forEach((i) -> animatedLabel.addFrame(frames.get(i)));
IntStream.range(1, frames.size() - 2)
.boxed()
.sorted(Collections.reverseOrder())
.forEach((i) -> animatedLabel.addFrame(frames.get(i)));
animatedLabel.startAnimation(50);
return animatedLabel;
}
@Override
public Object showDialog(WindowBasedTextGUI textGUI) {
showDialog(textGUI, true);
return null;
}
public void showDialog(WindowBasedTextGUI textGUI, boolean blockUntilClosed) {
textGUI.addWindow(this);
if (blockUntilClosed) {
waitUntilClosed();
}
}
public void addAbortListener(Button.Listener listener) {
abortBTN.addListener(listener);
}
public static ProgressDialog createDialog(
String title,
String text,
boolean determinateProgress,
Button.Listener abortListener
) {
final ProgressDialog progressDialog = new ProgressDialog(title, text, determinateProgress);
final Button.Listener closeDialog = (button) -> progressDialog.close();
if (abortListener == null) {
progressDialog.addAbortListener(closeDialog);
} else {
progressDialog.addAbortListener(abortListener);
}
return progressDialog;
}
private void update(WorkProgressEvent event) {
determinateProgressBar.ifPresent((ProgressBar bar) -> {
bar.setMin(0);
long totalWork = event.getTotalWork();
long currentlyDoneWork = event.getCurrentlyDoneWork();
double percentageDone = ((double) currentlyDoneWork / totalWork) * 100;
bar.setMax(100);
bar.setValue((int) percentageDone);
if (StringUtils.isNotEmpty(event.getWorkProgressMessage())) {
progressMessageLabel.get().setText(event.getWorkProgressMessage());
}
});
}
@Override
public void update(Observable o, Object event) {
if (event instanceof WorkProgressEvent) {
update((WorkProgressEvent) event);
}
}
}
|
package com.atguigu.gmall.oms.controller;
import java.util.Arrays;
import java.util.Map;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
import com.atguigu.core.bean.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.atguigu.gmall.oms.entity.OrderOperateHistoryEntity;
import com.atguigu.gmall.oms.service.OrderOperateHistoryService;
/**
* 订单操作历史记录
*
* @author lixianfeng
* @email lxf@atguigu.com
* @date 2020-03-10 09:40:22
*/
@Api(tags = "订单操作历史记录 管理")
@RestController
@RequestMapping("oms/orderoperatehistory")
public class OrderOperateHistoryController {
@Autowired
private OrderOperateHistoryService orderOperateHistoryService;
/**
* 列表
*/
@ApiOperation("分页查询(排序)")
@GetMapping("/list")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:list')")
public Resp<PageVo> list(QueryCondition queryCondition) {
PageVo page = orderOperateHistoryService.queryPage(queryCondition);
return Resp.ok(page);
}
/**
* 信息
*/
@ApiOperation("详情查询")
@GetMapping("/info/{id}")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:info')")
public Resp<OrderOperateHistoryEntity> info(@PathVariable("id") Long id){
OrderOperateHistoryEntity orderOperateHistory = orderOperateHistoryService.getById(id);
return Resp.ok(orderOperateHistory);
}
/**
* 保存
*/
@ApiOperation("保存")
@PostMapping("/save")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:save')")
public Resp<Object> save(@RequestBody OrderOperateHistoryEntity orderOperateHistory){
orderOperateHistoryService.save(orderOperateHistory);
return Resp.ok(null);
}
/**
* 修改
*/
@ApiOperation("修改")
@PostMapping("/update")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:update')")
public Resp<Object> update(@RequestBody OrderOperateHistoryEntity orderOperateHistory){
orderOperateHistoryService.updateById(orderOperateHistory);
return Resp.ok(null);
}
/**
* 删除
*/
@ApiOperation("删除")
@PostMapping("/delete")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:delete')")
public Resp<Object> delete(@RequestBody Long[] ids){
orderOperateHistoryService.removeByIds(Arrays.asList(ids));
return Resp.ok(null);
}
}
|
package com.allever.social.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.allever.social.BaseActivity;
import com.allever.social.R;
import com.allever.social.pojo.ShareRankItem;
import com.allever.social.pojo.WebCollectionItem;
import java.util.List;
/**
* Created by XM on 2016/7/30.
*/
public class WebCollectionItemBaseAdapter extends BaseAdapter {
private List<WebCollectionItem> list_webcollection_item;
private LayoutInflater inflater;
private Context context;
public WebCollectionItemBaseAdapter(Context context,List<WebCollectionItem> list_webcollection_item){
this.context = context;
this.list_webcollection_item = list_webcollection_item;
inflater = (LayoutInflater.from(context));
}
@Override
public View getView(int position, final View convertView, ViewGroup parent) {
WebCollectionItem webCollectionItem = list_webcollection_item.get(position);
View view;
ViewHolder viewHolder;
if (convertView == null){
view = inflater.inflate(R.layout.webcollection_item,parent,false);
viewHolder = new ViewHolder();
viewHolder.tv_title = (TextView)view.findViewById(R.id.id_webcollection_item_tv_title);
viewHolder.tv_url = (TextView)view.findViewById(R.id.id_webcollection_item_tv_url);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ViewHolder)view.getTag();
}
viewHolder.tv_url.setText(webCollectionItem.getUrl());
viewHolder.tv_title.setText(webCollectionItem.getTitle());
return view;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public Object getItem(int i) {
return list_webcollection_item.get(i);
}
@Override
public int getCount() {
return list_webcollection_item.size();
}
class ViewHolder{
TextView tv_title;
TextView tv_url;
}
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fescar.core.rpc;
/**
* The enum Client type.
*/
public enum ClientType {
/**
* The Tm.
*/
// Transaction Manager client
TM,
/**
* The Rm.
*/
// Resource Manager client
RM;
/**
* Get client type.
*
* @param ordinal the ordinal
* @return the client type
*/
public static ClientType get(byte ordinal) {
return get((int) ordinal);
}
/**
* Get client type.
*
* @param ordinal the ordinal
* @return the client type
*/
public static ClientType get(int ordinal) {
for (ClientType clientType : ClientType.values()) {
if (clientType.ordinal() == ordinal) {
return clientType;
}
}
throw new IllegalArgumentException("Unknown ClientType[" + ordinal + "]");
}
}
|
/*
* Copyright 2014-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 com.amazonaws.services.kinesisvideo.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisvideo-2017-09-30/UpdateDataRetention" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDataRetentionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateDataRetentionResult == false)
return false;
UpdateDataRetentionResult other = (UpdateDataRetentionResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public UpdateDataRetentionResult clone() {
try {
return (UpdateDataRetentionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
package mobi.hsz.idea.gitignore.completion;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import mobi.hsz.idea.gitignore.file.type.kind.GitFileType;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
public class CompletionTest extends LightPlatformCodeInsightFixtureTestCase {
public void testSimple() {
myFixture.getTempDirFixture().createFile("fileName.txt");
doTest("fileN<caret>", "fileName.txt<caret>");
}
public void testCurrentDirectoryAlias() throws IOException {
myFixture.getTempDirFixture().createFile("fileName.txt");
doTest("./fileN<caret>", "./fileName.txt<caret>");
}
public void testNestedDirectory() throws IOException {
myFixture.getTempDirFixture().findOrCreateDir("dir").createChildData(this, "fileName.txt");
doTest("dir/fileN<caret>", "dir/fileName.txt<caret>");
}
public void testInHiddenDirectory() throws IOException {
myFixture.getTempDirFixture().findOrCreateDir(".hidden").createChildData(this, "fileName.txt");
doTest(".hidden/fileN<caret>", ".hidden/fileName.txt<caret>");
}
public void testInGlobDirectory() throws IOException {
myFixture.getTempDirFixture().findOrCreateDir("glob1").createChildData(this, "fileName1.txt");
myFixture.getTempDirFixture().findOrCreateDir("glob2").createChildData(this, "fileName2.txt");
doTestVariants("*/fileN<caret>", "fileName1.txt", "fileName2.txt");
}
public void testNegation() throws IOException {
myFixture.getTempDirFixture().createFile("fileName.txt");
doTest("!fileNa<caret>", "!fileName.txt<caret>");
}
private void doTest(@NotNull String beforeText, @NotNull String afterText) {
myFixture.configureByText(GitFileType.INSTANCE, beforeText);
myFixture.completeBasic();
myFixture.checkResult(afterText);
}
private void doTestVariants(@NotNull String beforeText, String... variants) {
myFixture.configureByText(GitFileType.INSTANCE, beforeText);
myFixture.completeBasic();
assertContainsElements(myFixture.getLookupElementStrings(), variants);
}
}
|
/* SPDX-License-Identifier: Apache 2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.adapters.eventbus.topic.kafka;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.WakeupException;
import org.odpi.openmetadata.frameworks.connectors.ffdc.ConnectorCheckedException;
import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ExecutionException;
/**
* KafkaOpenMetadataEventProducer manages the sending of events on Apache Kafka. This is done through called to
* the Kafka Producer interface.
*
* Kafka is not always running. When this occurs, the call to publish events hangs and this is disruptive to the
* rest of the server. So the role of this class is to manage the sending of events in a separate thread
* and manage the logging of errors to alert the operations team that Kafka needs restarting.
*/
public class KafkaOpenMetadataEventProducer implements Runnable
{
private volatile List<String> sendBuffer = new ArrayList<>();
private static final Logger log = LoggerFactory.getLogger(KafkaOpenMetadataEventProducer.class);
private static final String defaultThreadName = "KafkaProducer for topic ";
private volatile boolean running = true;
private OMRSAuditLog auditLog;
private String listenerThreadName;
private String topicName;
private int sleepTime = 1000;
private static final long recoverySleepTimeSec = 10L;
private String localServerId;
private Properties producerProperties;
private Producer<String, String> producer;
private KafkaOpenMetadataTopicConnector connector;
private long messageSendCount = 0;
/**
*
* Constructor for the event consumer.
*
* @param topicName name of the topic to listen on.
* @param localServerId identifier to enable receiver to identify that an event came from this server.
* @param producerProperties properties for the consumer.
* @param connector connector holding the inbound listeners.
* @param auditLog audit log for this component.
*/
KafkaOpenMetadataEventProducer(String topicName,
String localServerId,
Properties producerProperties,
KafkaOpenMetadataTopicConnector connector,
OMRSAuditLog auditLog)
{
this.auditLog = auditLog;
this.topicName = topicName;
this.localServerId = localServerId;
this.connector = connector;
this.producerProperties = producerProperties;
this.listenerThreadName = defaultThreadName + topicName;
final String actionDescription = "new producer";
KafkaOpenMetadataTopicConnectorAuditCode auditCode;
auditCode = KafkaOpenMetadataTopicConnectorAuditCode.SERVICE_PRODUCER_PROPERTIES;
auditLog.logRecord(actionDescription,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(Integer.toString(producerProperties.size()), topicName),
producerProperties.toString(),
auditCode.getSystemAction(),
auditCode.getUserAction());
}
/**
* Sends the supplied event to the topic. It retries if Kafka is not responding.
*
* @param event object containing the event properties.
* @throws ConnectorCheckedException the connector is not able to communicate with the event bus
*/
private void publishEvent(String event) throws ConnectorCheckedException
{
final String methodName = "publishEvent";
boolean eventSent = false;
long eventRetryCount = 0;
while (!eventSent)
{
try
{
log.debug("Sending message {0}" + event);
ProducerRecord<String, String> record = new ProducerRecord<>(topicName, localServerId, event);
producer.send(record).get();
eventSent = true;
messageSendCount++;
}
catch (ExecutionException error)
{
/*
* This may be a simple timeout or something else more
*/
log.debug("Kafka had trouble sending event: " + event + "exception message is " + error.getMessage());
if (eventRetryCount == 10)
{
eventRetryCount = 0;
}
else
{
if (eventRetryCount == 0)
{
KafkaOpenMetadataTopicConnectorAuditCode auditCode;
auditCode = KafkaOpenMetadataTopicConnectorAuditCode.EVENT_SEND_IN_ERROR_LOOP;
auditLog.logRecord(methodName,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(topicName,
Long.toString(messageSendCount),
Long.toString(this.getSendBufferSize()),
error.getMessage()),
null,
auditCode.getSystemAction(),
auditCode.getUserAction());
}
eventRetryCount++;
}
}
catch (WakeupException error)
{
log.error("Wake up for shut down " + error.toString());
}
catch (Throwable error)
{
log.error("Exception in sendEvent " + error.toString());
KafkaOpenMetadataTopicConnectorErrorCode errorCode = KafkaOpenMetadataTopicConnectorErrorCode.ERROR_SENDING_EVENT;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(error.getClass().getName(),
topicName,
error.getMessage());
throw new ConnectorCheckedException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction(),
error);
}
finally
{
/*
* Producers have a thread and an in memory buffer
*/
producer.flush();
}
}
}
/**
* This is the method that provides the behaviour of the thread.
*/
@Override
public void run()
{
final String actionDescription = "run";
KafkaOpenMetadataTopicConnectorAuditCode auditCode = KafkaOpenMetadataTopicConnectorAuditCode.KAFKA_PRODUCER_START;
auditLog.logRecord(listenerThreadName,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(topicName, Integer.toString(sendBuffer.size())),
this.producerProperties.toString(),
auditCode.getSystemAction(),
auditCode.getUserAction());
this.producer = new KafkaProducer<>(producerProperties);
while (isRunning())
{
try
{
String bufferedEvent = this.getEvent();
/*
* If there are no events waiting then sleep
*/
if (bufferedEvent == null)
{
Thread.sleep(sleepTime);
}
else
{
/*
* Send all waiting events
*/
while (bufferedEvent != null)
{
publishEvent(bufferedEvent);
bufferedEvent = this.getEvent();
}
}
}
catch (InterruptedException error)
{
log.info("Woken up from sleep " + error.getMessage());
}
catch (Throwable error)
{
log.error("Bad exception from sending events " + error.getMessage());
this.recoverAfterError();
}
}
this.producer.close();
this.producer = null;
auditCode = KafkaOpenMetadataTopicConnectorAuditCode.KAFKA_PRODUCER_SHUTDOWN;
auditLog.logRecord(listenerThreadName,
auditCode.getLogMessageId(),
auditCode.getSeverity(),
auditCode.getFormattedLogMessage(topicName, Integer.toString(getSendBufferSize()), Long.toString(messageSendCount)),
this.producerProperties.toString(),
auditCode.getSystemAction(),
auditCode.getUserAction());
}
/**
* Supports putting events to the in memory OMRS Topic
*
* @param newEvent event to publish
*/
private synchronized void putEvent(String newEvent)
{
sendBuffer.add(newEvent);
}
/**
* Returns the size of the send buffer
*/
private synchronized int getSendBufferSize()
{
return sendBuffer.size();
}
/**
* Returns all of the events found on the in memory OMRS Topic.
*
* @return list of received events.
*/
private synchronized String getEvent()
{
if (sendBuffer.isEmpty())
{
return null;
}
return sendBuffer.remove(0);
}
/**
* Sends the supplied event to the topic.
*
* @param event OMRSEvent object containing the event properties.
*/
public void sendEvent(String event)
{
this.putEvent(event);
}
/**
* Give time for an error to clear.
*/
protected void recoverAfterError()
{
log.info(String.format("Waiting %s seconds to recover", recoverySleepTimeSec));
try
{
Thread.sleep(recoverySleepTimeSec * 1000L);
}
catch (InterruptedException e1)
{
log.debug("Interrupted while recovering", e1);
}
}
/**
* Normal shutdown
*/
public void safeCloseProducer()
{
stopRunning();
}
/**
* Should the thread keep looping.
*
* @return boolean
*/
private synchronized boolean isRunning()
{
return running;
}
/**
* Flip the switch to stop the thread.
*/
private synchronized void stopRunning()
{
running = false;
}
}
|
/*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.codec.impl;
import com.codahale.metrics.Metric;
import com.google.common.collect.ImmutableSet;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.Ethernet;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.cluster.RoleInfo;
import org.onosproject.codec.CodecService;
import org.onosproject.codec.JsonCodec;
import org.onosproject.core.Application;
import org.onosproject.core.ApplicationId;
import org.onosproject.incubator.net.dpi.DpiStatInfo;
import org.onosproject.incubator.net.dpi.DpiStatInfoCodec;
import org.onosproject.incubator.net.dpi.DpiStatistics;
import org.onosproject.incubator.net.dpi.DpiStatisticsCodec;
import org.onosproject.incubator.net.dpi.FlowStatInfo;
import org.onosproject.incubator.net.dpi.FlowStatInfoCodec;
import org.onosproject.incubator.net.dpi.ProtocolStatInfo;
import org.onosproject.incubator.net.dpi.ProtocolStatInfoCodec;
import org.onosproject.incubator.net.dpi.TrafficStatInfo;
import org.onosproject.incubator.net.dpi.TrafficStatInfoCodec;
import org.onosproject.incubator.net.virtual.TenantId;
import org.onosproject.incubator.net.virtual.VirtualDevice;
import org.onosproject.incubator.net.virtual.VirtualHost;
import org.onosproject.incubator.net.virtual.VirtualLink;
import org.onosproject.incubator.net.virtual.VirtualNetwork;
import org.onosproject.incubator.net.virtual.VirtualPort;
import org.onosproject.mastership.MastershipTerm;
import org.onosproject.net.Annotations;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.Host;
import org.onosproject.net.HostLocation;
import org.onosproject.net.Link;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.Path;
import org.onosproject.net.DisjointPath;
import org.onosproject.net.FilteredConnectPoint;
import org.onosproject.net.Port;
import org.onosproject.net.behaviour.protection.TransportEndpointDescription;
import org.onosproject.net.device.PortStatistics;
import org.onosproject.net.driver.Driver;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.TableStatisticsEntry;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flowobjective.FilteringObjective;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.NextObjective;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.intent.ConnectivityIntent;
import org.onosproject.net.intent.Constraint;
import org.onosproject.net.intent.HostToHostIntent;
import org.onosproject.net.intent.Intent;
import org.onosproject.net.intent.PointToPointIntent;
import org.onosproject.net.intent.SinglePointToMultiPointIntent;
import org.onosproject.net.intent.MMWaveIntent;
import org.onosproject.net.key.DeviceKey;
import org.onosproject.net.mcast.McastRoute;
import org.onosproject.net.meter.Band;
import org.onosproject.net.meter.Meter;
import org.onosproject.net.meter.MeterRequest;
import org.onosproject.net.packet.PacketRequest;
import org.onosproject.net.region.Region;
import org.onosproject.net.statistic.Load;
import org.onosproject.net.topology.Topology;
import org.onosproject.net.topology.TopologyCluster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static org.onosproject.security.AppGuard.checkPermission;
import static org.onosproject.security.AppPermission.Type.*;
/**
* Implementation of the JSON codec brokering service.
*/
@Component(immediate = true)
@Service
public class CodecManager implements CodecService {
private static Logger log = LoggerFactory.getLogger(CodecManager.class);
private final Map<Class<?>, JsonCodec> codecs = new ConcurrentHashMap<>();
@Activate
public void activate() {
codecs.clear();
registerCodec(Application.class, new ApplicationCodec());
registerCodec(ApplicationId.class, new ApplicationIdCodec());
registerCodec(ControllerNode.class, new ControllerNodeCodec());
registerCodec(Annotations.class, new AnnotationsCodec());
registerCodec(Device.class, new DeviceCodec());
registerCodec(Port.class, new PortCodec());
registerCodec(ConnectPoint.class, new ConnectPointCodec());
registerCodec(Link.class, new LinkCodec());
registerCodec(Host.class, new HostCodec());
registerCodec(HostLocation.class, new HostLocationCodec());
registerCodec(HostToHostIntent.class, new HostToHostIntentCodec());
registerCodec(MMWaveIntent.class, new MMWaveIntentCodec());
registerCodec(PointToPointIntent.class, new PointToPointIntentCodec());
registerCodec(SinglePointToMultiPointIntent.class, new SinglePointToMultiPointIntentCodec());
registerCodec(Intent.class, new IntentCodec());
registerCodec(ConnectivityIntent.class, new ConnectivityIntentCodec());
registerCodec(FlowEntry.class, new FlowEntryCodec());
registerCodec(FlowRule.class, new FlowRuleCodec());
registerCodec(TrafficTreatment.class, new TrafficTreatmentCodec());
registerCodec(TrafficSelector.class, new TrafficSelectorCodec());
registerCodec(Instruction.class, new InstructionCodec());
registerCodec(Criterion.class, new CriterionCodec());
registerCodec(Ethernet.class, new EthernetCodec());
registerCodec(Constraint.class, new ConstraintCodec());
registerCodec(Topology.class, new TopologyCodec());
registerCodec(TopologyCluster.class, new TopologyClusterCodec());
registerCodec(Path.class, new PathCodec());
registerCodec(DisjointPath.class, new DisjointPathCodec());
registerCodec(Group.class, new GroupCodec());
registerCodec(Driver.class, new DriverCodec());
registerCodec(GroupBucket.class, new GroupBucketCodec());
registerCodec(Load.class, new LoadCodec());
registerCodec(MeterRequest.class, new MeterRequestCodec());
registerCodec(Meter.class, new MeterCodec());
registerCodec(Band.class, new MeterBandCodec());
registerCodec(TableStatisticsEntry.class, new TableStatisticsEntryCodec());
registerCodec(PortStatistics.class, new PortStatisticsCodec());
registerCodec(Metric.class, new MetricCodec());
registerCodec(FilteringObjective.class, new FilteringObjectiveCodec());
registerCodec(ForwardingObjective.class, new ForwardingObjectiveCodec());
registerCodec(NextObjective.class, new NextObjectiveCodec());
registerCodec(McastRoute.class, new McastRouteCodec());
registerCodec(DeviceKey.class, new DeviceKeyCodec());
registerCodec(Region.class, new RegionCodec());
registerCodec(TenantId.class, new TenantIdCodec());
registerCodec(VirtualNetwork.class, new VirtualNetworkCodec());
registerCodec(VirtualDevice.class, new VirtualDeviceCodec());
registerCodec(VirtualPort.class, new VirtualPortCodec());
registerCodec(VirtualLink.class, new VirtualLinkCodec());
registerCodec(VirtualHost.class, new VirtualHostCodec());
registerCodec(MastershipTerm.class, new MastershipTermCodec());
registerCodec(MastershipRole.class, new MastershipRoleCodec());
registerCodec(RoleInfo.class, new RoleInfoCodec());
registerCodec(DpiStatistics.class, new DpiStatisticsCodec());
registerCodec(DpiStatInfo.class, new DpiStatInfoCodec());
registerCodec(TrafficStatInfo.class, new TrafficStatInfoCodec());
registerCodec(ProtocolStatInfo.class, new ProtocolStatInfoCodec());
registerCodec(FlowStatInfo.class, new FlowStatInfoCodec());
registerCodec(FilteredConnectPoint.class, new FilteredConnectPointCodec());
registerCodec(TransportEndpointDescription.class, new TransportEndpointDescriptionCodec());
registerCodec(PacketRequest.class, new PacketRequestCodec());
log.info("Started");
}
@Deactivate
public void deactivate() {
codecs.clear();
log.info("Stopped");
}
@Override
public Set<Class<?>> getCodecs() {
checkPermission(CODEC_READ);
return ImmutableSet.copyOf(codecs.keySet());
}
@Override
@SuppressWarnings("unchecked")
public <T> JsonCodec<T> getCodec(Class<T> entityClass) {
checkPermission(CODEC_READ);
return codecs.get(entityClass);
}
@Override
public <T> void registerCodec(Class<T> entityClass, JsonCodec<T> codec) {
checkPermission(CODEC_WRITE);
codecs.putIfAbsent(entityClass, codec);
}
@Override
public void unregisterCodec(Class<?> entityClass) {
checkPermission(CODEC_WRITE);
codecs.remove(entityClass);
}
}
|
package net.avicus.atlas.core.command;
import com.google.common.collect.Lists;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.NestedCommand;
import java.util.List;
import net.avicus.atlas.core.Atlas;
import net.avicus.atlas.core.command.exception.CommandMatchException;
import net.avicus.atlas.core.match.Match;
import net.avicus.atlas.core.module.loadouts.Loadout;
import net.avicus.atlas.core.module.loadouts.modmenu.LoadoutModificationMenu;
import net.avicus.atlas.core.module.loadouts.type.ItemLoadout;
import net.avicus.atlas.core.module.loadouts.type.LoadoutNode;
import net.avicus.compendium.StringUtil;
import net.avicus.compendium.commands.exception.MustBePlayerCommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class LoadoutCommands {
@Command(aliases = {"mod", "modify"}, desc = "Modify an item loadout", usage = "<id>", max = 1)
@CommandPermissions("atlas.loadout.modify")
public static void mod(CommandContext args, CommandSender sender)
throws CommandException {
MustBePlayerCommandException.ensurePlayer(sender);
Match match = Atlas.getMatch();
if (match == null) {
throw new CommandMatchException();
}
String id = args.getString(0);
Loadout found = match.getRegistry().get(Loadout.class, id, false)
.orElseThrow(() -> new CommandException("Loadout not found for id \"" + id + " \""));
ItemLoadout itemLoadout = null;
if (found instanceof ItemLoadout) {
itemLoadout = (ItemLoadout) found;
} else if (found instanceof LoadoutNode) {
itemLoadout = (ItemLoadout) ((LoadoutNode) found).getLoadouts().stream()
.filter(l -> l instanceof ItemLoadout).findFirst()
.orElseThrow(() -> new CommandException("Loadout not found for id \"" + id + " \""));
}
if (itemLoadout == null) {
throw new CommandException(
"Loadout with id \"" + id + "\" is a " + found.getClass().getSimpleName()
+ " and cannot be edited.");
}
new LoadoutModificationMenu((Player) sender, itemLoadout, match, id).open();
}
@Command(aliases = "list", desc = "List all registered loadouts", max = 0)
public static void list(CommandContext args, CommandSender sender)
throws CommandException {
MustBePlayerCommandException.ensurePlayer(sender);
Match match = Atlas.getMatch();
if (match == null) {
throw new CommandMatchException();
}
List<String> ids = Lists.newArrayList();
match.getRegistry().getObjects().forEach((id, obj) -> {
if (obj.getObject() instanceof Loadout) {
ids.add(id);
}
});
sender.sendMessage(StringUtil.listToEnglishCompound(ids));
}
public static class ParentCommand {
@Command(aliases = "loadout", usage = "<>", desc = ".", min = 1)
@NestedCommand(LoadoutCommands.class)
public static void loadout(CommandContext cmd, CommandSender sender) {
// Never called
}
}
}
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi;
import com.intellij.core.JavaPsiBundle;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.RecursionGuard;
import com.intellij.openapi.util.RecursionManager;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public abstract class PsiDiamondType extends PsiType {
public static final RecursionGuard<PsiElement> ourDiamondGuard = RecursionManager.createGuard("diamondInference");
public PsiDiamondType() {
super(TypeAnnotationProvider.EMPTY);
}
public abstract DiamondInferenceResult resolveInferredTypes();
public static class DiamondInferenceResult {
public static final DiamondInferenceResult EXPLICIT_CONSTRUCTOR_TYPE_ARGS = new DiamondInferenceResult() {
@Override
public PsiType @NotNull [] getTypes() {
return PsiType.EMPTY_ARRAY;
}
@Override
public String getErrorMessage() {
return JavaPsiBundle.message("diamond.error.explicit.type.parameters.for.constructor");
}
};
public static final DiamondInferenceResult NULL_RESULT = new DiamondInferenceResult() {
@Override
public PsiType @NotNull [] getTypes() {
return PsiType.EMPTY_ARRAY;
}
@Override
public String getErrorMessage() {
return JavaPsiBundle.message("diamond.error.cannot.infer.arguments");
}
};
public static final DiamondInferenceResult RAW_RESULT = new DiamondInferenceResult() {
@Override
public PsiType @NotNull [] getTypes() {
return PsiType.EMPTY_ARRAY;
}
@Override
public String getErrorMessage() {
return null;
}
};
public static final DiamondInferenceResult UNRESOLVED_CONSTRUCTOR = new DiamondInferenceResult() {
@Override
public PsiType @NotNull [] getTypes() {
return PsiType.EMPTY_ARRAY;
}
@Override
public String getErrorMessage() {
return JavaPsiBundle.message("diamond.error.cannot.infer.arguments.unable.to.resolve.constructor");
}
};
public static final DiamondInferenceResult ANONYMOUS_INNER_RESULT = new DiamondInferenceResult() {
@Override
public PsiType @NotNull [] getTypes() {
return PsiType.EMPTY_ARRAY;
}
@Override
public String getErrorMessage() {
return JavaPsiBundle.message("diamond.error.anonymous.inner.classes");
}
};
private final List<PsiType> myInferredTypes = new ArrayList<>();
private @NlsContexts.DetailedDescription String myErrorMessage;
private String myNewExpressionPresentableText;
public DiamondInferenceResult() { }
public DiamondInferenceResult(String expressionPresentableText) {
myNewExpressionPresentableText = expressionPresentableText;
}
public PsiType @NotNull [] getTypes() {
return myErrorMessage == null ? myInferredTypes.toArray(createArray(myInferredTypes.size())) : PsiType.EMPTY_ARRAY;
}
/**
* @return all inferred types even if inference failed
*/
public List<PsiType> getInferredTypes() {
return myInferredTypes;
}
public @NlsContexts.DetailedDescription String getErrorMessage() {
return myErrorMessage;
}
public boolean failedToInfer() {
return myErrorMessage != null;
}
protected void addInferredType(PsiType psiType) {
if (myErrorMessage != null) return;
if (psiType == null) {
myErrorMessage = JavaPsiBundle.message("diamond.error.cannot.infer.type.arguments", myNewExpressionPresentableText);
}
else {
myInferredTypes.add(psiType);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DiamondInferenceResult that = (DiamondInferenceResult)o;
if (myErrorMessage != null ? !myErrorMessage.equals(that.myErrorMessage) : that.myErrorMessage != null) return false;
if (!myInferredTypes.equals(that.myInferredTypes)) return false;
return true;
}
@Override
public int hashCode() {
int result = myInferredTypes.hashCode();
result = 31 * result + (myErrorMessage != null ? myErrorMessage.hashCode() : 0);
return result;
}
}
public static boolean hasDiamond(PsiNewExpression expression) {
return getDiamondType(expression) != null;
}
public static PsiDiamondType getDiamondType(PsiNewExpression expression) {
if (PsiUtil.isLanguageLevel7OrHigher(expression)) {
final PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference();
if (classReference != null) {
final PsiReferenceParameterList parameterList = classReference.getParameterList();
if (parameterList != null) {
final PsiTypeElement[] parameterElements = parameterList.getTypeParameterElements();
if (parameterElements.length == 1) {
final PsiType type = parameterElements[0].getType();
return type instanceof PsiDiamondType ? (PsiDiamondType)type : null;
}
}
}
}
return null;
}
public static JavaResolveResult getDiamondsAwareResolveResult(PsiCall expression) {
if (expression instanceof PsiNewExpression) {
PsiDiamondType diamondType = getDiamondType((PsiNewExpression)expression);
if (diamondType != null) {
JavaResolveResult factory = diamondType.getStaticFactory();
return factory != null ? factory : JavaResolveResult.EMPTY;
}
}
if (expression instanceof PsiEnumConstant) {
final PsiEnumConstant enumConstant = (PsiEnumConstant)expression;
PsiClass containingClass = enumConstant.getContainingClass();
if (containingClass == null) return JavaResolveResult.EMPTY;
final JavaPsiFacade facade = JavaPsiFacade.getInstance(enumConstant.getProject());
final PsiClassType type = facade.getElementFactory().createType(containingClass);
PsiExpressionList argumentList = enumConstant.getArgumentList();
if (argumentList == null) return JavaResolveResult.EMPTY;
return facade.getResolveHelper().resolveConstructor(type, argumentList, enumConstant);
}
return expression.resolveMethodGenerics();
}
@Nullable
public abstract JavaResolveResult getStaticFactory();
}
|
package org.mindinformatics.gwt.domeo.client.ui.annotation.plugins;
import java.util.HashMap;
/**
* @author Paolo Ciccarese <paolo.ciccarese@gmail.com>
*/
public abstract class APlugin {
/**
* This is the list of required plugins (names, version) for the present plugin
*/
public HashMap<String, String> requiredPlugins = new HashMap<String, String>();
public abstract String getPluginName();
public abstract String getSubType();
public abstract String getType();
public abstract String getVersion();
public abstract Boolean getMandatory();
}
|
/*
Copyright 2021 Fausto Spoto
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.takamaka.code.lang;
/**
* The superclass of classes whose objects can be kept in store.
* A storage class can only have fields of types allowed in store.
* Its updates are saved in store at the end of the execution of a transaction.
*/
public abstract class Storage {
/**
* The caller of the entry method or constructor currently
* being executed. This is set at the beginning of an entry and refers
* to the contract that called the entry.
*/
private transient Contract caller;
/**
* The abstract pointer used to refer to this object in store.
* This will contain a {@code io.hotmoka.beans.values.StorageReference}
* at run time. It is private so that it does not appear accessible in subclasses
* and will be accessed by reflection.
*/
@SuppressWarnings("unused")
private transient Object storageReference;
/**
* True if the object reflects an object serialized in store.
* False otherwise. The latter case occurs if the object has been
* created during the current transaction but has not been yet
* serialized in store. It is private so that it does not appear
* accessible in subclasses and will be accessed by reflection.
*/
@SuppressWarnings("unused")
private transient boolean inStorage;
/**
* Constructs an object that can be kept in store.
*/
protected Storage() {
// this constructor gets instrumented as follows:
// when the object is first created, it is not yet in store
//this.inStorage = false;
// assigns a fresh unique identifier to the object, that will later
// be used to refer to the object once serialized in store
//this.storageReference = Runtime.getNextStorageReference();
}
// the following constructor gets added by instrumentation
/*protected Storage(StorageReference storageReference) {
// this object reflects something already in store
this.inStorage = true;
// the storage reference of this object must be the same used in blockchain
this.storageReference = storageReference;
}*/
@Override
public String toString() {
return "storage";
}
/**
* Yields the name of the class of this object.
*
* @return the name of the class of this object
*/
public final @View String getClassName() {
return getClass().getName();
}
/**
* Implements an order on storage object that delegates to the
* {@code compareTo()} on the storage references of the compared objects.
* This method is guaranteed to implement a total order relation.
*
* @param other the other object that must be compared to this
* @return the result of comparison the storage references of the two objects
*/
public final int compareByStorageReference(Storage other) {
// the following actual code will be provided by instrumentation:
// return Runtime.compareStorageReferencesOf(this, other);
return 0;
}
/**
* Yields the caller of the entry currently being executed.
*
* @return the caller
*/
protected final Contract caller() {
return caller;
}
/**
* Called at the beginning of the instrumentation of a {@code @@FromContract} method or constructor.
* It sets the caller of the code. It is private, so that programmers cannot call
* it directly. Instead, instrumented code will call it by reflection.
*
* @param caller the caller of the method or constructor
*/
@SuppressWarnings("unused")
private void fromContract(Contract caller) {
// the caller is always non-null in correctly instrumented Takamaka code;
// however, we check it to avoid calls from illegal bytecode
Takamaka.require(caller != null, "A @FromContract method or constructor cannot receive a null caller");
this.caller = caller;
}
}
|
package module0287_public_tests_unittests.a;
import java.io.*;
import java.rmi.*;
import java.nio.file.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see java.nio.file.FileStore
* @see java.sql.Array
* @see java.util.logging.Filter
*/
@SuppressWarnings("all")
public abstract class Foo2<Y> extends module0287_public_tests_unittests.a.Foo0<Y> implements module0287_public_tests_unittests.a.IFoo2<Y> {
java.util.zip.Deflater f0 = null;
javax.annotation.processing.Completion f1 = null;
javax.lang.model.AnnotatedConstruct f2 = null;
public Y element;
public static Foo2 instance;
public static Foo2 getInstance() {
return instance;
}
public static <T> T create(java.util.List<T> input) {
return module0287_public_tests_unittests.a.Foo0.create(input);
}
public String getName() {
return module0287_public_tests_unittests.a.Foo0.getInstance().getName();
}
public void setName(String string) {
module0287_public_tests_unittests.a.Foo0.getInstance().setName(getName());
return;
}
public Y get() {
return (Y)module0287_public_tests_unittests.a.Foo0.getInstance().get();
}
public void set(Object element) {
this.element = (Y)element;
module0287_public_tests_unittests.a.Foo0.getInstance().set(this.element);
}
public Y call() throws Exception {
return (Y)module0287_public_tests_unittests.a.Foo0.getInstance().call();
}
}
|
package com.waka.workspace.smalldianping.Activity.Main.Fragment.Store;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationSet;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.waka.workspace.smalldianping.Activity.CityPicker.CityPickerDialogActivity;
import com.waka.workspace.smalldianping.Activity.Main.Fragment.Store.Adapter.FoodTypeRecyclerViewAdapter;
import com.waka.workspace.smalldianping.Activity.Main.Fragment.Store.Adapter.GuessYouLikeListViewAdapter;
import com.waka.workspace.smalldianping.Constant;
import com.waka.workspace.smalldianping.CustomViews.ListViewForScrollView;
import com.waka.workspace.smalldianping.QRCODE.CaptureActivity;
import com.waka.workspace.smalldianping.R;
import com.waka.workspace.smalldianping.Activity.SearchInput.SearchInputActivity;
import com.waka.workspace.smalldianping.StaticValues;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* StoreFragment
* Created by waka on 2015/12/22.
*/
public class StoreFragment extends Fragment implements View.OnClickListener {
private static final String TAG = "StoreFragment";
//标题栏
private LinearLayout mLayoutCity, mLayoutScan;
private TextView mTvCity;
private ImageView mImgCityArrow;
private CardView mCvSearch;
//食品种类RecyclerView
private RecyclerView mRvFoodType;
private List<Map<String, Object>> mListFoodType;
private FoodTypeRecyclerViewAdapter mFoodTypeAdapter;
//猜你喜欢ListView
private ListViewForScrollView mLvGuessYouLike;
private List<Map<String, Object>> mListGuessYouLike;
private GuessYouLikeListViewAdapter mGuessYouLikeAdapter;
/**
* 构造方法
*/
public StoreFragment() {
}
/**
* newInstance,可传入数据,推荐用初始化方法
*
* @param bundle
* @return
*/
public static StoreFragment newInstance(Bundle bundle) {
StoreFragment fragment = new StoreFragment();
fragment.setArguments(bundle);
return fragment;
}
/**
* onCreate
*
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//如果有数据的话,可以取出来
if (getArguments() != null) {
}
}
/**
* onCreateView,关联布局,创建View
*
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Nullable//表示参数可为null
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_store_in_activity_main, container, false);
initView(view);
initData();
initEvent();
return view;
}
/**
* initView
*
* @param view
*/
private void initView(View view) {
mCvSearch = (CardView) view.findViewById(R.id.cvSearch);
mLayoutCity = (LinearLayout) view.findViewById(R.id.layoutCity);
mTvCity = (TextView) view.findViewById(R.id.tvCity);
mImgCityArrow = (ImageView) view.findViewById(R.id.imgCityArrow);
mLayoutScan = (LinearLayout) view.findViewById(R.id.layoutScan);
mRvFoodType = (RecyclerView) view.findViewById(R.id.rvFoodType);
mLvGuessYouLike = (ListViewForScrollView) view.findViewById(R.id.lvGuessYouLike);
}
/**
* initData
*/
private void initData() {
//初始化FoodTypeRecyclerView数据
mListFoodType = new ArrayList<>();
addDataToListFoodType(R.drawable.chinese_food, "中餐");
addDataToListFoodType(R.drawable.western_food, "西餐");
addDataToListFoodType(R.drawable.junk_food, "快餐");
addDataToListFoodType(R.drawable.pizza, "披萨");
addDataToListFoodType(R.drawable.drink, "饮品");
addDataToListFoodType(R.drawable.hot_pot, "火锅");
addDataToListFoodType(R.drawable.fruit, "水果");
addDataToListFoodType(R.drawable.meat, "烤肉");
addDataToListFoodType(R.drawable.icecream, "冰激凌");
addDataToListFoodType(R.drawable.tea, "茶馆");
mRvFoodType.setLayoutManager(new GridLayoutManager(this.getActivity(), 5));
mFoodTypeAdapter = new FoodTypeRecyclerViewAdapter(this.getActivity(), mListFoodType);
mRvFoodType.setAdapter(mFoodTypeAdapter);
//初始化GuessYouLikeListView数据
mListGuessYouLike = new ArrayList<>();
addDataToListGuessYouLike(R.drawable.food_1, "梅菜扣肉", "1.3km", "【土吧那鸡】泡芙套餐,建议2人使用,包间免费,免预约", "59", "67", "7575");
addDataToListGuessYouLike(R.drawable.food_2, "香辣鸡翅", "<500m", "【王府半岛酒店JING餐厅】北京市东城区王府井金鱼胡同8号王府半岛酒店B1楼", "89", "92", "4874");
addDataToListGuessYouLike(R.drawable.food_3, "涮羊肉", "5.34km", "【九十九顶毡房】北京市海淀区 东升乡马坊村永泰庄北路9号(地铁8号线永泰庄站东北口...", "78", "83", "758");
addDataToListGuessYouLike(R.drawable.food_4, "北京烤鸭", "<200m", "【胡大饭馆】北京市东城区东直门内大街233号", "58.2", "59", "2257");
addDataToListGuessYouLike(R.drawable.food_5, "干锅虾", ">10km", "【晋风庄园(双林东路店)】北京市丰台区小屯村双林东路南口", "159", "161", "254");
addDataToListGuessYouLike(R.drawable.food_6, "宫保鸡丁", "4.80km", "【港丽餐厅(世界城店)】北京市朝阳区金汇路8-9号世界城商业街102号铺", "67", "67", "5489");
addDataToListGuessYouLike(R.drawable.food_7, "蚂蚁上树", "10.84km", "【西湖春天】北京市朝阳区广顺北大街33号嘉茂购物中心6-7楼", "89", "110", "1546");
mGuessYouLikeAdapter = new GuessYouLikeListViewAdapter(this.getActivity(), mListGuessYouLike);
mLvGuessYouLike.setAdapter(mGuessYouLikeAdapter);
}
/**
* initEvent
*/
private void initEvent() {
mCvSearch.setOnClickListener(this);
mLayoutCity.setOnClickListener(this);
mLayoutScan.setOnClickListener(this);
}
/**
* 点击事件
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.layoutCity:
mImgCityArrow.setImageResource(R.mipmap.ic_keyboard_arrow_up_white_24dp);
Intent intent1 = new Intent(this.getActivity(), CityPickerDialogActivity.class);
getActivity().startActivityForResult(intent1, Constant.CITY_PICKER_DIALOG_ACTIVITY_REQUEST_CODE);
break;
case R.id.cvSearch:
Intent intent = new Intent(this.getActivity(), SearchInputActivity.class);
getActivity().startActivityForResult(intent, Constant.SEARCH_INPUT_ACTIVITY_REQUEST_CODE);
getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);//由左向右滑入的效果
break;
case R.id.layoutScan:
Intent intent2 = new Intent(this.getActivity(), CaptureActivity.class);
this.startActivityForResult(intent2,Constant.CAPTURE_ACTIVITY_REQUEST_CODE);
break;
default:
break;
}
}
/**
* 添加数据至FoodTypeList
*
* @param typeicon
* @param typename
*/
private void addDataToListFoodType(int typeicon, String typename) {
Map<String, Object> map = new HashMap<>();
map.put("typeicon", typeicon);
map.put("typename", typename);
mListFoodType.add(map);
}
/**
* 添加数据至GuessYouLikeList
*
* @param imgStoreIcon
* @param tvStoreName
* @param tvDistance
* @param tvDescription
* @param tvPrice
* @param tvNormalPrice
* @param tvAlreadySold
*/
private void addDataToListGuessYouLike(int imgStoreIcon, String tvStoreName, String tvDistance, String tvDescription, String tvPrice, String tvNormalPrice, String tvAlreadySold) {
Map<String, Object> map = new HashMap<>();
map.put("imgStoreIcon", imgStoreIcon);
map.put("tvStoreName", tvStoreName);
map.put("tvDistance", tvDistance);
map.put("tvDescription", tvDescription);
map.put("tvPrice", "¥" + tvPrice);
map.put("tvNormalPrice", "门市价:¥" + tvNormalPrice);
map.put("tvAlreadySold", "已售" + tvAlreadySold);
mListGuessYouLike.add(map);
}
/**
* 设置箭头方向
*/
public void setImgCityArrowBack() {
mImgCityArrow.setImageResource(R.mipmap.ic_keyboard_arrow_down_white_24dp);
}
/**
* 设置tvCity的文本
*
* @param text
*/
public void setTvCityText(String text) {
mTvCity.setText(text);
StaticValues.cityName = text;
}
}
|
/**
* Copyright 2009-2017 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.apache.ibatis.scripting.xmltags;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.ibatis.session.Configuration;
/**
* <trim>节点
* @author Clinton Begin
*/
public class TrimSqlNode implements SqlNode {
private final SqlNode contents;
private final String prefix; // 当<trim> 包裹
private final String suffix;
private final List<String> prefixesToOverride;
private final List<String> suffixesToOverride;
private final Configuration configuration;
public TrimSqlNode(Configuration configuration, SqlNode contents, String prefix, String prefixesToOverride, String suffix, String suffixesToOverride) {
this(configuration, contents, prefix, parseOverrides(prefixesToOverride), suffix, parseOverrides(suffixesToOverride));
}
protected TrimSqlNode(Configuration configuration, SqlNode contents, String prefix, List<String> prefixesToOverride, String suffix, List<String> suffixesToOverride) {
this.contents = contents;
this.prefix = prefix;
this.prefixesToOverride = prefixesToOverride;
this.suffix = suffix;
this.suffixesToOverride = suffixesToOverride;
this.configuration = configuration;
}
@Override
public boolean apply(DynamicContext context) {
FilteredDynamicContext filteredDynamicContext = new FilteredDynamicContext(context);
// filteredDynamicContext代理了context,用filteredDynamicContext来获取被trim节点包裹的sql语句,进行拦截判断后再赋值给context
boolean result = contents.apply(filteredDynamicContext);
// 运行自己的业务判断
filteredDynamicContext.applyAll();
return result;
}
private static List<String> parseOverrides(String overrides) {
if (overrides != null) {
final StringTokenizer parser = new StringTokenizer(overrides, "|", false);
final List<String> list = new ArrayList<String>(parser.countTokens());
while (parser.hasMoreTokens()) {
list.add(parser.nextToken().toUpperCase(Locale.ENGLISH));
}
return list;
}
return Collections.emptyList();
}
/**
* 为了只获取处理trim节点包裹的sql的语句,相当于代理了DynamicContext的方法
* 先运行自己的逻辑后,再根据sqlBuffer是否为空进行前缀后缀的处理
*/
private class FilteredDynamicContext extends DynamicContext {
private DynamicContext delegate;
private boolean prefixApplied;
private boolean suffixApplied;
private StringBuilder sqlBuffer;//相对于 DynamicContext中的sqlBuilder
public FilteredDynamicContext(DynamicContext delegate) {
super(configuration, null);
this.delegate = delegate;
this.prefixApplied = false;
this.suffixApplied = false;
this.sqlBuffer = new StringBuilder();
}
public void applyAll() {
sqlBuffer = new StringBuilder(sqlBuffer.toString().trim());
String trimmedUppercaseSql = sqlBuffer.toString().toUpperCase(Locale.ENGLISH);
if (trimmedUppercaseSql.length() > 0) {
applyPrefix(sqlBuffer, trimmedUppercaseSql);
applySuffix(sqlBuffer, trimmedUppercaseSql);
}
// delegate 是原来上一层的context,这个FilteredDynamicContext 处理完trimSqlNode节点后就把数据交给原来的context,自己退出
delegate.appendSql(sqlBuffer.toString());
}
@Override
public Map<String, Object> getBindings() {
return delegate.getBindings();
}
@Override
public void bind(String name, Object value) {
delegate.bind(name, value);
}
@Override
public int getUniqueNumber() {
return delegate.getUniqueNumber();
}
@Override
public void appendSql(String sql) {
sqlBuffer.append(sql);
}
@Override
public String getSql() {
return delegate.getSql();
}
private void applyPrefix(StringBuilder sql, String trimmedUppercaseSql) {
if (!prefixApplied) {
prefixApplied = true;
if (prefixesToOverride != null) {
// 只覆盖prefixesToOverride 其中一个元素就结束,如 and|or 如果遇到and就结束
for (String toRemove : prefixesToOverride) {
if (trimmedUppercaseSql.startsWith(toRemove)) {
sql.delete(0, toRemove.trim().length());
break;
}
}
}
if (prefix != null) {
sql.insert(0, " ");
sql.insert(0, prefix);
}
}
}
private void applySuffix(StringBuilder sql, String trimmedUppercaseSql) {
if (!suffixApplied) {
suffixApplied = true;
if (suffixesToOverride != null) {
for (String toRemove : suffixesToOverride) {
if (trimmedUppercaseSql.endsWith(toRemove) || trimmedUppercaseSql.endsWith(toRemove.trim())) {
int start = sql.length() - toRemove.trim().length();
int end = sql.length();
sql.delete(start, end);
break;
}
}
}
if (suffix != null) {
sql.append(" ");
sql.append(suffix);
}
}
}
}
}
|
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.impl.nio.DefaultHttpClientIODispatch;
import org.apache.http.impl.nio.pool.BasicNIOConnPool;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.protocol.BasicAsyncRequestProducer;
import org.apache.http.nio.protocol.BasicAsyncResponseConsumer;
import org.apache.http.nio.protocol.HttpAsyncRequestExecutor;
import org.apache.http.nio.protocol.HttpAsyncRequester;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
/**
* Minimal pipelining HTTP/1.1 client.
* <p>
* Please note that this example represents a minimal HTTP client implementation.
* It does not support HTTPS as is.
* You either need to provide BasicNIOConnPool with a connection factory
* that supports SSL or use a more complex HttpAsyncClient.
*
* @see org.apache.http.impl.nio.pool.BasicNIOConnPool#BasicNIOConnPool(org.apache.http.nio.reactor.ConnectingIOReactor,
* org.apache.http.nio.pool.NIOConnFactory, int)
* @see org.apache.http.impl.nio.pool.BasicNIOConnFactory
*/
public class PipeliningHttpClient {
public static void main(final String[] args) throws Exception {
// Create HTTP protocol processing chain
final HttpProcessor httpproc = HttpProcessorBuilder.create()
// Use standard client-side protocol interceptors
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();
// Create client-side HTTP protocol handler
final HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
// Create client-side I/O event dispatch
final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
ConnectionConfig.DEFAULT);
// Create client-side I/O reactor
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
// Create HTTP connection pool
final BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);
// Limit total number of connections to just two
pool.setDefaultMaxPerRoute(2);
pool.setMaxTotal(2);
// Run the I/O reactor in a separate thread
final Thread t = new Thread(new Runnable() {
public void run() {
try {
// Ready to go!
ioReactor.execute(ioEventDispatch);
} catch (final InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (final IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
});
// Start the client thread
t.start();
// Create HTTP requester
final HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);
final HttpHost target = new HttpHost("www.apache.org");
final List<BasicAsyncRequestProducer> requestProducers = Arrays.asList(
new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/index.html")),
new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/foundation/index.html")),
new BasicAsyncRequestProducer(target, new BasicHttpRequest("GET", "/foundation/how-it-works.html"))
);
final List<BasicAsyncResponseConsumer> responseConsumers = Arrays.asList(
new BasicAsyncResponseConsumer(),
new BasicAsyncResponseConsumer(),
new BasicAsyncResponseConsumer()
);
final CountDownLatch latch = new CountDownLatch(1);
final HttpCoreContext context = HttpCoreContext.create();
requester.executePipelined(
target, requestProducers, responseConsumers, pool, context,
new FutureCallback<List<HttpResponse>>() {
@Override
public void completed(final List<HttpResponse> result) {
latch.countDown();
for (final HttpResponse response: result) {
System.out.println(target + "->" + response.getStatusLine());
}
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(target + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(target + " cancelled");
}
});
latch.await();
System.out.println("Shutting down I/O reactor");
ioReactor.shutdown();
System.out.println("Done");
}
}
|
package com.redhat.developer.demos.customer.rest;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/")
public class CustomerResource {
private static final String RESPONSE_STRING_FORMAT = "customer => %s\n";
private final Logger logger = LoggerFactory.getLogger(getClass());
@Inject
@RestClient
PreferenceService preferenceService;
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getCustomer() {
try {
String response = preferenceService.getPreference().trim();
return Response.ok(String.format(RESPONSE_STRING_FORMAT, response)).build();
} catch (WebApplicationException ex) {
Response response = ex.getResponse();
logger.warn("Non HTTP 20x trying to get the response from preference service: " + response.getStatus());
return Response
.status(Response.Status.SERVICE_UNAVAILABLE)
.entity(String.format(RESPONSE_STRING_FORMAT,
String.format("Error: %d - %s", response.getStatus(), response.readEntity(String.class)))
)
.build();
} catch (ProcessingException ex) {
logger.warn("Exception trying to get the response from preference service.", ex);
return Response
.status(Response.Status.SERVICE_UNAVAILABLE)
.entity(String.format(RESPONSE_STRING_FORMAT, ex.getCause().getClass().getSimpleName() + ": " + ex.getCause().getMessage()))
.build();
}
}
}
|
package com.jparams.junit4.data.converter;
import com.jparams.junit4.reflection.MethodParameter;
import java.math.BigDecimal;
public class BigDecimalConverter implements Converter {
@Override
public Object convert(Object data, MethodParameter methodParameter) {
return new BigDecimal(data.toString());
}
}
|
/*
* Ory Kratos
* Welcome to the ORY Kratos HTTP API documentation!
*
* The version of the OpenAPI document: v0.5.4-alpha.1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package sh.ory.kratos.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import sh.ory.kratos.model.RecoveryFlowMethodConfig;
/**
* RecoveryFlowMethod
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-11-11T13:10:56.063507Z[GMT]")
public class RecoveryFlowMethod {
public static final String SERIALIZED_NAME_CONFIG = "config";
@SerializedName(SERIALIZED_NAME_CONFIG)
private RecoveryFlowMethodConfig config;
public static final String SERIALIZED_NAME_METHOD = "method";
@SerializedName(SERIALIZED_NAME_METHOD)
private String method;
public RecoveryFlowMethod config(RecoveryFlowMethodConfig config) {
this.config = config;
return this;
}
/**
* Get config
* @return config
**/
@ApiModelProperty(required = true, value = "")
public RecoveryFlowMethodConfig getConfig() {
return config;
}
public void setConfig(RecoveryFlowMethodConfig config) {
this.config = config;
}
public RecoveryFlowMethod method(String method) {
this.method = method;
return this;
}
/**
* Method contains the request credentials type.
* @return method
**/
@ApiModelProperty(required = true, value = "Method contains the request credentials type.")
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RecoveryFlowMethod recoveryFlowMethod = (RecoveryFlowMethod) o;
return Objects.equals(this.config, recoveryFlowMethod.config) &&
Objects.equals(this.method, recoveryFlowMethod.method);
}
@Override
public int hashCode() {
return Objects.hash(config, method);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class RecoveryFlowMethod {\n");
sb.append(" config: ").append(toIndentedString(config)).append("\n");
sb.append(" method: ").append(toIndentedString(method)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/**
* 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.camel.component.file;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.util.FileUtil;
import org.junit.Before;
import org.junit.Test;
public class FileProducerFileExistFailTest extends ContextTestSupport {
@Override
@Before
public void setUp() throws Exception {
deleteDirectory("target/file");
super.setUp();
}
@Test
public void testFail() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mock.expectedFileExists("target/file/hello.txt", "Hello World");
template.sendBodyAndHeader("file://target/file", "Hello World", Exchange.FILE_NAME, "hello.txt");
try {
template.sendBodyAndHeader("file://target/file?fileExist=Fail", "Bye World", Exchange.FILE_NAME, "hello.txt");
fail("Should have thrown a GenericFileOperationFailedException");
} catch (CamelExecutionException e) {
GenericFileOperationFailedException cause = assertIsInstanceOf(GenericFileOperationFailedException.class, e.getCause());
assertEquals(FileUtil.normalizePath("File already exist: target/file/hello.txt. Cannot write new file."), cause.getMessage());
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("file://target/file?noop=true&initialDelay=0&delay=10").convertBodyTo(String.class).to("mock:result");
}
};
}
}
|
/*******************************************************************************
* Copyright 2017 Vincenzo-Maria Cappelleri <vincenzo.cappelleri@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
*
*/
package raw.blockChain.api.implementations;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.TimeZone;
import raw.blockChain.api.Block;
import raw.blockChain.api.BlockHeader;
import raw.blockChain.api.BlockMiner;
import raw.blockChain.api.BlockMinerTask;
import raw.blockChain.api.HashValue;
import raw.blockChain.api.Hasher;
import raw.blockChain.api.Merkler;
import raw.blockChain.api.Transaction;
import raw.blockChain.api.implementations.DefaultBlockHeader.Builder;
import raw.blockChain.exceptions.IllegalBlockHeaderBytesRepresentation;
import raw.blockChain.exceptions.IncompleteBuilderSettingsException;
import raw.logger.Log;
import raw.settings.BlockChainProperties;
import raw.settings.ModuleProperty;
import raw.settings.PropertiesManager;
import static raw.blockChain.api.implementations.utils.BlockUtils.*;
/**
* Default implementation of {@link BlockMinerTask}
*
* @author vic
*
*/
public class DefaultBlockMinerTask extends BlockMinerTask {
private Log log;
private Merkler merkler;
private Hasher hasher;
private Random rand;
private boolean compute;
private DefaultBlockMiner father;
private String blockChainName;
private String mySignature;
public DefaultBlockMinerTask(BlockHeader previousBlockHeader,ArrayList<Transaction> candidateTransactions, BlockMiner father, String minerSignature) throws IllegalArgumentException {
super(previousBlockHeader, candidateTransactions);
log = Log.getLogger();
BlockChainProperties properties = (BlockChainProperties) PropertiesManager.getManager().getProperties(ModuleProperty.BLOCK_CHAIN);
merkler = new DefaultMerkler(properties.getMerkleCacheSize());
hasher = new DefaultHasher();
rand = new Random(System.currentTimeMillis());
compute = true;
blockChainName = properties.getBlockChainName();
mySignature = minerSignature;
if(father instanceof DefaultBlockMiner){
this.father = (DefaultBlockMiner) father;
}
else{
this.father = null;
}
}
/* (non-Javadoc)
* @see java.util.concurrent.Callable#call()
*/
@Override
public Block call() throws Exception {
log.debug("Starting this task.");
BigDecimal difficulty = nextDifficulty(getPreviousBlockHeader());
HashValue target = targetMaskFromDifficulty(difficulty);
Builder baseBlockHeaderBluilder = new Builder();
baseBlockHeaderBluilder.setBlockChainName(blockChainName).
setBlockNumber(nextBlockNumber(getPreviousBlockHeader())).
setDifficulty(difficulty).
setPrevBlockHash(getPreviousBlockHeader().hash()).
setMinerSignature(mySignature);
boolean found = false;
Block foundBlock = null;
log.debug("beginning miner loop...");
while(compute && !found){
Collections.shuffle(getCandidateTransactions());
HashValue merkleRoot = merkler.getMerkleRoot(getCandidateTransactions());
Builder blockHeaderBluilder = baseBlockHeaderBluilder;
long timestamp = System.currentTimeMillis();
TimeZone timeZone = TimeZone.getDefault();
timestamp = timestamp - timeZone.getOffset(timestamp);
blockHeaderBluilder.setTimestamp(timestamp).
setMerkleRoot(merkleRoot);
HashValue headerHash = null;
int startingNonce = rand.nextInt();
log.debug("Extracted first nonce = "+startingNonce);
for(int nonce=startingNonce; nonce < Integer.MAX_VALUE; nonce++){
if(!compute){
break;
}
headerHash = tryThisNonce(nonce, blockHeaderBluilder);
HashValue masked = headerHash.maskWith(target);
if(headerHash.equals(masked)){
log.info("YAY! found a block header: "+headerHash.toHexString());
foundBlock = new DefaultBlock(blockHeaderBluilder.build(), getCandidateTransactions());
found = true;
break;
}
}
if(!found){
for(int nonce=Integer.MIN_VALUE; nonce<startingNonce; nonce++){
if(!compute){
break;
}
headerHash = tryThisNonce(nonce, blockHeaderBluilder);
HashValue masked = headerHash.maskWith(target);
if(headerHash.equals(masked)){
log.info("YAY! found a block header: "+headerHash.toHexString());
foundBlock = new DefaultBlock(blockHeaderBluilder.build(), getCandidateTransactions());
found = true;
break;
}
}
}
}
if(father != null && found){
father.signalBlockIsFound(foundBlock);
}
return foundBlock;
}
/* (non-Javadoc)
* @see raw.blockChain.BlockMinerTask#stop()
*/
@Override
public void stop() {
compute = false;
}
private HashValue tryThisNonce(int nonce, Builder headerBuilder){
headerBuilder.setNonce(nonce);
HashValue computedHash = null;
try {
computedHash = hasher.hashBlockHeader(headerBuilder.build());
} catch (ClassNotFoundException e) {
log.exception(e);
} catch (IncompleteBuilderSettingsException e) {
log.exception(e);
} catch (IOException e) {
log.exception(e);
} catch (IllegalBlockHeaderBytesRepresentation e) {
log.exception(e);
}
return computedHash;
}
}
|
package vetcilinicservice.RestControllers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vetcilinicservice.Utils.ERest;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("/admin")
@Api(value = "LogoutRestController",authorizations = {@Authorization(value = "basicAuth")})
public class LogoutRestController {
@GetMapping("/logout")
@ApiOperation(value = "Çıkış Yap Servisi")
public Map<ERest,Object> logout(){
Map<ERest,Object> hm = new LinkedHashMap<>();
hm.put(ERest.status,true);
hm.put(ERest.message,"Başarıyla çıkış yapıldı!");
return hm;
}
}
|
/*
* Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client;
import com.hazelcast.core.Instance;
import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class LightEntrySet<K, V> extends AbstractCollection<java.util.Map.Entry<K, V>> implements Set<java.util.Map.Entry<K, V>> {
private final Set<K> keySet;
private final MapClientProxy<K, V> proxy;
private final Instance.InstanceType instanceType;
public LightEntrySet(Set<K> set, MapClientProxy<K, V> proxy, Instance.InstanceType instanceType) {
this.keySet = set;
this.proxy = proxy;
this.instanceType = instanceType;
}
public Iterator<Entry<K, V>> iterator() {
return new MapEntryIterator<K, V>(keySet.iterator(), proxy, instanceType);
}
public int size() {
return keySet.size();
}
}
|
package mb.tiger;
import mb.jsglr1.common.JSGLR1ParseTable;
import mb.jsglr1.common.JSGLR1ParseTableException;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
public class TigerParseTable implements Serializable {
final JSGLR1ParseTable parseTable;
private TigerParseTable(JSGLR1ParseTable parseTable) {
this.parseTable = parseTable;
}
public static TigerParseTable fromClassLoaderResources() {
final String resource = "mb/tiger/target/metaborg/sdf.tbl";
try(final @Nullable InputStream inputStream = TigerParseTable.class.getClassLoader().getResourceAsStream(resource)) {
if(inputStream == null) {
throw new RuntimeException("Cannot create parse table; cannot find resource '" + resource + "' in classloader resources");
}
final JSGLR1ParseTable parseTable = JSGLR1ParseTable.fromStream(inputStream);
return new TigerParseTable(parseTable);
} catch(JSGLR1ParseTableException | IOException e) {
throw new RuntimeException("Cannot create parse table; cannot read parse table from resource '" + resource + "' in classloader resources");
}
}
}
|
/*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.error;
/**
* Creates an error message indicating that an assertion that verifies that two {@code CharSequence}s are not equal,
* ignoring case
* considerations, failed.
*
* @author Alexander Bischof
*/
public class ShouldNotBeEqualIgnoringCase extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link org.assertj.core.error.ShouldNotBeEqualIgnoringCase}</code>.
*
* @param actual the actual value in the failed assertion.
* @param expected the expected value in the failed assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotBeEqualIgnoringCase(CharSequence actual, CharSequence expected) {
return new ShouldNotBeEqualIgnoringCase(actual, expected);
}
private ShouldNotBeEqualIgnoringCase(CharSequence actual, CharSequence expected) {
super("%nExpecting:%n %s%nnot to be equal to:%n %s%nignoring case considerations", actual, expected);
}
}
|
package toll.geofence;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
/**
* Created by simarv on 2016-06-06.
*/
public class GeoFenceService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public GeoFenceService(String name) {
super(name);
}
public GeoFenceService() {
super("GeoFenceService");
}
@Override protected void onHandleIntent(Intent intent) {
Log.d(this.getClass().getSimpleName(), "received: " + intent.toString());
GeoFenceHandler handler = new GeoFenceHandler(this);
if (handler.hasStarted()) {
handler.startBlocking(new ResultCallback() {
@Override public void onResult(Result result) {
Log.d(this.getClass().getSimpleName(), "started " + result.getStatus().isSuccess());
}
});
}
}
}
|
package tcp.array.client;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.*;
/*
Đề bài: Viết chương trình TCP Client/Server trong đó Client gửi lên một số nguyên dương n.
Server tạo mảng có kích thước bằng n. Sinh ngẫu nhiên các phần tử trong mảng. Server gửi trả
danh sách mảng ngẫu nhiên cho Client và Gửi Danh sách đã sắp xếp theo chiều tăng dần, giảm dần, phần tử MAX và MIN trong mảng
*/
public class Client {
Socket socket;
Scanner input;
DataOutputStream dataOutputStream;
DataInputStream dataInputStream;
public void SocketClient() {
try {
socket = new Socket("localhost", 2016);
System.out.println("Connect to Server . . .");
input = new Scanner(System.in);
System.out.print("Nhập số nguyên dương n = ");
int a = input.nextInt();
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeInt(a);
dataInputStream = new DataInputStream(socket.getInputStream());
String nhanDS = dataInputStream.readUTF();
System.out.println(nhanDS);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dataInputStream.close();
dataOutputStream.close();
socket.close();
System.out.println("Client closed!");
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) {
Client client = new Client();
client.SocketClient();
}
}
|
/*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package nettopologysuite.geometries;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import nettopologysuite.geometries.Geometry;
import nettopologysuite.geometries.Coordinate;
import nettopologysuite.geometries.CoordinateSequence;
import nettopologysuite.geometries.GeometryFactory;
import nettopologysuite.geometries.Ordinate;
import nettopologysuite.geometries.Point;
import nettopologysuite.geometries.ICoordinateFilter;
import nettopologysuite.geometries.ICoordinateFilterImplementation;
import nettopologysuite.geometries.ICoordinateSequenceFilter;
import nettopologysuite.geometries.ICoordinateSequenceFilterImplementation;
import nettopologysuite.geometries.IEntireCoordinateSequenceFilter;
import nettopologysuite.geometries.IEntireCoordinateSequenceFilterImplementation;
import nettopologysuite.geometries.IGeometryComponentFilter;
import nettopologysuite.geometries.IGeometryComponentFilterImplementation;
import nettopologysuite.geometries.IGeometryFilter;
import nettopologysuite.geometries.IGeometryFilterImplementation;
import nettopologysuite.geometries.Dimension;
import nettopologysuite.geometries.OgcGeometryType;
import nettopologysuite.geometries.ILineal;
import nettopologysuite.geometries.ILinealImplementation;
/**
* The base .NET class managing NetTopologySuite.Geometries.LineString, NetTopologySuite, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f580a05016ebada1.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/NetTopologySuite.Geometries.LineString" target="_top">https://docs.microsoft.com/en-us/dotnet/api/NetTopologySuite.Geometries.LineString</a>
*/
public class LineString extends Geometry implements nettopologysuite.geometries.ILineal {
/**
* Fully assembly qualified name: NetTopologySuite, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f580a05016ebada1
*/
public static final String assemblyFullName = "NetTopologySuite, Version=2.0.0.0, Culture=neutral, PublicKeyToken=f580a05016ebada1";
/**
* Assembly name: NetTopologySuite
*/
public static final String assemblyShortName = "NetTopologySuite";
/**
* Qualified class name: NetTopologySuite.Geometries.LineString
*/
public static final String className = "NetTopologySuite.Geometries.LineString";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public LineString(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link LineString}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link LineString} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static LineString cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new LineString(from.getJCOInstance());
}
// Constructors section
public LineString() throws Throwable {
}
public LineString(Coordinate[] points) throws Throwable, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentException, system.ArgumentNullException, system.IndexOutOfRangeException, system.InvalidOperationException {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject((java.lang.Object)toObjectFromArray(points)));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public LineString(CoordinateSequence points, GeometryFactory factory) throws Throwable, system.ArgumentNullException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentException {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(points == null ? null : points.getJCOInstance(), factory == null ? null : factory.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
public boolean EqualsExact(Geometry other, double tolerance) throws Throwable, system.PlatformNotSupportedException, system.NotSupportedException, system.IndexOutOfRangeException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Invoke("EqualsExact", other == null ? null : other.getJCOInstance(), tolerance);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean IsCoordinate(Coordinate pt) throws Throwable, system.IndexOutOfRangeException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Invoke("IsCoordinate", pt == null ? null : pt.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public double[] GetOrdinates(Ordinate ordinate) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Invoke("GetOrdinates", ordinate == null ? null : ordinate.getJCOInstance());
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
double[] resultingArray = new double[resultingArrayList.size()];
for(int indexGetOrdinates = 0; indexGetOrdinates < resultingArrayList.size(); indexGetOrdinates++ ) {
resultingArray[indexGetOrdinates] = (double)resultingArrayList.get(indexGetOrdinates);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Coordinate GetCoordinateN(int n) throws Throwable, system.IndexOutOfRangeException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objGetCoordinateN = (JCObject)classInstance.Invoke("GetCoordinateN", n);
return new Coordinate(objGetCoordinateN);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Geometry Reverse() throws Throwable, system.NotSupportedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objReverse = (JCObject)classInstance.Invoke("Reverse");
return new Geometry(objReverse);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Point GetPointN(int n) throws Throwable, system.IndexOutOfRangeException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException, nettopologysuite.utilities.AssertionFailedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objGetPointN = (JCObject)classInstance.Invoke("GetPointN", n);
return new Point(objGetPointN);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Apply(ICoordinateFilter filter) throws Throwable, system.IndexOutOfRangeException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Apply", filter == null ? null : filter.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Apply(ICoordinateSequenceFilter filter) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Apply", filter == null ? null : filter.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Apply(IEntireCoordinateSequenceFilter filter) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.ArrayTypeMismatchException, system.IndexOutOfRangeException, system.NotSupportedException, system.globalization.CultureNotFoundException, system.ObjectDisposedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Apply", filter == null ? null : filter.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Apply(IGeometryComponentFilter filter) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Apply", filter == null ? null : filter.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Apply(IGeometryFilter filter) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Apply", filter == null ? null : filter.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Normalize() throws Throwable, system.IndexOutOfRangeException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Normalize");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Properties section
public boolean getIsClosed() throws Throwable, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.NotSupportedException, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("IsClosed");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean getIsRing() throws Throwable, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.ArgumentNullException, nettopologysuite.utilities.AssertionFailedException, system.NotSupportedException, system.PlatformNotSupportedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("IsRing");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public int getCount() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Get("Count");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public CoordinateSequence getCoordinateSequence() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("CoordinateSequence");
return new CoordinateSequence(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Point getEndPoint() throws Throwable, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.NotSupportedException, system.ArgumentNullException, nettopologysuite.utilities.AssertionFailedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("EndPoint");
return new Point(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Point getStartPoint() throws Throwable, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.ArgumentException, system.NotSupportedException, system.ArgumentNullException, nettopologysuite.utilities.AssertionFailedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("StartPoint");
return new Point(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
package org.jboss.resteasy.security;
import org.jboss.resteasy.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
/**
* Utility classes to extract PublicKey, PrivateKey, and X509Certificate from openssl generated PEM files
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class PemUtils
{
static
{
BouncyIntegration.init();
}
public static X509Certificate decodeCertificate(InputStream is) throws Exception
{
byte[] der = pemToDer(is);
ByteArrayInputStream bis = new ByteArrayInputStream(der);
return DerUtils.decodeCertificate(bis);
}
/**
* Extract a public key from a PEM string
*
* @param pem
* @return
* @throws Exception
*/
public static PublicKey decodePublicKey(String pem) throws Exception
{
byte[] der = pemToDer(pem);
return DerUtils.decodePublicKey(der);
}
/**
* Extract a private key that is a PKCS8 pem string (base64 encoded PKCS8)
*
* @param pem
* @return
* @throws Exception
*/
public static PrivateKey decodePrivateKey(String pem) throws Exception
{
byte[] der = pemToDer(pem);
return DerUtils.decodePrivateKey(der);
}
public static PrivateKey decodePrivateKey(InputStream is) throws Exception
{
String pem = pemFromStream(is);
return decodePrivateKey(pem);
}
/**
* Decode a PEM file to DER format
*
* @param is
* @return
* @throws IOException
*/
public static byte[] pemToDer(InputStream is) throws IOException
{
String pem = pemFromStream(is);
byte[] der = pemToDer(pem);
return der;
}
/**
* Decode a PEM string to DER format
*
* @param pem
* @return
* @throws java.io.IOException
*/
public static byte[] pemToDer(String pem) throws java.io.IOException
{
pem = removeBeginEnd(pem);
return Base64.decode(pem);
}
private static String removeBeginEnd(String pem)
{
pem = pem.replaceAll("-----BEGIN (.*)-----", "");
pem = pem.replaceAll("-----END (.*)----", "");
pem = pem.replaceAll("\r\n", "\n");
return pem.trim();
}
public static String pemFromStream(InputStream is) throws IOException
{
DataInputStream dis = new DataInputStream(is);
byte[] keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
dis.close();
return new String(keyBytes, "utf-8");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.