hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
a65e75acf4781f8be3b9b66ade8284d362b17e60 | 1,050 | package me.mervin.project.linkPrediction.similarity.global;
import java.util.Map;
import me.mervin.core.Network;
import me.mervin.project.linkPrediction.similarity.Similarity;
import me.mervin.util.E;
import me.mervin.util.Pair;
public class RWR extends Similarity {
/*
* 迭代次数
*/
private int t = 10;
/**
* 构造函数
* @param net1 网络
*/
public RWR(Network net1) {
super(net1);
this.t = 10;
// TODO Auto-generated constructor stub
}
/**
* 构造函数
* @param net1 网络
* @param t 参数
* @throws E 异常输出
*/
public RWR(Network net1, int t) throws E {
super(net1);
this.t = t;
// TODO Auto-generated constructor stub
}
/**
* 构造函数
* @param net 网络
* @param k 存在边集合的划分个数
* @param t 参数
* @throws E 异常输出
*/
public RWR(Network net, int k, int t) throws E {
super(net, k);
this.t = t;
// TODO Auto-generated constructor stub
}
/**
*
* 通过算法对未知边赋值
* @return Map<Pair<Number>, Double>
*/
@Override
public Map<Pair<Number>, Double> script() {
// TODO Auto-generated method stub
return null;
}
}
| 17.213115 | 62 | 0.641905 |
3d1845b5b36be5b98ed36391c17b2f00b13129ef | 4,299 | /*
* Copyright (c) 2017 STMicroelectronics – All rights reserved
* The STMicroelectronics corporate logo is a trademark of STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name nor trademarks of STMicroelectronics International N.V. nor any other
* STMicroelectronics company nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* - All of the icons, pictures, logos and other images that are provided with the source code
* in a directory whose title begins with st_images may only be used for internal purposes and
* shall not be redistributed to any third party or modified in any way.
*
* - Any redistributions in binary form shall not include the capability to display any of the
* icons, pictures, logos and other images that are provided with the source code in a directory
* whose title begins with st_images.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
package com.st.BlueMS.demos.Audio.BlueVoice.ASRServices;
import android.content.Context;
import android.support.annotation.IntDef;
import com.st.BlueMS.R;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* ASR Response Messages
*/
public abstract class ASRMessage {
@IntDef({NO_ERROR,IO_CONNECTION_ERROR,
RESPONSE_ERROR,REQUEST_FAILED,NOT_RECOGNIZED,NETWORK_PROBLEM,LOW_CONFIDENCE})
@Retention(RetentionPolicy.SOURCE)
public @interface Status {}
public static final int NO_ERROR = 0;
public static final int IO_CONNECTION_ERROR = 1;
public static final int RESPONSE_ERROR = 2;
public static final int REQUEST_FAILED = 3;
public static final int NOT_RECOGNIZED = 4;
public static final int NETWORK_PROBLEM = 5;
public static final int LOW_CONFIDENCE =6;
/**
* Provides the {@code status} corresponding resource string.
* @param context current active context.
* @param status an ASRMessage status.
* @return the corresponding String to the state provided as a parameter.
*/
public static String getMessage(Context context, @ASRMessage.Status int status){
switch(status){
case NO_ERROR:
return "";
case IO_CONNECTION_ERROR:
return context.getResources().getString(R.string.blueVoice_ioError);
case RESPONSE_ERROR:
return context.getResources().getString(R.string.blueVoice_responseError);
case REQUEST_FAILED:
return context.getResources().getString(R.string.blueVoice_requestFailed);
case NOT_RECOGNIZED:
return context.getResources().getString(R.string.blueVoice_notRecognized);
case NETWORK_PROBLEM:
return context.getResources().getString(R.string.blueVoice_networkError);
case LOW_CONFIDENCE:
return context.getString(R.string.blueVoice_errorLowConfidence);
default:
return null;
}
}
}
| 46.225806 | 100 | 0.731333 |
88b458b46e2c2cb1f9f70720b73d21ec92602396 | 686 | package com.yuzhi.back.service;
import com.github.pagehelper.PageInfo;
import com.yuzhi.back.dao.entity.User;
import com.yuzhi.back.common.JsonResult;
/**
* Created by tiansj on 15/6/23.
*/
public interface UserService {
boolean addUser(User user);
boolean deleteUser(Long userId);
boolean updateUser(User user);
boolean updateUserStatus(Long id, Integer status);
User getUser(Long userId);
User getByUsername(String username);
PageInfo getUserList(int pageNum, int pageSize, User user);
boolean batchDelUser(String ids);
JsonResult bindRole(Long userId, String roleIds);
JsonResult batchBindRole(String userIds, String roleIds);
}
| 21.4375 | 63 | 0.737609 |
eb77d6610db0027c0fa4d584278c78562de47b3a | 1,775 | /**
* Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same
* color are adjacent, with the colors in the order red, white, and blue.
*
* Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
*
* Follow up:
* Could you solve this problem without using the library's sort function?
* Could you come up with a one-pass algorithm using only O(1) constant space?
*
* Example 1:
* Input: nums = [2,0,2,1,1,0]
* Output: [0,0,1,1,2,2]
*
* Example 2:
* Input: nums = [2,0,1]
* Output: [0,1,2]
*
* Example 3:
* Input: nums = [0]
* Output: [0]
*
* Example 4:
* Input: nums = [1]
* Output: [1]
*
* Constraints:
* n == nums.length
* 1 <= n <= 300
* nums[i] is 0, 1, or 2
*/
public class Problem75 {
/**
* One-pass algorithm using only O(1) constant space
*
* @param nums
*/
private static void sortColors(int[] nums) {
int redIndex = 0, blueIndex = nums.length - 1;
for (int i = 0; i <= blueIndex; i++) {
while (nums[i] == 2 && i < blueIndex) { swap(nums, i, blueIndex--);}
while (nums[i] == 0 && i > redIndex) { swap(nums, i, redIndex++);}
}
}
/**
* Method to swap elements in the array
*
* @param nums
* @param i
* @param j
*/
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
/**
* Main method for test cases
* @param args
*/
public static void main(String[] args) {
int[] nums = {2,0,2,1,1,0};
sortColors(nums);
for (int n : nums) {
System.out.print(n + " | ");
}
}
}
| 23.986486 | 113 | 0.539155 |
f6fa756a64398e1f3166d9b9bc18b8f1eaa4d50a | 2,219 | /*
* Copyright DataStax, 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.datastax.driver.osgi;
import static com.datastax.driver.osgi.BundleOptions.defaultOptions;
import static com.datastax.driver.osgi.BundleOptions.driverBundle;
import static com.datastax.driver.osgi.BundleOptions.extrasBundle;
import static com.datastax.driver.osgi.BundleOptions.guavaBundle;
import static com.datastax.driver.osgi.BundleOptions.mailboxBundle;
import static com.datastax.driver.osgi.BundleOptions.mappingBundle;
import static com.datastax.driver.osgi.BundleOptions.nettyBundles;
import static org.ops4j.pax.exam.CoreOptions.options;
import com.datastax.driver.osgi.api.MailboxException;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.testng.listener.PaxExam;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners({CCMBridgeListener.class, PaxExam.class})
public class MailboxServiceGuava19IT extends MailboxServiceTests {
@Configuration
public Option[] guava19Config() {
return options(
defaultOptions(),
nettyBundles(),
guavaBundle().version("19.0"),
driverBundle(),
extrasBundle(),
mappingBundle(),
mailboxBundle());
}
/**
* Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with Guava
* 19 explicitly enforced.
*
* @test_category packaging
* @expected_result Can create, retrieve and delete data using the mailbox service.
* @jira_ticket JAVA-620
* @since 2.0.10, 2.1.5
*/
@Test(groups = "short")
public void test_guava_19() throws MailboxException {
checkService();
}
}
| 35.222222 | 99 | 0.753042 |
44de91b055413c7edf89a3e40834679f54d0d8a2 | 2,504 | package me.katsumag.itemactionslib.nbt;
import org.bukkit.Bukkit;
import java.util.Arrays;
/**
* @author GabyTM
*/
public enum ServerVersion {
UNKNOWN(0),
/**
* Legacy versions
*/
V1_8_R1(8_1),
V1_8_R2(8_2),
V1_8_R3(8_3),
V1_9_R1(9_1),
V1_9_R2(9_2),
V1_10_R1(10_1),
V1_11_R1(11_1),
V1_12_R1(12_1),
/**
* New versions
*/
V1_13_R1(13_1),
V1_13_R2(13_2),
V1_14_R1(14_1),
V1_15_R1(15_1),
V1_16_R1(16_1);
private final int versionNumber;
/**
* Main constructor that defines a protocol version representing NX where N is the main version and X is the R version
* For example NX - 81 - 8_R1
*
* @param versionNumber The protocol version
*/
ServerVersion(final int versionNumber) {
this.versionNumber = versionNumber;
}
public static final String PACKAGE_NAME = Bukkit.getServer().getClass().getPackage().getName();
public static final String NMS_VERSION = PACKAGE_NAME.substring(PACKAGE_NAME.lastIndexOf('.') + 1);
public static final ServerVersion CURRENT_VERSION = getByNmsName(NMS_VERSION);
/**
* Checks if the current version is newer than the {@link ServerVersion} specified
*
* @param version The {@link ServerVersion} to check from
* @return Whether or not the version is newer
*/
public boolean isNewerThan(final ServerVersion version) {
return versionNumber > version.versionNumber;
}
/**
* Checks if the current version is older than the {@link ServerVersion} specified
*
* @param version The {@link ServerVersion} to check from
* @return Whether or not the version is older
*/
public boolean isOlderThan(final ServerVersion version) {
return versionNumber < version.versionNumber;
}
/**
* Checks if the server is using a legacy version
*
* @return Whether or not the server is running on a version before 1.13
*/
public boolean isLegacy() {
return versionNumber < V1_13_R1.versionNumber;
}
/**
* Gets a version from the NMS name
*
* @param name The NMS name
* @return The {@link ServerVersion} that represents that version
*/
public static ServerVersion getByNmsName(final String name) {
return Arrays.stream(values())
.filter(version -> version.name().equalsIgnoreCase(name))
.findFirst()
.orElse(UNKNOWN);
}
}
| 25.55102 | 122 | 0.641374 |
c73d0d9974f52e6aacba86dc07fc3f8618186465 | 5,826 | /*-
* #%L
* anchor-plugin-image-feature
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* 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.
* #L%
*/
package org.anchoranalysis.plugin.image.feature.object.calculation.single;
import java.util.Optional;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import org.anchoranalysis.core.exception.CreateException;
import org.anchoranalysis.feature.calculate.FeatureCalculation;
import org.anchoranalysis.feature.calculate.FeatureCalculationException;
import org.anchoranalysis.feature.calculate.cache.CalculationResolver;
import org.anchoranalysis.feature.calculate.cache.ResolvedCalculation;
import org.anchoranalysis.image.feature.input.FeatureInputSingleObject;
import org.anchoranalysis.image.voxel.object.ObjectMask;
import org.anchoranalysis.image.voxel.object.morphological.MorphologicalErosion;
import org.anchoranalysis.plugin.image.feature.bean.morphological.MorphologicalIterations;
import org.anchoranalysis.plugin.image.feature.object.calculation.single.morphological.CalculateDilation;
import org.anchoranalysis.plugin.image.feature.object.calculation.single.morphological.CalculateErosion;
import org.anchoranalysis.spatial.box.Extent;
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class CalculateShellObjectMask
extends FeatureCalculation<ObjectMask, FeatureInputSingleObject> {
private final ResolvedCalculation<ObjectMask, FeatureInputSingleObject> calculateDilation;
private final ResolvedCalculation<ObjectMask, FeatureInputSingleObject> calculateErosion;
private final int iterationsErosionSecond;
private final boolean do3D;
private final boolean inverse;
public static FeatureCalculation<ObjectMask, FeatureInputSingleObject> of(
CalculationResolver<FeatureInputSingleObject> params,
MorphologicalIterations iterations,
int iterationsErosionSecond,
boolean inverse) {
ResolvedCalculation<ObjectMask, FeatureInputSingleObject> ccDilation =
CalculateDilation.of(
params, iterations.getIterationsDilation(), iterations.isDo3D());
ResolvedCalculation<ObjectMask, FeatureInputSingleObject> ccErosion =
CalculateErosion.ofResolved(
params, iterations.getIterationsErosion(), iterations.isDo3D());
return new CalculateShellObjectMask(
ccDilation, ccErosion, iterationsErosionSecond, iterations.isDo3D(), inverse);
}
@Override
protected ObjectMask execute(FeatureInputSingleObject input)
throws FeatureCalculationException {
Extent extent = input.dimensionsRequired().extent();
ObjectMask shell = createShellObject(input);
if (inverse) {
ObjectMask duplicated = input.getObject().duplicate();
Optional<ObjectMask> omShellIntersected = shell.intersect(duplicated, extent);
omShellIntersected.ifPresent(
shellIntersected -> assignOffTo(duplicated, shellIntersected));
return duplicated;
} else {
return shell;
}
}
@Override
public String toString() {
return String.format(
"%s ccDilation=%s, ccErosion=%s, do3D=%s, inverse=%s, iterationsErosionSecond=%d",
super.toString(),
calculateDilation.toString(),
calculateErosion.toString(),
do3D ? "true" : "false",
inverse ? "true" : "false",
iterationsErosionSecond);
}
private ObjectMask createShellObject(FeatureInputSingleObject input)
throws FeatureCalculationException {
ObjectMask dilated = calculateDilation.getOrCalculate(input).duplicate();
ObjectMask eroded = calculateErosion.getOrCalculate(input);
// Maybe apply a second erosion
dilated = maybeErodeSecondTime(dilated);
assignOffTo(dilated, eroded);
return dilated;
}
private ObjectMask maybeErodeSecondTime(ObjectMask object) throws FeatureCalculationException {
try {
if (iterationsErosionSecond > 0) {
return MorphologicalErosion.erode(object, iterationsErosionSecond, do3D);
} else {
return object;
}
} catch (CreateException e) {
throw new FeatureCalculationException(e);
}
}
/**
* Assigns off pixels to an object-mask based on another object-mask specified in
* global-cordinates
*/
private static void assignOffTo(ObjectMask toAssignTo, ObjectMask objectMask) {
toAssignTo.assignOff().toObject(objectMask);
}
}
| 41.913669 | 105 | 0.718847 |
1c312f288e4b6c7288e986bb00c5a80b36f3ba32 | 2,180 | /*
* Decompiled with CFR 0_110.
*/
package edu.stanford.crypto.bitcoin;
import edu.stanford.crypto.SQLDatabase;
import edu.stanford.crypto.database.Database;
import org.bouncycastle.math.ec.ECPoint;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
public class SQLPrivateKeyDatabase
implements PrivateKeyDatabase,
SQLDatabase {
public static final String RETRIEVE_SECRETS_SQL = "SELECT private_key FROM asset_proof_secrets WHERE public_key=?";
public static final String INSERT_INTO_SQL = "INSERT INTO asset_proof_secrets VALUES (?,?)";
private final PreparedStatement retrieveSecrets;
private final PreparedStatement insertSecrets;
private final Connection connection = Database.getConnection();
public SQLPrivateKeyDatabase() throws SQLException {
this.retrieveSecrets = this.connection.prepareStatement("SELECT private_key FROM asset_proof_secrets WHERE public_key=?");
this.insertSecrets = this.connection.prepareStatement("INSERT INTO asset_proof_secrets VALUES (?,?)");
}
@Override
public void store(ECPoint publicKey, BigInteger privateKey) {
try {
this.insertSecrets.setBytes(1, publicKey.getEncoded(true));
this.insertSecrets.setBytes(2, privateKey.toByteArray());
this.insertSecrets.execute();
}
catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public Optional<BigInteger> retrievePrivateKey(ECPoint publicKey) {
try {
this.retrieveSecrets.setBytes(1, publicKey.getEncoded(true));
ResultSet resultSet = this.retrieveSecrets.executeQuery();
if (resultSet.next()) {
return Optional.of(new BigInteger(resultSet.getBytes(1)));
}
return Optional.empty();
}
catch (SQLException e) {
e.printStackTrace();
throw new IllegalArgumentException(e);
}
}
@Override
public void close() throws SQLException {
this.connection.close();
}
}
| 33.538462 | 130 | 0.693119 |
c3584460121dda00ad5a92058bea3ebd52ef23b9 | 763 | /**
*/
package de.dc.javafx.xcore.workbench.impl;
import de.dc.javafx.xcore.workbench.LeftPane;
import de.dc.javafx.xcore.workbench.WorkbenchPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Left Pane</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class LeftPaneImpl extends ViewContainerImpl implements LeftPane {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected LeftPaneImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return WorkbenchPackage.Literals.LEFT_PANE;
}
} //LeftPaneImpl
| 20.078947 | 74 | 0.609436 |
1244249df840e12ced38fdf98c1d26433d75fe05 | 4,245 | package com.sc.reminder.ui;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import com.sc.reminder.R;
import com.sc.reminder.model.trip.Trip;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.ScrollView;
public class TimeAxisView extends View {
private Paint paint;
private Context context;
private Calendar calendar;
private int width;
private int height = 3000;
private ArrayList<Trip> trips;
private String[] timeStrings = {"00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00"};
public TimeAxisView(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.calendar = Calendar.getInstance();
this.context = context;
paint = new Paint();
paint.setColor(Color.BLACK);
}
public TimeAxisView(Context context,Calendar c,int position,ArrayList<Trip> trips) {
super(context);
// TODO Auto-generated constructor stub
this.calendar = Calendar.getInstance();
this.context = context;
paint = new Paint();
paint.setColor(Color.BLACK);
this.trips = trips;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
drawAxis(canvas);
drawEvents(canvas);
//drawPicture(canvas);
super.onDraw(canvas);
}
private void drawAxis(Canvas canvas){
paint.setTextSize(35);
int startX = 150;
int startY = height/24;
int stopX = width;
int offset = height/24;
for(int i =0;i<24;i++){
startY = offset*i;
paint.setColor(Color.WHITE);
if(i == 0){
canvas.drawText(timeStrings[i], 20, startY+35, paint);
}else{
canvas.drawText(timeStrings[i], 20, startY+17, paint);
}
//canvas.drawText(timeStrings[i], 20, startY+17, paint);
paint.setColor(Color.BLACK);
canvas.drawLine(startX, startY, stopX, startY, paint);
}
paint.setColor(Color.WHITE);
canvas.drawLine(150, 0, 150, 3000, paint);
}
private void drawEvent(Canvas canvas){
int startX = 150;
int stopX = width;
Rect r = new Rect(startX, 680, width, 980);
paint.setColor(Color.parseColor("#AAAAAA"));
canvas.drawRect(r, paint);
}
private void drawPicture(Canvas canvas){
InputStream is = getResources().openRawResource(R.drawable.trip_type0);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
int bh = mBitmap.getHeight();
int bw = mBitmap.getWidth();
canvas.drawBitmap(mBitmap, 150-bw/2,680, paint);
}
private int top = 0;
private int bottom = 0;
private void drawEvents(Canvas canvas){
int hour = 0;
int minute = 0;
//int second;
for(int i = 0;i<trips.size();i++){
String start = trips.get(i).getStarttime();
hour = Integer.parseInt(start.substring(11, 13));
Log.i("top", start.substring(11, 13));
minute = Integer.parseInt(start.substring(14, 16));
//second = Integer.parseInt(start.substring(17, 18));
top = hour*(3000/24)+minute*(3000/1440);
String end = trips.get(i).getEndtime();
hour = Integer.parseInt(end.substring(11, 13));
minute = Integer.parseInt(end.substring(14, 16));
bottom = hour*(3000/24)+minute*(3000/1440);Log.i("bottom", start.substring(11, 13));
Rect r = new Rect(150, top, width, bottom);
paint.setColor(Color.parseColor("#AAAAAA"));
canvas.drawRect(r, paint);
InputStream is = getResources().openRawResource(R.drawable.trip_type0);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
//int bh = mBitmap.getHeight();
int bw = mBitmap.getWidth();
canvas.drawBitmap(mBitmap, 150-bw/2,top, paint);
paint.setColor(Color.parseColor("#000000"));
canvas.drawText(trips.get(i).getTitle(), 180, top + 38, paint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
width = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(width, 3000);
}
}
| 28.877551 | 226 | 0.69258 |
a7f6274dc3d4e303bc6f6a1b6098d4b6c02ef05e | 804 | package com.hbasebook.hush.table;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.util.Bytes;
public class ShortUrlTable {
public static final TableName NAME = TableName.valueOf("hush", "surl");
public static final byte[] DATA_FAMILY = Bytes.toBytes("data");
public static final byte[] DAILY_FAMILY = Bytes.toBytes("std");
public static final byte[] WEEKLY_FAMILY = Bytes.toBytes("stw");
public static final byte[] MONTHLY_FAMILY = Bytes.toBytes("stm");
public static final byte[] URL = Bytes.toBytes("url");
public static final byte[] SHORT_DOMAIN = Bytes.toBytes("sdom");
public static final byte[] REF_SHORT_ID = Bytes.toBytes("ref");
public static final byte[] USER_ID = Bytes.toBytes("uid");
public static final byte[] CLICKS = Bytes.toBytes("clk");
}
| 44.666667 | 73 | 0.736318 |
1e1190714859968c830c597d24b4b4ab6ecf775f | 3,874 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spi.block;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.security.Identity;
import com.facebook.presto.spi.type.TimeZoneKey;
import com.facebook.presto.spi.type.Type;
import io.airlift.slice.DynamicSliceOutput;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import org.testng.annotations.Test;
import java.util.Locale;
import java.util.Optional;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_SESSION_PROPERTY;
import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static java.util.Locale.ENGLISH;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class TestDictionaryBlockEncoding
{
private static final ConnectorSession SESSION = new ConnectorSession()
{
@Override
public Identity getIdentity()
{
return new Identity("user", Optional.empty());
}
@Override
public TimeZoneKey getTimeZoneKey()
{
return UTC_KEY;
}
@Override
public Locale getLocale()
{
return ENGLISH;
}
@Override
public long getStartTime()
{
return 0;
}
@Override
public <T> T getProperty(String name, Class<T> type)
{
throw new PrestoException(INVALID_SESSION_PROPERTY, "Unknown session property " + name);
}
};
@Test
public void testRoundTrip()
{
int positionCount = 40;
// build dictionary
BlockBuilder dictionaryBuilder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 4);
VARCHAR.writeString(dictionaryBuilder, "alice");
VARCHAR.writeString(dictionaryBuilder, "bob");
VARCHAR.writeString(dictionaryBuilder, "charlie");
VARCHAR.writeString(dictionaryBuilder, "dave");
Block dictionary = dictionaryBuilder.build();
// build ids
int[] ids = new int[positionCount];
for (int i = 0; i < 40; i++) {
ids[i] = i % 4;
}
Slice idsSlice = Slices.wrappedIntArray(ids);
BlockEncoding blockEncoding = new DictionaryBlockEncoding(new VariableWidthBlockEncoding());
DictionaryBlock dictionaryBlock = new DictionaryBlock(positionCount, dictionary, idsSlice);
DynamicSliceOutput sliceOutput = new DynamicSliceOutput(1024);
blockEncoding.writeBlock(sliceOutput, dictionaryBlock);
Block actualBlock = blockEncoding.readBlock(sliceOutput.slice().getInput());
assertTrue(actualBlock instanceof DictionaryBlock);
DictionaryBlock actualDictionaryBlock = (DictionaryBlock) actualBlock;
assertBlockEquals(VARCHAR, actualDictionaryBlock.getDictionary(), dictionary);
assertEquals(actualDictionaryBlock.getIds(), idsSlice);
}
private static void assertBlockEquals(Type type, Block actual, Block expected)
{
for (int position = 0; position < actual.getPositionCount(); position++) {
assertEquals(type.getObjectValue(SESSION, actual, position), type.getObjectValue(SESSION, expected, position));
}
}
}
| 34.900901 | 123 | 0.695405 |
911065c32e210aa4251ef8c7088146b9b92d8a7e | 557 | package com.zyd.blog.business.service;
import com.github.pagehelper.PageInfo;
import com.zyd.blog.business.entity.Tags;
import com.zyd.blog.business.vo.TagsConditionVO;
import com.zyd.blog.framework.object.AbstractService;
/**
* 标签
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @website https://www.zhyd.me
* @date 2018/4/16 16:26
* @since 1.0
*/
public interface BizTagsService extends AbstractService<Tags, Long> {
PageInfo<Tags> findPageBreakByCondition(TagsConditionVO vo);
Tags getByName(String name);
}
| 23.208333 | 69 | 0.746858 |
51e9fd7748b6486ca5c8664a683c044b108f3653 | 1,915 | package com.zhilian.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
/**
* 封装 accessToken
* 正确获取
* {"accessToken":"PYtr70kAdrfdTQjCht8yEcJtfi1LYlUMivgRoJgrZEzNnzmUTm9gFnlif3OtyKmT","expiresIn":7200}
* 获取错误
* {"errCode":40001,"errMsg":"invalid credential"}
*/
public class AccessToken {
private String accessToken; // 正确获取到 accessToken 时有值
private String key; // 正确获取到 accessToken 时有值
private Integer expiresIn; // 正确获取到 accessToken 时有值,有效时长,单位为秒
private Integer errCode; // 出错时有值
private String errMsg; // 出错时有值
private Long expiredTime; // 正确获取到 accessToken 时有值,存放过期时间
private String json;
public AccessToken(String jsonStr) {
this.json = jsonStr;
try {
@SuppressWarnings("rawtypes")
Map map = new ObjectMapper().readValue(jsonStr, Map.class);
accessToken = (String)map.get("accessToken");
expiresIn = (Integer)map.get("expiresIn");
key = (String)map.get("key");
errCode = (Integer)map.get("errCode");
errMsg = (String)map.get("errMsg");
if (expiresIn != null)
expiredTime = System.currentTimeMillis() + ((expiresIn -5) * 1000);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getJson() {
return json;
}
public boolean isAvailable() {
if (expiredTime == null)
return false;
if (errCode != null)
return false;
if (expiredTime < System.currentTimeMillis())
return false;
return accessToken != null;
}
public String getAccessToken() {
return accessToken;
}
public Integer getExpiresIn() {
return expiresIn;
}
public Integer getErrorCode() {
return errCode;
}
public String getErrorMsg() {
if (errCode != null) {
String result = ReturnCode.get(errCode);
if (result != null)
return result;
}
return errMsg;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
| 21.761364 | 102 | 0.68094 |
f9ec8130a4eb02097014f2d367723f8d2b3e3a74 | 1,549 | package com.x.processplatform.assemble.designer.jaxrs.querystat;
import java.util.ArrayList;
import java.util.List;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.exception.ExceptionWhen;
import com.x.base.core.http.ActionResult;
import com.x.base.core.http.EffectivePerson;
import com.x.base.core.utils.SortTools;
import com.x.processplatform.assemble.designer.Business;
import com.x.processplatform.assemble.designer.wrapout.WrapOutQueryStat;
import com.x.processplatform.core.entity.element.Application;
import com.x.processplatform.core.entity.element.QueryStat;
class ActionListWithApplication extends ActionBase {
ActionResult<List<WrapOutQueryStat>> execute(EffectivePerson effectivePerson, String applicationId)
throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<WrapOutQueryStat>> result = new ActionResult<>();
List<WrapOutQueryStat> wraps = new ArrayList<>();
Business business = new Business(emc);
Application application = emc.find(applicationId, Application.class, ExceptionWhen.not_found);
business.applicationEditAvailable(effectivePerson, application, ExceptionWhen.not_allow);
List<String> ids = business.queryStat().listWithApplication(applicationId);
List<QueryStat> os = emc.list(QueryStat.class, ids);
wraps = outCopier.copy(os);
SortTools.asc(wraps, "name");
result.setData(wraps);
return result;
}
}
}
| 44.257143 | 100 | 0.801808 |
7e3bcd1f36d9e24638bd663613b9449030ac30f9 | 5,852 | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.professor.zebrautility;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import com.zebra.sdk.comm.ConnectionException;
import com.zebra.sdk.comm.internal.BluetoothHelper;
import com.zebra.sdk.comm.internal.BtServiceDiscoverer;
import com.zebra.sdk.printer.discovery.DeviceFilter;
import com.zebra.sdk.printer.discovery.DiscoveredPrinterBluetooth;
import com.zebra.sdk.printer.discovery.DiscoveryHandler;
import com.zebra.sdk.printer.discovery.ServiceDiscoveryHandler;
import java.util.HashMap;
import java.util.Map;
public class BluetoothDiscoverer {
private Context mContext;
private DiscoveryHandler mDiscoveryHandler;
BluetoothDiscoverer.BtReceiver btReceiver;
BluetoothDiscoverer.BtRadioMonitor btMonitor;
private DeviceFilter deviceFilter;
private BluetoothDiscoverer(Context var1, DiscoveryHandler var2, DeviceFilter var3) {
this.mContext = var1;
this.deviceFilter = var3;
this.mDiscoveryHandler = var2;
}
public static void findPrinters(Context var0, DiscoveryHandler var1, DeviceFilter var2) throws ConnectionException {
BluetoothAdapter var3 = BluetoothAdapter.getDefaultAdapter();
if (var3 == null) {
var1.discoveryError("No bluetooth radio found");
} else if (!var3.isEnabled()) {
var1.discoveryError("Bluetooth radio is currently disabled");
} else {
if (var3.isDiscovering()) {
var3.cancelDiscovery();
}
(new BluetoothDiscoverer(var0.getApplicationContext(), var1, var2)).doBluetoothDisco();
}
}
public static void findPrinters(Context var0, DiscoveryHandler var1) throws ConnectionException {
DeviceFilter var2 = new DeviceFilter() {
public boolean shouldAddPrinter(BluetoothDevice var1) {
return true;
}
};
findPrinters(var0, var1, var2);
}
public static void findServices(Context var0, String var1, ServiceDiscoveryHandler var2) {
BtServiceDiscoverer var3 = new BtServiceDiscoverer(BluetoothHelper.formatMacAddress(var1), var2);
var3.doDiscovery(var0);
}
private void unregisterTopLevelReceivers(Context var1) {
if (this.btReceiver != null) {
var1.unregisterReceiver(this.btReceiver);
}
if (this.btMonitor != null) {
var1.unregisterReceiver(this.btMonitor);
}
}
private void doBluetoothDisco() {
this.btReceiver = new BluetoothDiscoverer.BtReceiver();
this.btMonitor = new BluetoothDiscoverer.BtRadioMonitor();
IntentFilter var1 = new IntentFilter("android.bluetooth.device.action.FOUND");
IntentFilter var2 = new IntentFilter("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
IntentFilter var3 = new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED");
this.mContext.registerReceiver(this.btReceiver, var1);
this.mContext.registerReceiver(this.btReceiver, var2);
this.mContext.registerReceiver(this.btMonitor, var3);
BluetoothAdapter.getDefaultAdapter().startDiscovery();
}
private class BtRadioMonitor extends BroadcastReceiver {
private BtRadioMonitor() {
}
public void onReceive(Context var1, Intent var2) {
String var3 = var2.getAction();
if ("android.bluetooth.adapter.action.STATE_CHANGED".equals(var3)) {
Bundle var4 = var2.getExtras();
int var5 = var4.getInt("android.bluetooth.adapter.extra.STATE");
if (var5 == 10) {
BluetoothDiscoverer.this.mDiscoveryHandler.discoveryFinished();
BluetoothDiscoverer.this.unregisterTopLevelReceivers(var1);
}
}
}
}
private class BtReceiver extends BroadcastReceiver {
private static final int BLUETOOTH_PRINTER_CLASS = 1664;
private Map<String, BluetoothDevice> foundDevices;
private BtReceiver() {
this.foundDevices = new HashMap();
}
public void onReceive(Context var1, Intent var2) {
String var3 = var2.getAction();
if ("android.bluetooth.device.action.FOUND".equals(var3)) {
this.processFoundPrinter(var2);
} else if ("android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(var3)) {
BluetoothDiscoverer.this.mDiscoveryHandler.discoveryFinished();
BluetoothDiscoverer.this.unregisterTopLevelReceivers(var1);
}
}
private void processFoundPrinter(Intent var1) {
BluetoothDevice var2 = (BluetoothDevice)var1.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
if (!this.foundDevices.keySet().contains(var2.getAddress()) && BluetoothDiscoverer.this.deviceFilter != null && BluetoothDiscoverer.this.deviceFilter.shouldAddPrinter(var2) && this.isPrinterClass(var2)) {
BluetoothDiscoverer.this.mDiscoveryHandler.foundPrinter(new DiscoveredPrinterBluetooth(var2.getAddress(), var2.getName()));
this.foundDevices.put(var2.getAddress(), var2);
}
}
private boolean isPrinterClass(BluetoothDevice var1) {
BluetoothClass var2 = var1.getBluetoothClass();
if (var2 != null) {
return var2.getDeviceClass() == 1664;
} else {
return false;
}
}
}
}
| 39.275168 | 216 | 0.676863 |
74f8dc1925519e71733b270c3c8ab3ac107074fc | 1,014 | /*
* 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 easycoding.ch04.encryption.symmetric;
import easycoding.ch04.classLoader.Constants;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 生成对称密钥 以 序列化的方式存储
* @author wliu
*/
public class Skey_DES_SaveAsObject {
public static void main(String[] args) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(168); // keysize = 168
SecretKey key = keyGenerator.generateKey();
FileOutputStream fileOutputStream = new FileOutputStream(
Constants.LOAD_PATH + "/DES_object.dat");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
fileOutputStream);
objectOutputStream.writeObject(key);
}
}
| 32.709677 | 79 | 0.725838 |
67625c1416839249e60c924a2a4cc18d9b31f7ae | 957 | /*
* Copyright 2017 8Kdata Technology
*
* 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.torodb.testing.docker;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
/**
*
*/
public interface ImageInstaller {
/**
* Install the installable image if it is not yet installed.
*/
void installImage(DockerClient client) throws DockerException, InterruptedException;
}
| 29.90625 | 86 | 0.750261 |
772ac7105885539fc431756e7ae4f68c91d1e3e7 | 335 | package com.github.srec.rec.common;
import javax.swing.*;
import java.awt.*;
/**
* Decodes text from JCheckBoxes.
*
* @author Vivek Prahlad
*/
public class JCheckBoxDecoder implements ComponentDecoder {
public String decode(Component renderer) {
return Boolean.toString(((JCheckBox) renderer).isSelected());
}
}
| 19.705882 | 69 | 0.710448 |
47a9980fc36311644927a52627d5857bec1d0c7a | 9,121 | /**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.runtime.storm.bolt.rules;
import com.hortonworks.streamline.common.util.Utils;
import com.hortonworks.streamline.streams.StreamlineEvent;
import com.hortonworks.streamline.streams.Result;
import com.hortonworks.streamline.streams.common.IdPreservedStreamlineEvent;
import com.hortonworks.streamline.streams.common.StreamlineEventImpl;
import com.hortonworks.streamline.streams.common.event.correlation.EventCorrelationInjector;
import com.hortonworks.streamline.streams.exception.ProcessingException;
import com.hortonworks.streamline.streams.layout.component.Stream;
import com.hortonworks.streamline.streams.layout.component.impl.RulesProcessor;
import com.hortonworks.streamline.streams.layout.component.rule.expression.Window;
import com.hortonworks.streamline.streams.runtime.processor.RuleProcessorRuntime;
import com.hortonworks.streamline.streams.runtime.storm.bolt.AbstractWindowedProcessorBolt;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.apache.storm.windowing.TupleWindow;
import com.hortonworks.streamline.streams.runtime.storm.bolt.StreamlineWindowedBolt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static com.hortonworks.streamline.streams.common.StreamlineEventImpl.GROUP_BY_TRIGGER_EVENT;
import static com.hortonworks.streamline.streams.runtime.transform.AddHeaderTransformRuntime.HEADER_FIELD_DATASOURCE_IDS;
import static com.hortonworks.streamline.streams.runtime.transform.AddHeaderTransformRuntime.HEADER_FIELD_EVENT_IDS;
/**
* A windowed rules bolt
*/
public class WindowRulesBolt extends AbstractWindowedProcessorBolt {
private static final Logger LOG = LoggerFactory.getLogger(WindowRulesBolt.class);
private RuleProcessorRuntime ruleProcessorRuntime;
private final RulesProcessor rulesProcessor;
private final RuleProcessorRuntime.ScriptType scriptType;
private long windowId;
public WindowRulesBolt(RulesProcessor rulesProcessor, RuleProcessorRuntime.ScriptType scriptType) {
this.rulesProcessor = rulesProcessor;
this.scriptType = scriptType;
}
public WindowRulesBolt(String rulesProcessorJson, RuleProcessorRuntime.ScriptType scriptType) {
this(Utils.createObjectFromJson(rulesProcessorJson, RulesProcessor.class), scriptType);
}
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
super.prepare(stormConf, context, collector);
if (this.rulesProcessor == null) {
throw new RuntimeException("rulesProcessor cannot be null");
}
ruleProcessorRuntime = new RuleProcessorRuntime(rulesProcessor, scriptType);
Map<String, Object> config = Collections.emptyMap();
ruleProcessorRuntime.initialize(config);
}
/**
* Process the tuple window and optionally emit new tuples based on the tuples in the input window.
*
* @param inputWindow
*/
@Override
public void execute(TupleWindow inputWindow) {
++windowId;
LOG.debug("Window activated, window id {}, number of tuples in window {}", windowId, inputWindow.get().size());
Map<String, Tuple> eventIdToTupleMap = new HashMap<>();
try {
StreamlineEvent event;
for (Tuple input : inputWindow.get()) {
if ((event = getStreamlineEventFromTuple(input)) != null) {
LOG.debug("++++++++ Executing tuple [{}] which contains StreamlineEvent [{}]", input, event);
eventIdToTupleMap.put(event.getId(), input);
processAndEmit(event, eventIdToTupleMap);
}
}
// force evaluation of the last group by
processAndEmit(GROUP_BY_TRIGGER_EVENT, eventIdToTupleMap);
// current group is processed and result emitted
eventIdToTupleMap.clear();
} catch (Exception e) {
collector.reportError(e);
LOG.error("", e);
}
}
private void processAndEmit(StreamlineEvent event, Map<String, Tuple> curGroup) throws ProcessingException {
List<Result> results = ruleProcessorRuntime.process(eventWithWindowId(event));
for (Result result : results) {
for (StreamlineEvent e : result.events) {
// TODO: updateHeaders can be handled at ruleProcessorRuntime.process stage passing context info.
// anchor parent events if such information is available
if (EventCorrelationInjector.containsParentIds(e)) {
Set<String> parentIds = EventCorrelationInjector.getParentIds(e);
List<Tuple> parents = parentIds.stream().map(pid -> {
if (!curGroup.containsKey(pid)) {
throw new IllegalStateException("parents should be in grouped tuples");
}
return curGroup.get(pid);
}).collect(Collectors.toList());
collector.emit(result.stream, parents, new Values(updateHeaders(e, parents)));
} else {
// put all events in current group if there's no information
collector.emit(result.stream, curGroup.values(), new Values(updateHeaders(e, curGroup.values())));
}
}
}
}
private StreamlineEvent updateHeaders(StreamlineEvent event, Collection<Tuple> tuples) {
Map<String, Object> headers = new HashMap<>();
headers.put(HEADER_FIELD_EVENT_IDS, getEventIds(tuples));
headers.put(HEADER_FIELD_DATASOURCE_IDS, getDataSourceIds(tuples));
event = event.addHeaders(headers);
return event;
}
private List<String> getEventIds(Collection<Tuple> tuples) {
Set<String> res = new HashSet<>();
StreamlineEvent event;
for (Tuple tuple : tuples) {
if ((event = getStreamlineEventFromTuple(tuple)) != null) {
res.add(event.getId());
}
}
return new ArrayList<>(res);
}
private List<String> getDataSourceIds(Collection<Tuple> tuples) {
Set<String> res = new HashSet<>();
StreamlineEvent event;
for (Tuple tuple : tuples) {
if ((event = getStreamlineEventFromTuple(tuple)) != null) {
res.add(event.getDataSourceId());
}
}
return new ArrayList<>(res);
}
private StreamlineEvent getStreamlineEventFromTuple(Tuple tuple) {
final Object event = tuple.getValueByField(StreamlineEvent.STREAMLINE_EVENT);
if (event instanceof StreamlineEvent) {
return getStreamlineEventWithStream((StreamlineEvent) event, tuple);
} else {
LOG.debug("Invalid tuple received. Tuple disregarded and rules not evaluated.\n\tTuple [{}]." +
"\n\tStreamlineEvent [{}].", tuple, event);
}
return null;
}
private StreamlineEvent getStreamlineEventWithStream(StreamlineEvent event, Tuple tuple) {
StreamlineEventImpl newEvent = StreamlineEventImpl.builder().from(event).sourceStream(tuple.getSourceStreamId()).build();
return new IdPreservedStreamlineEvent(newEvent, event.getId());
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
if (this.rulesProcessor == null) {
throw new RuntimeException("rulesProcessor cannot be null");
}
for (Stream stream : rulesProcessor.getOutputStreams()) {
declarer.declareStream(stream.getId(), new Fields(StreamlineEvent.STREAMLINE_EVENT));
}
}
private StreamlineEvent eventWithWindowId(final StreamlineEvent event) {
if (event == GROUP_BY_TRIGGER_EVENT) {
return event;
}
StreamlineEvent newEvent = event.addFieldsAndValues(Collections.<String, Object>singletonMap(Window.WINDOW_ID, windowId));
return new IdPreservedStreamlineEvent(newEvent, event.getId());
}
}
| 43.850962 | 130 | 0.691591 |
fc701a886dfacac4173bb79ef099a437f827fb37 | 2,071 | package hackovid2020.back.rest;
import hackovid2020.back.dto.category.CategoryRequest;
import hackovid2020.back.dto.category.CategoryResponse;
import hackovid2020.back.dto.category.CategoryResponseList;
import hackovid2020.back.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
@RestController
@RequestMapping("/api/category")
@Api(value = "category", description = "Category management", tags = { "Category" })
public class CategoryController {
@Autowired
CategoryService categoryService;
@PostMapping(produces=MediaType.APPLICATION_JSON_VALUE, consumes=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value = "Creates a new category.")
@Transactional
public CategoryResponse createCategory(CategoryRequest request) {
return CategoryResponse.ofCategory(categoryService.saveCategory(request.toCategory()));
}
@GetMapping(value="/{id}", produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value = "Get a category.")
@Transactional
public CategoryResponse getCategory(@PathVariable("id") Long id) {
return CategoryResponse.ofCategory(categoryService.getCategory(id));
}
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value = "Get all categories.")
@Transactional
public CategoryResponseList getCategories() {
return CategoryResponseList.ofCategoriesList(categoryService.getAllCategories());
}
@PutMapping(value="/{id}", produces=MediaType.APPLICATION_JSON_VALUE, consumes=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value = "Update a file.")
@Transactional
public CategoryResponse updateCategory(CategoryRequest request, @PathVariable("id") Long id) {
return CategoryResponse.ofCategory(categoryService.updateCategory(id, request.getCategoryType(),
request.getParentCategory()));
}
}
| 36.333333 | 113 | 0.811685 |
5caaaba1432511b3b9135a12d699abfb5b9936e5 | 3,618 | package org.rcsb.mmtf.codec;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.rcsb.mmtf.dataholders.MmtfStructure;
import org.rcsb.mmtf.encoder.EncoderUtils;
/**
* Class to test the codecs (anything that implements {@link CodecInterface}).
* @author Anthony Bradley
*
*/
public class TestCodecs {
/**
* Test all of the float codecs work on a range of input data.
*/
@Test
public void testFloatCodecs() {
for(float[] inputData : getFloatData()){
for (FloatCodecs floatCodecs : FloatCodecs.values()){
byte[] encoded = floatCodecs.encode(inputData,1000);
assertNotNull(encoded);
float[] decoded = floatCodecs.decode(encoded,1000);
assertArrayEquals(decoded, inputData, 0.0009f);
}
}
}
/**
* Test all of the int codecs work on a range of input data.
*/
@Test
public void testIntCodecs() {
for(int[] inputData : getIntData()){
for (IntCodecs codec : IntCodecs.values()){
byte[] encoded = codec.encode(inputData,EncoderUtils.NULL_PARAM);
assertNotNull(encoded);
int[] decoded = codec.decode(encoded,EncoderUtils.NULL_PARAM);
assertArrayEquals(decoded, inputData);
}
}
}
/**
* Test all of the char codecs work on a range of input data.
*/
@Test
public void testCharCodecs() {
for(char[] inputData : getCharData()){
for (CharCodecs codec : CharCodecs.values()){
byte[] encoded = codec.encode(inputData,MmtfStructure.CHAIN_LENGTH);
assertNotNull(encoded);
char[] decoded = codec.decode(encoded,MmtfStructure.CHAIN_LENGTH);
assertArrayEquals(decoded, inputData);
}
}
}
/**
* Test all of the String codecs work on a range of input data.
*/
@Test
public void testStringCodecs() {
for(String[] inputData : getStringData()){
for (StringCodecs codec : StringCodecs.values()){
byte[] encoded = codec.encode(inputData,MmtfStructure.CHAIN_LENGTH);
assertNotNull(encoded);
String[] decoded = codec.decode(encoded,MmtfStructure.CHAIN_LENGTH);
assertArrayEquals(decoded, inputData);
}
}
}
/**
* Test the lossy compression of floats
*/
@Test
public void testLossyCompression(){
float[] inputData = new float[] {1.23020f, 4.299239f, 1.9032f,12203.4023002f};
float[] expected = new float[] {1.2f, 4.3f, 1.9f,12203.4f};
assertArrayEquals(expected, FloatCodecs.INT_DELTA_RECURSIVE.decode(FloatCodecs.INT_DELTA_RECURSIVE.encode(inputData, 10),10),0.0f);
}
/**
* Get the character array data to test all the methods with.
* @return a list of character arrays to be used as test data.
*/
private List<char[]> getCharData() {
List<char[]> data = new ArrayList<>();
data.add(new char[]{'A','B','?'});
return data;
}
/**
* Get the String array data to test all the methods with.
* @return a list of String arrays to be used as test data.
*/
private List<String[]> getStringData() {
List<String[]> data = new ArrayList<>();
data.add(new String[]{"A","BDDD","?"});
return data;
}
/**
* Get the integer array data to test all the methods with.
* @return a list of integer arrays to be used as test data.
*/
private List<int[]> getIntData() {
List<int[]> data = new ArrayList<>();
// TODO Must be 8 bit (1 byte) ints
data.add(new int[]{1,2,12});
return data;
}
/**
* Get the floating point array data to test all the methods with.
* @return a list of float arrays to be used as test data.
*/
private List<float[]> getFloatData() {
List<float[]> data = new ArrayList<>();
data.add(new float[]{1.0f,2.0f,Short.MAX_VALUE});
return data;
}
}
| 26.217391 | 133 | 0.678552 |
3ea6f9ecb05e5a0da17f3c26583b91656181ef23 | 3,292 | /*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.spring.concourse.artifactoryresource.artifactory;
import java.util.Date;
import java.util.List;
import io.spring.concourse.artifactoryresource.artifactory.payload.BuildModule;
import io.spring.concourse.artifactoryresource.artifactory.payload.BuildRun;
import io.spring.concourse.artifactoryresource.artifactory.payload.ContinuousIntegrationAgent;
import io.spring.concourse.artifactoryresource.artifactory.payload.DeployedArtifact;
import org.springframework.util.Assert;
/**
* Access to artifactory build runs.
*
* @author Phillip Webb
* @author Madhura Bhave
*/
public interface ArtifactoryBuildRuns {
/**
* Add a new build run.
* @param buildNumber the build number
* @param buildUri the build URL
* @param modules the modules for the build run
*/
default void add(String buildNumber, String buildUri, List<BuildModule> modules) {
add(buildNumber, buildUri, null, new Date(), modules);
}
/**
* Add a new build run.
* @param buildNumber the build number
* @param buildUri the build URL
* @param continuousIntegrationAgent the CI Agent
* @param modules the modules for the build run
*/
default void add(String buildNumber, String buildUri, ContinuousIntegrationAgent continuousIntegrationAgent,
List<BuildModule> modules) {
add(buildNumber, buildUri, continuousIntegrationAgent, new Date(), modules);
}
/**
* Add a new build run.
* @param buildNumber the build number
* @param buildUri the build URL
* @param continuousIntegrationAgent the CI Agent
* @param started the date the build was started
* @param modules the modules for the build run
*/
void add(String buildNumber, String buildUri, ContinuousIntegrationAgent continuousIntegrationAgent, Date started,
List<BuildModule> modules);
/**
* Return all previous build runs.
* @return the build runs
*/
List<BuildRun> getAll();
/**
* Return a string containing the build-info JSON as stored on the server.
* @param buildNumber the build number
* @return a string containing the build-info JSON
*/
String getRawBuildInfo(String buildNumber);
/**
* Return all artifacts that were deployed for the specified build run.
* @param buildRun the build run
* @return the deployed artifacts
*/
default List<DeployedArtifact> getDeployedArtifacts(BuildRun buildRun) {
Assert.notNull(buildRun, "BuildRun must not be null");
return getDeployedArtifacts(buildRun.getBuildNumber());
}
/**
* Return all artifacts that were deployed for the specified build number.
* @param buildNumber the build number
* @return the deployed artifacts
*/
List<DeployedArtifact> getDeployedArtifacts(String buildNumber);
}
| 32.594059 | 115 | 0.755772 |
54459cf401f7c3146c99d2267f2c29017edae19d | 214 | package com.dcm.easypoi.excel.entity.enmus;
/**
* Cell 值得类型
*
* @Author hourz
* @since 2020-01-06
*/
public enum CellValueType {
InlineStr, String, Number, Boolean, Date, TElement, Null, Formula, None;
}
| 17.833333 | 76 | 0.682243 |
748d4f969d61d904072b8aeca78535aec14e86a1 | 752 | package io.github.talelin.latticy.dto.my;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
/**
* @Author Guiquan Chen
* @Date 2021/3/7 15:53
* @Version 1.0
* 更新规格时,使用的DTO
*/
@Data
public class SpecKeyUpdateDTO {
/**
* id
*/
@NotNull
@Positive
private Long id;
/**
* 规格名
*/
@NotNull
@NotEmpty
@Length(min = 1)
private String name;
/**
* 是否为标准规格
*/
@NotNull
private Boolean standard;
/**
* 当前规格的单位,例:个,英寸
*/
private String unit;
/**
* 规格描述
*/
private String description;
}
| 16.711111 | 50 | 0.614362 |
7619c9809787ae1143f36be9d74ed525947f0a60 | 1,345 | //package Berkeley.CS61B.exercise.list1;
public class ExtraIntListPractice {
/** Returns an IntList identical to L, but with
* each element incremented by x. L is not allowed
* to change. */
public static IntList incrList(IntList L, int x) {
/* Your code here. */
if (L == null)
return null;
return new IntList(L.first + x, incrList(L.rest, x));
}
/** Returns an IntList identical to L, but with
* each element incremented by x. Not allowed to use
* the 'new' keyword. */
public static IntList dincrList(IntList L, int x) {
/* Your code here. */
if (L == null)
return null;
L.first += x;
L.rest = dincrList(L.rest, x);
return L;
}
public static void main(String[] args) {
IntList L = new IntList(5, null);
L.rest = new IntList(7, null);
L.rest.rest = new IntList(9, null);
System.out.println(L.size());
System.out.println(L.iterativeSize());
// Test your answers by uncommenting. Or copy and paste the
// code for incrList and dincrList into IntList.java and
// run it in the visualizer.
System.out.println(L.get(1));
System.out.println(incrList(L, 3).get(1));
System.out.println(dincrList(L, 3).get(1));
}
}
| 32.02381 | 67 | 0.581413 |
61830638053603f7c6c123e853ce0604d23c9959 | 844 | package cn.he.zhao.bbs.util;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 描述:
* id生产
*
* @Author HeFeng
* @Create 2018-09-02 11:46
*/
public final class Ids {
private static final Lock ID_GEN_LOCK = new ReentrantLock();
private static final long ID_GEN_SLEEP_MILLIS = 50L;
private Ids() {
}
public static synchronized String genTimeMillisId() {
String ret = null;
ID_GEN_LOCK.lock();
try {
ret = String.valueOf(System.currentTimeMillis());
try {
Thread.sleep(50L);
} catch (InterruptedException var5) {
throw new RuntimeException("Generates time millis id fail");
}
} finally {
ID_GEN_LOCK.unlock();
}
return ret;
}
} | 22.210526 | 76 | 0.590047 |
686c21867a74000e3b72be8fc6eb9b682d72a6d6 | 297 | /**
*
*/
package za.co.sindi.validations.core;
import java.util.logging.Logger;
/**
* @author Bienfait Sindi
* @since 23 July 2012
*
*/
public abstract class AbstractConstraint<T> implements Constraint<T> {
protected final Logger logger = Logger.getLogger(this.getClass().getName());
}
| 17.470588 | 77 | 0.710438 |
ac0af8f2f8cb1522512f4cf90100f5e48ec8cfa6 | 3,116 | package com.bignerdranch.android.loginapp.Service;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
//import android.support.v7.app.NotificationCompat;
import android.support.v4.app.NotificationCompat;
import com.bignerdranch.android.loginapp.Common;
import com.bignerdranch.android.loginapp.OrderStatus;
import com.bignerdranch.android.loginapp.R;
import com.bignerdranch.android.loginapp.Request;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ListenOrder extends Service implements ChildEventListener {
FirebaseDatabase db;
DatabaseReference requests;
public ListenOrder() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
db=FirebaseDatabase.getInstance();
requests=db.getReference("Requests");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
requests.addChildEventListener(this);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Request request=dataSnapshot.getValue(Request.class);
showNotification(dataSnapshot.getKey(),request);
}
private void showNotification(String key, Request request) {
Intent intent =new Intent(getBaseContext(), OrderStatus.class);
intent.putExtra("userPhone", request.getPhone());
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder= new NotificationCompat.Builder(getBaseContext());
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setTicker("Edmtdev")
.setContentInfo("Your order was updated")
.setContentText("Order #"+"key"+"was update to status to"+ Common.convertCodeToStatus(request.getStatus()))
.setContentIntent(contentIntent)
.setContentInfo("Info").setSmallIcon(R.mipmap.ic_launcher);
NotificationManager notificationManager=(NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}
| 33.505376 | 133 | 0.730103 |
e175217f50303dc90f2e277492163390ed55828c | 2,029 | /* Copyright 2004-2015 Jim Voris
*
* 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.qumasoft.server;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Directory ID store.
* @author Jim Voris
*/
public class DirectoryIDStore implements Serializable {
private static final long serialVersionUID = -6263643751412006708L;
// Create our logger object
private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryIDStore.class);
private int instanceMaximumDirectoryID = 0;
/**
* Creates a new instance of DirectoryIDStore.
*/
public DirectoryIDStore() {
}
synchronized void dump() {
LOGGER.info(": Max directory ID: " + instanceMaximumDirectoryID);
}
/**
* Return a fresh directory ID for the given project.
* @return a fresh directory ID for the given project.
*/
synchronized int getNewDirectoryID() {
return ++instanceMaximumDirectoryID;
}
/**
* Return the current maximum directory ID.
* @return the current maximum directory ID.
*/
synchronized int getCurrentMaximumDirectoryID() {
return instanceMaximumDirectoryID;
}
/**
* Set the maximum directory id.
* @param maximumDirectoryId the value to use as the current maximum directory id.
*/
public synchronized void setMaximumDirectoryID(int maximumDirectoryId) {
instanceMaximumDirectoryID = maximumDirectoryId;
}
}
| 30.742424 | 89 | 0.699852 |
6b810a36ed963093fcfc201ea42b527ea8e22dac | 4,724 | /*
* 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.aliyuncs.outboundbot.model.v20191226;
import com.aliyuncs.RpcAcsRequest;
import java.util.List;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.outboundbot.Endpoint;
/**
* @author auto create
* @version
*/
public class CreateJobGroupRequest extends RpcAcsRequest<CreateJobGroupResponse> {
private String recallStrategyJson;
private String jobGroupName;
private String scriptId;
private String strategyJson;
private Long ringingDuration;
private String scenarioId;
private String priority;
private String jobGroupDescription;
private List<String> callingNumbers;
private String instanceId;
private Long minConcurrency;
public CreateJobGroupRequest() {
super("OutboundBot", "2019-12-26", "CreateJobGroup", "outboundbot");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getRecallStrategyJson() {
return this.recallStrategyJson;
}
public void setRecallStrategyJson(String recallStrategyJson) {
this.recallStrategyJson = recallStrategyJson;
if(recallStrategyJson != null){
putQueryParameter("RecallStrategyJson", recallStrategyJson);
}
}
public String getJobGroupName() {
return this.jobGroupName;
}
public void setJobGroupName(String jobGroupName) {
this.jobGroupName = jobGroupName;
if(jobGroupName != null){
putQueryParameter("JobGroupName", jobGroupName);
}
}
public String getScriptId() {
return this.scriptId;
}
public void setScriptId(String scriptId) {
this.scriptId = scriptId;
if(scriptId != null){
putQueryParameter("ScriptId", scriptId);
}
}
public String getStrategyJson() {
return this.strategyJson;
}
public void setStrategyJson(String strategyJson) {
this.strategyJson = strategyJson;
if(strategyJson != null){
putQueryParameter("StrategyJson", strategyJson);
}
}
public Long getRingingDuration() {
return this.ringingDuration;
}
public void setRingingDuration(Long ringingDuration) {
this.ringingDuration = ringingDuration;
if(ringingDuration != null){
putQueryParameter("RingingDuration", ringingDuration.toString());
}
}
public String getScenarioId() {
return this.scenarioId;
}
public void setScenarioId(String scenarioId) {
this.scenarioId = scenarioId;
if(scenarioId != null){
putQueryParameter("ScenarioId", scenarioId);
}
}
public String getPriority() {
return this.priority;
}
public void setPriority(String priority) {
this.priority = priority;
if(priority != null){
putQueryParameter("Priority", priority);
}
}
public String getJobGroupDescription() {
return this.jobGroupDescription;
}
public void setJobGroupDescription(String jobGroupDescription) {
this.jobGroupDescription = jobGroupDescription;
if(jobGroupDescription != null){
putQueryParameter("JobGroupDescription", jobGroupDescription);
}
}
public List<String> getCallingNumbers() {
return this.callingNumbers;
}
public void setCallingNumbers(List<String> callingNumbers) {
this.callingNumbers = callingNumbers;
if (callingNumbers != null) {
for (int i = 0; i < callingNumbers.size(); i++) {
putQueryParameter("CallingNumber." + (i + 1) , callingNumbers.get(i));
}
}
}
public String getInstanceId() {
return this.instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
if(instanceId != null){
putQueryParameter("InstanceId", instanceId);
}
}
public Long getMinConcurrency() {
return this.minConcurrency;
}
public void setMinConcurrency(Long minConcurrency) {
this.minConcurrency = minConcurrency;
if(minConcurrency != null){
putQueryParameter("MinConcurrency", minConcurrency.toString());
}
}
@Override
public Class<CreateJobGroupResponse> getResponseClass() {
return CreateJobGroupResponse.class;
}
}
| 25.12766 | 118 | 0.727561 |
9f7c422ac12ce4889ca497e114f849ec0f84558f | 27,060 | /*
* GROOVE: GRaphs for Object Oriented VErification Copyright 2003--2007
* University of Twente
*
* 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.
*
* $Id: PartitionRefiner.java 5787 2016-08-04 10:36:41Z rensink $
*/
package groove.graph.iso;
import java.util.LinkedList;
import java.util.List;
import groove.grammar.host.HostNode;
import groove.grammar.host.ValueNode;
import groove.graph.Edge;
import groove.graph.Element;
import groove.graph.Graph;
import groove.graph.Label;
import groove.graph.Node;
import groove.util.collect.TreeHashSet;
/**
* Implements an algorithm to partition a given graph into sets of symmetric
* graph elements (i.e., nodes and edges). The result is available as a mapping
* from graph elements to "certificate" objects; two edges are predicted to be
* symmetric if they map to the same (i.e., <tt>equal</tt>) certificate. This
* strategy goes beyond bisimulation in that it breaks all apparent symmetries
* in all possible ways and accumulates the results.
* @author Arend Rensink
* @version $Revision: 5787 $
*/
public class PartitionRefiner extends CertificateStrategy {
/**
* Constructs a new bisimulation strategy, on the basis of a given graph.
* The strategy checks for isomorphism weakly, meaning that it might yield
* false negatives.
* @param graph the underlying graph for the bisimulation strategy; should
* not be <tt>null</tt>
*/
public PartitionRefiner(Graph graph) {
this(graph, false);
}
/**
* Constructs a new bisimulation strategy, on the basis of a given graph.
* @param graph the underlying graph for the bisimulation strategy; should
* not be <tt>null</tt>
* @param strong if <code>true</code>, the strategy puts more effort into
* getting distinct certificates.
*/
public PartitionRefiner(Graph graph, boolean strong) {
super(graph);
this.strong = strong;
}
@Override
public CertificateStrategy newInstance(Graph graph, boolean strong) {
return new PartitionRefiner(graph, strong);
}
/**
* This method only returns a useful result after the graph certificate or
* partition map has been calculated.
*/
@Override
public int getNodePartitionCount() {
if (this.nodePartitionCount == 0) {
computeCertificates();
}
return this.nodePartitionCount;
}
/** Right now only a strong strategy is implemented. */
@Override
public boolean getStrength() {
return true;
}
@Override
void iterateCertificates() {
iterateCertificates1();
iterateCertificates2();
}
/**
* Iterates node certificates until this results in a stable partitioning.
*/
private void iterateCertificates1() {
resizeTmpCertIxs();
// get local copies of attributes for speedup
int nodeCertCount = this.nodeCertCount;
// collect and then count the number of certificates
boolean goOn;
do {
int oldPartitionCount = this.nodePartitionCount;
// first compute the new edge certificates
advanceEdgeCerts();
advanceNodeCerts(this.iterateCount > 0 && this.nodePartitionCount < nodeCertCount);
// we stop the iteration when the number of partitions has not grown
// moreover, when the number of partitions equals the number of
// nodes then
// it cannot grow, so we might as well stop straight away
if (this.iterateCount == 0) {
goOn = true;
} else {
goOn = this.nodePartitionCount > oldPartitionCount;
}
this.iterateCount++;
} while (goOn);
recordIterateCount(this.iterateCount);
if (TRACE) {
System.out.printf("First iteration done; %d partitions for %d nodes in %d iterations%n",
this.nodePartitionCount,
this.nodeCertCount,
this.iterateCount);
}
}
/** Computes the node and edge certificate arrays. */
private void iterateCertificates2() {
if ((this.strong || BREAK_DUPLICATES) && this.nodePartitionCount < this.nodeCertCount) {
resizeTmpCertIxs();
// now look for smallest unbroken duplicate certificate (if any)
int oldPartitionCount;
do {
oldPartitionCount = this.nodePartitionCount;
List<MyNodeCert> duplicates = getSmallestDuplicates();
if (duplicates.isEmpty()) {
if (TRACE) {
System.out.printf("All duplicate certificates broken%n");
}
// EZ: Need to increase the count here, otherwise this
// counter is always zero.
totalSymmetryBreakCount++;
break;
}
checkpointCertificates();
// successively break the symmetry at each of these
for (MyNodeCert duplicate : duplicates) {
duplicate.breakSymmetry();
iterateCertificates1();
rollBackCertificates();
this.nodePartitionCount = oldPartitionCount;
}
accumulateCertificates();
// calculate the edge and node certificates once more
// to push out the accumulated node values and get the correct
// node partition count
advanceEdgeCerts();
advanceNodeCerts(true);
if (TRACE) {
System.out.printf(
"Next iteration done; %d partitions for %d nodes in %d iterations%n",
this.nodePartitionCount,
this.nodeCertCount,
this.iterateCount);
}
} while (true);// this.nodePartitionCount < this.nodeCertCount &&
// this.nodePartitionCount > oldPartitionCount);
}
// so far we have done nothing with the self-edges, so
// give them a chance to get their value right
int edgeCount = this.edgeCerts.length;
for (int i = this.edge2CertCount; i < edgeCount; i++) {
((MyEdge1Cert) this.edgeCerts[i]).setNewValue();
}
}
/** Extends the {@link #tmpCertIxs} array, if necessary. */
private void resizeTmpCertIxs() {
if (this.nodeCertCount > tmpCertIxs.length) {
tmpCertIxs = new int[this.nodeCertCount + 100];
}
}
/**
* Calls {@link MyCert#setNewValue()} on all edge certificates.
*/
private void advanceEdgeCerts() {
for (int i = 0; i < this.edge2CertCount; i++) {
MyEdge2Cert edgeCert = (MyEdge2Cert) this.edgeCerts[i];
this.graphCertificate += edgeCert.setNewValue();
}
}
/**
* Calls {@link MyCert#setNewValue()} on all node certificates. Also
* calculates the certificate store on demand.
* @param store if <code>true</code>, {@link #certStore} and
* {@link #nodePartitionCount} are recalculated
*/
private void advanceNodeCerts(boolean store) {
int tmpSize = 0;
for (int i = 0; i < this.nodeCertCount; i++) {
MyNodeCert nodeCert = (MyNodeCert) this.nodeCerts[i];
this.graphCertificate += nodeCert.setNewValue();
if (store) {
if (nodeCert.isSingular()) {
// add to the certStore later, to avoid resetting singularity
tmpCertIxs[tmpSize] = i;
tmpSize++;
} else {
MyNodeCert oldCertForValue = certStore.put(nodeCert);
if (oldCertForValue == null) {
// assume this certificate is singular
nodeCert.setSingular(this.iterateCount);
} else {
// the original certificate was not singular
oldCertForValue.setSingular(0);
}
}
}
}
if (store) {
// copy the remainder of the certificates to the store
for (int i = 0; i < tmpSize; i++) {
certStore.add((MyNodeCert) this.nodeCerts[tmpCertIxs[i]]);
}
this.nodePartitionCount = certStore.size();
certStore.clear();
}
}
/**
* Calls {@link MyCert#setCheckpoint()} on all node and edge
* certificates.
*/
private void checkpointCertificates() {
for (int i = 0; i < this.nodeCerts.length; i++) {
MyCert<?> nodeCert = (MyCert<?>) this.nodeCerts[i];
nodeCert.setCheckpoint();
}
for (int i = 0; i < this.edge2CertCount; i++) {
MyCert<?> edgeCert = (MyCert<?>) this.edgeCerts[i];
edgeCert.setCheckpoint();
}
}
/** Calls {@link MyCert#rollBack()} on all node and edge certificates. */
private void rollBackCertificates() {
for (int i = 0; i < this.nodeCerts.length; i++) {
MyCert<?> nodeCert = (MyCert<?>) this.nodeCerts[i];
nodeCert.rollBack();
}
for (int i = 0; i < this.edge2CertCount; i++) {
MyCert<?> edgeCert = (MyCert<?>) this.edgeCerts[i];
edgeCert.rollBack();
}
}
/**
* Calls {@link MyCert#accumulate(int)} on all node and edge
* certificates.
*/
private void accumulateCertificates() {
for (int i = 0; i < this.nodeCerts.length; i++) {
MyCert<?> nodeCert = (MyCert<?>) this.nodeCerts[i];
nodeCert.accumulate(this.iterateCount);
}
for (int i = 0; i < this.edge2CertCount; i++) {
MyCert<?> edgeCert = (MyCert<?>) this.edgeCerts[i];
edgeCert.accumulate(this.iterateCount);
}
}
/** Returns the list of duplicate certificates with the smallest value. */
private List<MyNodeCert> getSmallestDuplicates() {
List<MyNodeCert> result = new LinkedList<>();
MyNodeCert minCert = null;
for (int i = 0; i < this.nodeCerts.length; i++) {
MyNodeCert cert = (MyNodeCert) this.nodeCerts[i];
if (!cert.isSingular()) {
if (minCert == null) {
minCert = cert;
result.add(cert);
} else if (cert.getValue() < minCert.getValue()) {
minCert = cert;
result.clear();
result.add(cert);
} else if (cert.getValue() == minCert.getValue()) {
result.add(cert);
}
}
}
assert result.size() != 1;
return result;
}
@Override
NodeCertificate createValueNodeCertificate(ValueNode node) {
return new MyValueNodeCert(node);
}
@Override
MyNodeCert createNodeCertificate(Node node) {
return new MyNodeCert(node);
}
@Override
MyEdge1Cert createEdge1Certificate(Edge edge, NodeCertificate source) {
return new MyEdge1Cert(edge, (MyNodeCert) source);
}
@Override
MyEdge2Cert createEdge2Certificate(Edge edge, NodeCertificate source, NodeCertificate target) {
return new MyEdge2Cert(edge, (MyNodeCert) source, (MyNodeCert) target);
}
/**
* Flag to indicate that more effort should be put into obtaining distinct
* certificates.
*/
private final boolean strong;
/**
* The number of pre-computed node partitions.
*/
private int nodePartitionCount;
/** Total number of iterations in {@link #iterateCertificates()}. */
private int iterateCount;
/**
* Returns the total number of times symmetry was broken during the
* calculation of the certificates.
*/
static public int getSymmetryBreakCount() {
return totalSymmetryBreakCount;
}
/**
* The resolution of the tree-based certificate store.
*/
static private final int TREE_RESOLUTION = 3;
/**
* Store for node certificates, to count the number of partitions
*/
static private final TreeHashSet<MyNodeCert> certStore =
new TreeHashSet<MyNodeCert>(TREE_RESOLUTION) {
/**
* For the purpose of this set, only the certificate value is of
* importance.
*/
@Override
protected boolean allEqual() {
return true;
}
@Override
protected int getCode(MyNodeCert key) {
return key.getValue();
}
};
/** Temporary storage for node certificates. */
static private int[] tmpCertIxs = new int[100];
/** Debug flag to switch the use of duplicate breaking on and off. */
static private final boolean BREAK_DUPLICATES = true;
/** Total number of times the symmetry was broken. */
static private int totalSymmetryBreakCount;
/**
* Superclass of graph element certificates.
*/
public static abstract class MyCert<E extends Element>
implements CertificateStrategy.ElementCertificate<E> {
/** Constructs a certificate for a given graph element. */
MyCert(E element) {
this.element = element;
}
/**
* Returns the certificate value. Note that this means the hash code is
* not constant during the initial phase, and so no hash sets or maps
* should be used.
* @ensure <tt>result == getValue()</tt>
* @see #getValue()
*/
@Override
public int hashCode() {
return this.value;
}
/**
* Tests if the other is a {@link PartitionRefiner.MyCert} with the same value.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
MyCert<?> other = ((MyCert<?>) obj);
return this.value == other.value;
}
/**
* Returns the current certificate value.
*/
@Override
final public int getValue() {
return this.value;
}
@Override
public void modifyValue(int mod) {
this.value += mod;
}
/**
* Computes, stores and returns a new value for this certificate. The
* computation is done by invoking {@link #computeNewValue()}.
* @return the freshly computed new value
* @see #computeNewValue()
*/
protected int setNewValue() {
return this.value = computeNewValue();
}
/**
* Callback method that provides the new value at each iteration.
* @return the freshly computed new value
* @see #setNewValue()
*/
abstract protected int computeNewValue();
/** Returns the element of which this is a certificate. */
@Override
public E getElement() {
return this.element;
}
/**
* Sets a checkpoint that we can later roll back to.
*/
public void setCheckpoint() {
this.checkpointValue = this.value;
}
/**
* Rolls back the value to that frozen at the latest checkpoint.
*/
public void rollBack() {
this.cumulativeValue += this.value;
this.value = this.checkpointValue;
}
/**
* Combines the accumulated intermediate values collected at rollback,
* and adds them to the actual value.
* @param round the iteration round
*/
public void accumulate(int round) {
this.value += this.cumulativeValue;
this.cumulativeValue = 0;
}
/** The current value, which determines the hash code. */
protected int value;
/** The value as frozen at the last call of {@link #setCheckpoint()}. */
private int checkpointValue;
/**
* The cumulative values as calculated during the {@link #rollBack()}s
* after the last {@link #setCheckpoint()}.
*/
private int cumulativeValue;
/** The element for which this is a certificate. */
private final E element;
}
/**
* Class of nodes that carry (and are identified with) an integer
* certificate value.
* @author Arend Rensink
* @version $Revision: 5787 $
*/
static class MyNodeCert extends MyCert<Node>implements CertificateStrategy.NodeCertificate {
/** Initial node value to provide a better spread of hash codes. */
static private final int INIT_NODE_VALUE = 0x126b;
/**
* Constructs a new certificate node. The incidence count (i.e., the
* number of incident edges) is passed in as a parameter. The initial
* value is set to the incidence count.
*/
public MyNodeCert(Node node) {
super(node);
if (node instanceof HostNode) {
this.label = ((HostNode) node).getType().label();
this.value = this.label.hashCode();
} else {
this.label = null;
this.value = INIT_NODE_VALUE;
}
}
/**
* Tests if the other is a {@link PartitionRefiner.MyCert} with the same value.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (this.label == null) {
return true;
}
return this.label.equals(((MyNodeCert) obj).label);
}
@Override
public String toString() {
return "c" + this.value;
}
/**
* Change the certificate value predictably to break symmetry.
*/
public void breakSymmetry() {
this.value ^= this.value << 5 ^ this.value >> 3;
}
/**
* The new value for this certificate node is the sum of the values of
* the incident certificate edges.
*/
@Override
protected int computeNewValue() {
int result = this.nextValue ^ this.value;
this.nextValue = 0;
return result;
}
/**
* Adds to the current value. Used during construction, to record the
* initial value of incident edges.
*/
protected void addValue(int inc) {
this.value += inc;
}
/**
* Adds a certain value to {@link #nextValue}.
*/
protected void addNextValue(int value) {
this.nextValue += value;
}
/**
* Signals that the certificate has become singular at a certain round.
* @param round the round at which the certificate is set to singular;
* if <code>0</code>, it is still duplicate.
*/
protected void setSingular(int round) {
this.singular = round > 0;
// this.singularRound = round;
// this.singularValue = getValue();
}
/**
* Signals if the certificate is singular or duplicate.
*/
protected boolean isSingular() {
return this.singular;
}
/** Possibly {@code null} node label. */
private final Label label;
/** The value for the next invocation of {@link #computeNewValue()} */
int nextValue;
/**
* Records if the certificate has become singular at some point of the
* calculation.
*/
boolean singular;
}
/**
* Certificate for value nodes. This takes the actual node identity into
* account.
* @author Arend Rensink
* @version $Revision $
*/
static class MyValueNodeCert extends MyNodeCert {
/**
* Constructs a new certificate node. The incidence count (i.e., the
* number of incident edges) is passed in as a parameter. The initial
* value is set to the incidence count.
*/
public MyValueNodeCert(ValueNode node) {
super(node);
this.nodeValue = node.getValue();
this.value = this.nodeValue.hashCode();
}
/**
* Returns <tt>true</tt> if <tt>obj</tt> is also a
* {@link PartitionRefiner.MyValueNodeCert} and has the same node as this one.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
return obj instanceof MyValueNodeCert
&& this.nodeValue.equals(((MyValueNodeCert) obj).nodeValue);
}
/**
* The new value for this certificate node is the sum of the values of
* the incident certificate edges.
*/
@Override
protected int computeNewValue() {
int result = this.nextValue ^ this.value;
this.nextValue = 0;
return result;
}
private final Object nodeValue;
}
/**
* An edge with certificate nodes as endpoints. The hash code is computed
* dynamically, on the basis of the current certificate node value.
* @author Arend Rensink
* @version $Revision: 5787 $
*/
static class MyEdge2Cert extends MyCert<Edge>implements EdgeCertificate {
/**
* Constructs a certificate for a binary edge.
* @param edge The target certificate node
* @param source The source certificate node
* @param target The label of the original edge
*/
public MyEdge2Cert(Edge edge, MyNodeCert source, MyNodeCert target) {
super(edge);
this.source = source;
this.target = target;
this.label = edge.label();
this.initValue = this.label.hashCode();
this.value = this.initValue;
source.addValue(this.value);
target.addValue(this.value << 1);
}
@Override
public String toString() {
return "[" + this.source + "," + this.label + "(" + this.initValue + ")," + this.target
+ "]";
}
/**
* Returns <tt>true</tt> if <tt>obj</tt> is also a
* {@link PartitionRefiner.MyEdge2Cert} and has the same value, as well as the same
* source and target values, as this one.
* @see #getValue()
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
MyEdge2Cert other = (MyEdge2Cert) obj;
if (!this.source.equals(other.source) || !this.label.equals(other.label)) {
return false;
}
if (this.target == this.source) {
return other.target == other.source;
}
return this.target.equals(other.target);
}
/**
* Computes the value on the basis of the end nodes and the label index.
*/
@Override
protected int computeNewValue() {
int targetShift = (this.initValue & 0xf) + 1;
int sourceHashCode = this.source.value;
int targetHashCode = this.target.value;
int result = ((sourceHashCode << 8) | (sourceHashCode >>> 24))
+ ((targetHashCode << targetShift) | (targetHashCode >>> targetShift)) + this.value;
this.source.nextValue += 2 * result;
this.target.nextValue -= 3 * result;
return result;
}
private final Label label;
/** The source certificate for the edge. */
private final MyNodeCert source;
/** The target certificate for the edge; may be <tt>null</tt>. */
private final MyNodeCert target;
/**
* The hash code of the original edge label.
*/
private final int initValue;
}
/**
* An edge with only one endpoint. The hash code is computed dynamically, on
* the basis of the current certificate node value.
* @author Arend Rensink
* @version $Revision: 5787 $
*/
static class MyEdge1Cert extends MyCert<Edge>implements EdgeCertificate {
/** Constructs a certificate edge for a predicate (i.e., a unary edge). */
public MyEdge1Cert(Edge edge, MyNodeCert source) {
super(edge);
this.source = source;
this.label = edge.label();
this.initValue = this.label.hashCode();
this.value = this.initValue;
source.addValue(this.value);
}
@Override
public String toString() {
return "[" + this.source + "," + this.label + "(" + this.initValue + ")]";
}
/**
* Returns <tt>true</tt> if <tt>obj</tt> is also a
* {@link PartitionRefiner.MyEdge1Cert} and has the same value, as well as the same
* source and target values, as this one.
* @see #getValue()
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
MyEdge1Cert other = (MyEdge1Cert) obj;
return this.label.equals(other.label);
}
/**
* Computes the value on the basis of the end nodes and the label index.
*/
@Override
protected int computeNewValue() {
int sourceHashCode = this.source.hashCode();
int result = (sourceHashCode << 8) + (sourceHashCode >> 24) + this.value;
// source.nextValue += result;
return result;
}
/** The source certificate for the edge. */
private final MyNodeCert source;
/** Possibly {@code null} node label. */
private final Label label;
/**
* The hash code of the original edge label.
*/
private final int initValue;
}
}
| 34.871134 | 100 | 0.559719 |
cfa8b082372d7307635b11acdd3e280a8a1bb04b | 24 | public class Exclude{
} | 8 | 21 | 0.75 |
4d437edd00b6914df7be0ff9880b628930a62460 | 1,780 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.ql.TestUtils;
import org.elasticsearch.xpack.ql.expression.Literal;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In;
import java.util.Arrays;
import static org.elasticsearch.xpack.ql.expression.Literal.NULL;
import static org.elasticsearch.xpack.ql.tree.Source.EMPTY;
public class InTests extends ESTestCase {
private static final Literal ONE = L(1);
private static final Literal TWO = L(2);
private static final Literal THREE = L(3);
public void testInWithContainedValue() {
In in = new In(EMPTY, TWO, Arrays.asList(ONE, TWO, THREE));
assertTrue(in.fold());
}
public void testInWithNotContainedValue() {
In in = new In(EMPTY, THREE, Arrays.asList(ONE, TWO));
assertFalse(in.fold());
}
public void testHandleNullOnLeftValue() {
In in = new In(EMPTY, NULL, Arrays.asList(ONE, TWO, THREE));
assertNull(in.fold());
in = new In(EMPTY, NULL, Arrays.asList(ONE, NULL, THREE));
assertNull(in.fold());
}
public void testHandleNullsOnRightValue() {
In in = new In(EMPTY, THREE, Arrays.asList(ONE, NULL, THREE));
assertTrue(in.fold());
in = new In(EMPTY, ONE, Arrays.asList(TWO, NULL, THREE));
assertNull(in.fold());
}
private static Literal L(Object value) {
return TestUtils.of(EMPTY, value);
}
}
| 33.584906 | 79 | 0.693258 |
4838e4e72b93c8b88d0f6d70c81a703b9caf1330 | 1,180 | /*
* Copyright 2020 Acoustic, L.P.
* 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
* Apache License, Version 2.0
* www.apache.org
* Home page of The Apache Software Foundation
*
* 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 co.acoustic.content.delivery.sdk;
import androidx.annotation.StringDef;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.SOURCE;
class DeliverySearchNetworkServiceConstants {
@Retention(SOURCE)
@StringDef({
TYPE_DELIVERY_SEARCH,
TYPE_MY_DELIVERY_SEARCH
})
@interface DeliveryTypes {}
static final String TYPE_DELIVERY_SEARCH = "delivery";
static final String TYPE_MY_DELIVERY_SEARCH = "mydelivery";
}
| 34.705882 | 131 | 0.752542 |
d1d62df51528c6ebc007342f32ac6273362078c1 | 1,310 | package com.slurpy.glowfighter.gui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import com.slurpy.glowfighter.Core;
import com.slurpy.glowfighter.managers.AssetManager.FontAsset;
import com.slurpy.glowfighter.utils.Util;
public class Label {
private String text;
public final Position position;
private float fontW, fontH;
public final Color color;
private float size;
public Label(String text, Position position, Color color, float size) {
this.text = text;
this.position = position;
Vector2 fontSize = Util.getTextSize(FontAsset.CatV, text, size);
fontW = fontSize.x;
fontH = fontSize.y;
this.color = color.cpy();
this.size = size;
}
public void draw(){
if(color.a == 0f)return;
Vector2 pos = position.getPosition();
pos.sub(fontW/2, -fontH/2);
Core.graphics.drawText(text, pos, size, color);
}
public void setText(String text, float size){
if(text == this.text && size == this.size)return;
this.text = text;
this.size = size;
Vector2 fontSize = Util.getTextSize(FontAsset.CatV, text, size);
fontW = fontSize.x;
fontH = fontSize.y;
}
public String getText(){
return text;
}
public float getFontW() {
return fontW;
}
public float getFontH() {
return fontH;
}
public float getSize() {
return size;
}
}
| 22.586207 | 72 | 0.709924 |
64ee8e71105846080292d5f0551f8644499cfa75 | 339 | package com.ctrip.xpipe.simple;
import java.net.InetSocketAddress;
import org.junit.Test;
/**
* @author shyin
*
* Dec 22, 2016
*/
public class InetSocketAddressTest {
@Test
public void test() {
System.out.println(new InetSocketAddress("0.0.0.0", 0));
System.out.println(InetSocketAddress.createUnresolved("0.0.0.0", 0));
}
}
| 17.842105 | 71 | 0.705015 |
cd464df130ef963bdf6ff4482e7d82d48afdeb4c | 7,135 | package com.jianpan.myrecord.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import com.jianpan.myrecord.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 键盘 on 2016/5/22.
*/
public class RippleDiffuse extends ViewGroup implements View.OnTouchListener{
private static final int ANIMATION_EACH_OFFSET = 800; // 每个动画的播放时间间隔
private static final int RIPPLE_VIEW_COUNT = 3;//波纹view的个数
private static final float DEFAULT_SCALE = 1.6f;//波纹放大后的大小
//点击有扩散效果的view
private CircleImageView mBtnImg;
private int mBtnViewHeight;
private int mBtnViewWidth;
private float mScale = DEFAULT_SCALE;
//图片资源
private int mBtnImgRes;
private int mRippleRes;
//是否初始化完成
private boolean mInitDataSucceed = false;
private OnTouchListener mBtnOnTouchListener;
private List<CircleImageView> mWaves = new ArrayList<>();
private List<AnimationSet> mAnimas = new ArrayList<>();
public RippleDiffuse(Context context) {
this(context, null);
}
public RippleDiffuse(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RippleDiffuse(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(context, attrs);
}
private void initAttrs(Context context, AttributeSet attributeSet){
if (attributeSet != null){
TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.RippleDiffuse);
mScale = typedArray.getFloat(R.styleable.RippleDiffuse_rd_scale, DEFAULT_SCALE);
mBtnImgRes = typedArray.getResourceId(R.styleable.RippleDiffuse_btn_img_res, 0);
mRippleRes = typedArray.getResourceId(R.styleable.RippleDiffuse_ripple_img_res, 0);
typedArray.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
if (!mInitDataSucceed){
initData();
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
private void initData(){
if (getMeasuredHeight() > 0 && getMeasuredWidth() > 0){
mInitDataSucceed = true;
int height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
int width = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
mBtnViewHeight = (int) (height / mScale);
mBtnViewWidth = (int) (width / mScale);
mBtnImg = new CircleImageView(getContext());
mBtnImg.setImageResource(mBtnImgRes);
mBtnImg.setOnTouchListener(this);
addView(mBtnImg, getWaveLayoutParams());
for (int i = 0; i < RIPPLE_VIEW_COUNT; i++){
//创建view
CircleImageView wave = createWave();
mWaves.add(wave);
//创建动画
mAnimas.add(getNewAnimationSet());
addView(wave, 0, getWaveLayoutParams());
}
}
}
private CircleImageView createWave(){
CircleImageView CircleImageView = new CircleImageView(getContext());
CircleImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
CircleImageView.setImageResource(mRippleRes);
return CircleImageView;
}
private LayoutParams getWaveLayoutParams(){
LayoutParams lp = new LayoutParams(mBtnViewWidth, mBtnViewHeight);
return lp;
}
private AnimationSet getNewAnimationSet() {
AnimationSet as = new AnimationSet(true);
ScaleAnimation sa = new ScaleAnimation(1f, mScale, 1f, mScale,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
sa.setDuration(ANIMATION_EACH_OFFSET * 3);
sa.setRepeatCount(-1);// 设置循环
AlphaAnimation aniAlp = new AlphaAnimation(1, 0.1f);
aniAlp.setRepeatCount(-1);// 设置循环
as.setDuration(ANIMATION_EACH_OFFSET * 3);
as.addAnimation(sa);
as.addAnimation(aniAlp);
return as;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (mInitDataSucceed) {
int childLeft = (getMeasuredWidth() - mBtnViewWidth) / 2;
int childTop = (getMeasuredHeight() - mBtnViewHeight) / 2;
for (int i = 0; i < RIPPLE_VIEW_COUNT; i++) {
CircleImageView wave = mWaves.get(i);
wave.layout(childLeft, childTop, mBtnViewWidth + childLeft, mBtnViewHeight + childTop);
}
mBtnImg.layout(childLeft, childTop, mBtnViewWidth + childLeft, mBtnViewHeight + childTop);
}else {
initData();
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
showWaveAnimation();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
cancelWaveAnimation();
break;
}
if (mBtnOnTouchListener != null){
boolean flag = mBtnOnTouchListener.onTouch(v, event);
if (!flag){
cancelWaveAnimation();
return false;
}
}
return true;
}
private void showWaveAnimation() {
for (int i = 0; i < RIPPLE_VIEW_COUNT; i++){
Message message = new Message();
message.obj = i;
handler.sendMessageDelayed(message, ANIMATION_EACH_OFFSET * i);
}
}
private void cancelWaveAnimation() {
for (int i = 0; i < RIPPLE_VIEW_COUNT; i++){
handler.removeMessages(i);
CircleImageView wave = mWaves.get(i);
wave.clearAnimation();
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int position = (int) msg.obj;
CircleImageView wave = mWaves.get(position);
wave.startAnimation(mAnimas.get(position));
super.handleMessage(msg);
}
};
public void setScale(float scale){
this.mScale = scale;
}
public void setBtnImgRes(int res){
mBtnImgRes = res;
}
public void setRippleRes(int rippleRes){
mRippleRes = rippleRes;
}
public void setBtnOnTouchListener(OnTouchListener onTouchListener){
mBtnOnTouchListener = onTouchListener;
}
}
| 32.579909 | 108 | 0.632796 |
6e3a892bddec60cb468abd17f776857dbfd4c984 | 158 | package befunge98_gui_glimmer_dsl_swt;
/** The soul purpose of this class is to retrieve icons for uri:classloader paths used from JAR */
class Resource {
}
| 26.333333 | 98 | 0.78481 |
906bdc4020b93c5045b2f799c2fc2dd2daa0607a | 1,755 | package com.eltechs.axs.widgets.touchScreenControlsOverlay;
import android.view.View;
import com.eltechs.axs.TouchScreenControlsFactory;
import com.eltechs.axs.activities.XServerDisplayActivity;
import com.eltechs.axs.activities.XServerDisplayActivityInterfaceOverlay;
import com.eltechs.axs.configuration.TouchScreenControlsInputConfiguration;
import com.eltechs.axs.widgets.actions.Action;
import com.eltechs.axs.widgets.viewOfXServer.ViewOfXServer;
import java.util.Collections;
import java.util.List;
public class TouchScreenControlsOverlay implements XServerDisplayActivityInterfaceOverlay {
private final TouchScreenControlsInputConfiguration configuration;
private final TouchScreenControlsFactory controlsFactory;
private List<? extends Action> popupMenuItems = Collections.emptyList();
private TouchScreenControlsWidget widget;
public TouchScreenControlsOverlay(TouchScreenControlsFactory touchScreenControlsFactory, TouchScreenControlsInputConfiguration touchScreenControlsInputConfiguration) {
this.controlsFactory = touchScreenControlsFactory;
this.configuration = touchScreenControlsInputConfiguration;
}
public void setPopupMenuItems(List<? extends Action> list) {
this.popupMenuItems = list;
}
public View attach(XServerDisplayActivity xServerDisplayActivity, ViewOfXServer viewOfXServer) {
this.widget = new TouchScreenControlsWidget(xServerDisplayActivity, viewOfXServer, this.controlsFactory, this.configuration);
this.widget.setZOrderMediaOverlay(true);
xServerDisplayActivity.addDefaultPopupMenu(this.popupMenuItems);
return this.widget;
}
public void detach() {
this.widget.detach();
this.widget = null;
}
}
| 43.875 | 171 | 0.805698 |
88275a1007be0747dd73cda2fc5e19c3b6e55b15 | 982 | package net.bootsfaces.themes;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class Theme implements Serializable {
private static final long serialVersionUID = 1L;
private String currentTheme="default";
private String internalTheme="default";
private String customTheme="";
public String getCurrentTheme() {
return currentTheme;
}
public String getInternalTheme() {
return internalTheme;
}
public String getCustomTheme() {
return customTheme;
}
public void setCurrentTheme(String currentTheme) {
this.currentTheme = currentTheme;
if (currentTheme.equalsIgnoreCase("Freelancer")) {
internalTheme="other";
customTheme=currentTheme;
} else if (currentTheme.equalsIgnoreCase("Grayscale")) {
internalTheme="other";
customTheme=currentTheme;
} else {
internalTheme = currentTheme;
customTheme="";
}
}
public void selectTheme() {
}
}
| 20.893617 | 58 | 0.750509 |
fbb9684b1514064026915190157bc1f1d956e2c5 | 608 | // Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
package com.alcatel.as.service.concurrent.impl;
/**
* Defines the supported PlatformExecutor schedule priorities.
*/
public enum TaskPriority {
/**
* The task must be scheduled on one executor, using the DEFAULT priority.
* DEFAULT priority tasks are executed after all HIGH priority tasks.
*/
DEFAULT,
/**
* The task must be scheduled in one executor, using the HIGH priority.
* HIGH priority tasks are executed before any DEFAULT priority tasks.
*/
HIGH,
}
| 24.32 | 76 | 0.713816 |
3ed7a0c77e90b01179094bdfa4a727f0b938a0f3 | 1,005 | class lab70 implements Runnable
{
public void run()
{
Thread t = Thread.currentThread();
System.out.println(t.currentThread()+" started execution ");
for (int i=0;i<5 ;i++ )
{
try
{
System.out.println(Thread.currentThread()+" is printing"+ i);
t.sleep(1000);
}
catch(InterruptedException ie)
{System.out.println(Thread.currentThread()+"is interupted");}
}
System.out.println(Thread.currentThread()+" has been completed ");
}
public static void main(String[] args)
{
lab70 td = new lab70();
Thread tchild = new Thread(td,"child thread");
tchild.start();
Thread tmain = Thread.currentThread();
tmain.setName("Main thread ");
for (int i=0;i<5;i++ )
{
try
{
System.out.println(Thread.currentThread()+" is printing " + i);
tmain.sleep(2000);
}
catch(InterruptedException ie)
{ System.out.println(Thread.currentThread()+"has been interupted");}
}
System.out.println(Thread.currentThread()+ " has completed execution");
}
} | 25.769231 | 73 | 0.655721 |
e66b36f5736909f431b23f2d36672ab9befddcdb | 440 | package game_engine.level;
import game_engine.Component;
/**
*
* @author Andy Nguyen, Jeremy Chen, Kevin Deng, Ben Hubsch
* The purpose of this class is to allow Levels to have a height attribute
*
*/
public class LevelHeightComponent extends Component<Double>{
/**
* instantiates a new LevelHeightComponent with the value for the Level's height
* @param val
*/
public LevelHeightComponent(Double val) {
super(val);
}
}
| 20.952381 | 81 | 0.729545 |
0e4c9da34cb421c09f035e4f92dee95ecd518249 | 4,000 | package jet.learning.opengl.samples;
import android.opengl.GLES20;
import com.nvidia.developer.opengl.app.NvSampleApp;
import com.nvidia.developer.opengl.utils.GLES;
import com.nvidia.developer.opengl.utils.GLUtil;
import com.nvidia.developer.opengl.utils.Glut;
import com.nvidia.developer.opengl.utils.NvGLSLProgram;
import org.lwjgl.util.vector.Matrix4f;
/**
* Created by mazhen'gui on 2018/2/10.
*/
public final class ContourDemo extends NvSampleApp {
// Shader-related variables
private int textureID;
private int quadVBO;
NvGLSLProgram programObj;
NvGLSLProgram[] programObjs = new NvGLSLProgram[4];
private final Matrix4f mProj = new Matrix4f();
private final Matrix4f mView = new Matrix4f();
@Override
protected void initRendering() {
// Load textures
// The special shader used to render this texture performs its own minification
// and magnification. Specify nearest neighbor sampling to avoid trampling
// over the distance values split over two channels as 8.8 fixed-point data.
textureID = Glut.loadTextureFromFile("textures/disttex.png", GLES20.GL_NEAREST, GLES20.GL_CLAMP_TO_EDGE);
int texw = 512;
int texh = 512;
// Create, load and compile the shader programs
programObjs[0] = NvGLSLProgram.createFromFiles("shaders/vertex.glsl", "shaders/fragment1.glsl");
programObjs[1] = NvGLSLProgram.createFromFiles("shaders/vertex.glsl", "shaders/fragment2.glsl");
programObjs[2] = NvGLSLProgram.createFromFiles("shaders/vertex.glsl", "shaders/fragment3.glsl");
programObjs[3] = NvGLSLProgram.createFromFiles("shaders/vertex.glsl", "shaders/fragment4.glsl");
for(int i = 0; i < programObjs.length; i++){
programObjs[i].enable();
programObjs[i].setUniform1i("disttex", 0);
programObjs[i].setUniform1f("oneu", 1.f/texw);
programObjs[i].setUniform1f("onev", 1.f/texh);
programObjs[i].setUniform1f("texw", texw);
programObjs[i].setUniform1f("texh", texh);
}
programObj = programObjs[0];
float size = 5;
float[] verts = {
-size, -size, 0, 0,0,
+size, -size, 0, 1,0,
-size, +size, 0, 0,1,
+size, +size, 0, 1,1,
};
quadVBO = GLES.glGenBuffers();
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, quadVBO);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, verts.length * 4, GLUtil.wrap(verts), GLES20.GL_STATIC_DRAW);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
m_transformer.setTranslation(0,0, -10);
}
@Override
protected void draw() {
m_transformer.getModelViewMat(mView);
GLES20.glClearColor(0,0,0,0);
GLES20.glClearDepthf(1.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT|GLES20.GL_DEPTH_BUFFER_BIT);
Matrix4f.mul(mProj, mView, mView);
programObj.enable();
programObj.setUniformMatrix4("g_MVP", mView);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, quadVBO);
int position = programObj.getAttribLocation("In_Position");
int texcoord = programObj.getAttribLocation("In_Texcoord");
GLES20.glEnableVertexAttribArray(position);
GLES20.glVertexAttribPointer(position, 3, GLES20.GL_FLOAT, false, 20, 0 );
GLES20.glEnableVertexAttribArray(texcoord);
GLES20.glVertexAttribPointer(texcoord, 2, GLES20.GL_FLOAT, false, 20, 12 );
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDisableVertexAttribArray(position);
GLES20.glDisableVertexAttribArray(texcoord);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
}
@Override
protected void reshape(int width, int height) {
Matrix4f.perspective(60, (float)width/height, 0.1f, 1000.0f, mProj);
}
}
| 37.037037 | 113 | 0.6745 |
52b095282bfcd071dfe6375f2046b65edb2677d0 | 2,158 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.mongo.v3_1;
import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.DB_MONGODB_COLLECTION;
import static java.util.Arrays.asList;
import com.mongodb.event.CommandStartedEvent;
import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import org.bson.BsonValue;
class MongoAttributesExtractor implements AttributesExtractor<CommandStartedEvent, Void> {
@Override
public void onStart(AttributesBuilder attributes, CommandStartedEvent event) {
set(attributes, DB_MONGODB_COLLECTION, collectionName(event));
}
@Override
public void onEnd(
AttributesBuilder attributes,
CommandStartedEvent event,
@Nullable Void unused,
@Nullable Throwable error) {}
@Nullable
String collectionName(CommandStartedEvent event) {
if (event.getCommandName().equals("getMore")) {
BsonValue collectionValue = event.getCommand().get("collection");
if (collectionValue != null) {
if (collectionValue.isString()) {
return collectionValue.asString().getValue();
}
}
} else if (COMMANDS_WITH_COLLECTION_NAME_AS_VALUE.contains(event.getCommandName())) {
BsonValue commandValue = event.getCommand().get(event.getCommandName());
if (commandValue != null && commandValue.isString()) {
return commandValue.asString().getValue();
}
}
return null;
}
private static final Set<String> COMMANDS_WITH_COLLECTION_NAME_AS_VALUE =
new HashSet<>(
asList(
"aggregate",
"count",
"distinct",
"mapReduce",
"geoSearch",
"delete",
"find",
"killCursors",
"findAndModify",
"insert",
"update",
"create",
"drop",
"createIndexes",
"listIndexes"));
}
| 31.275362 | 97 | 0.662651 |
c47d81974f875d8770512afbd4387115be23090a | 2,106 | package com.company.project.controller;
import com.company.project.common.aop.annotation.LogAnnotation;
import com.company.project.common.utils.NumberConstants;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import io.swagger.annotations.ApiOperation;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.TaskRewardSettingsEntity;
import com.company.project.service.TaskRewardSettingsService;
import javax.annotation.Resource;
import java.util.List;
/**
* 任务奖励设置
*
* @author zhoushuai
* @email [email protected]
* @date 2021-07-13 17:59:56
*/
@Api(tags = "任务奖励设置")
@Controller
@RequestMapping("/")
public class TaskRewardSettingsController extends BaseController {
@Resource
private TaskRewardSettingsService taskRewardSettingsService;
@ApiOperation(value = "跳转进入任务奖励设置页面")
@RequiresPermissions("taskRewardSettings:list")
@GetMapping("/index/taskRewardSettings")
public String taskRewardSettings(Model model) {
List<TaskRewardSettingsEntity> taskRewardSettingsEntityList = taskRewardSettingsService.list();
model.addAttribute("taskRewardSettingsEntity", CollectionUtils.isNotEmpty(taskRewardSettingsEntityList) ? taskRewardSettingsEntityList.get(NumberConstants.ZERO) : new TaskRewardSettingsEntity());
return "member/taskRewardSettings";
}
@ApiOperation(value = "新增/修改")
@PostMapping("taskRewardSettings/addOrUpdate")
@RequiresPermissions(value = {"taskRewardSettings:add", "taskRewardSettings:update"}, logical = Logical.OR)
@LogAnnotation(title = "任务奖励设置", action = "新增/修改")
@ResponseBody
public DataResult addOrUpdate(@RequestBody TaskRewardSettingsEntity taskRewardSettings){
return DataResult.success(taskRewardSettingsService.saveOrUpdate(taskRewardSettings));
}
}
| 36.947368 | 203 | 0.792498 |
e393bb7446ffe0a23a9a6374b5566ed5a3af380a | 903 | /*
* Copyright (c) 2014, Isode Limited, London, England.
* All rights reserved.
*/
/*
* Copyright (c) 2014, Remko Tronçon.
* All rights reserved.
*/
package com.isode.stroke.elements;
import java.util.ArrayList;
import com.isode.stroke.elements.PubSubOwnerPayload;
public class PubSubOwnerSubscriptions extends PubSubOwnerPayload {
public PubSubOwnerSubscriptions() {
}
public ArrayList<PubSubOwnerSubscription> getSubscriptions() {
return subscriptions_;
}
public void setSubscriptions(ArrayList<PubSubOwnerSubscription> subscriptions) {
subscriptions_ = subscriptions;
}
public void addSubscription(PubSubOwnerSubscription value) {
subscriptions_.add(value);
}
public String getNode() {
return node_;
}
public void setNode(String node) {
node_ = node;
}
private ArrayList<PubSubOwnerSubscription> subscriptions_ = new ArrayList<PubSubOwnerSubscription>();
private String node_ = "";
}
| 20.522727 | 101 | 0.781838 |
9bc5b573724149412de5c161882e1e334e9fcd7a | 4,470 | package com.example.selfunction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.selfunction.databinding.ActivitySelLocationBinding;
import java.net.URLDecoder;
public class SelLocationActivity extends AppCompatActivity {
private String address = "";
private String latng;
private String TAG = "SelLocationActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivitySelLocationBinding binding = ActivitySelLocationBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
TextView tv_confrim = findViewById(R.id.tv_confrim);
WebView mWebView = findViewById(R.id.web_view);
String title = getIntent().getStringExtra("title");
int bgColor = getIntent().getIntExtra("bgColor",getResources().getColor(R.color.blue));
int textColor = getIntent().getIntExtra("textColor",getResources().getColor(R.color.white));
binding.rlTitle.setBackgroundColor(bgColor);
binding.tvConfrim.setTextColor(textColor);
binding.tvTitle.setTextColor(textColor);
if(null != title) {
binding.tvTitle.setText(title);
}
String mUrl = "https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=http://callback&key=QULBZ-6M6KO-5YZWR-SEYTJ-GNNS5-O6B3L&referer=myapp";
WebSettings settings = mWebView.getSettings();
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setSupportMultipleWindows(true);
settings.setJavaScriptEnabled(true);
settings.setSavePassword(false);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
settings.setAllowFileAccess(false);
settings.setTextSize(WebSettings.TextSize.NORMAL);
mWebView.setVerticalScrollbarOverlay(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!url.startsWith("http://callback")) {
view.loadUrl(url);
} else {
try {
Log.e(TAG,url);
//转utf-8编码
String decode = URLDecoder.decode(url, "UTF-8");
Log.e(TAG,decode);
//转uri,然后根据key取值
Uri uri = Uri.parse(decode);
//纬度在前,经度在后,以逗号分隔
latng = uri.getQueryParameter("latng");
String[] split = latng.split(",");
String lat = split[0];//纬度
String lng = split[1];//经度
//地址
address = uri.getQueryParameter("addr");
String name = uri.getQueryParameter("name");
address = address+name;
// uri.getQueryParameter("addr");
Log.e("地址", address);
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
});
mWebView.loadUrl(mUrl);
tv_confrim.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(null == address){
Toast.makeText(SelLocationActivity.this, "请选择位置", Toast.LENGTH_SHORT).show();
return;
}
if(!TextUtils.isEmpty(address)){
Intent intent = new Intent();
Log.e("点击了",address);
intent.putExtra("address", address);
intent.putExtra("latng", latng);
setResult(200, intent);
finish();
}else{
Toast.makeText(SelLocationActivity.this, "请选择位置", Toast.LENGTH_SHORT).show();
}
}
});
}
} | 38.534483 | 158 | 0.576734 |
184191ff3cd5069c816cf3c2ffe4696d85eaa60d | 2,799 | package xreliquary.entities;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.IRendersAsItem;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.ThrowableEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.network.IPacket;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.math.EntityRayTraceResult;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.network.NetworkHooks;
import xreliquary.init.ModEntities;
import xreliquary.init.ModItems;
@SuppressWarnings("squid:S2160")
@OnlyIn(
value = Dist.CLIENT,
_interface = IRendersAsItem.class
)
public class HolyHandGrenadeEntity extends ThrowableEntity implements IRendersAsItem {
private int count = 0;
private PlayerEntity playerThrower;
public HolyHandGrenadeEntity(EntityType<HolyHandGrenadeEntity> entityType, World world) {
super(entityType, world);
}
public HolyHandGrenadeEntity(World world, PlayerEntity player, String customName) {
super(ModEntities.HOLY_HAND_GRENADE, player, world);
playerThrower = player;
setCustomName(new StringTextComponent(customName));
}
public HolyHandGrenadeEntity(World world, double x, double y, double z) {
super(ModEntities.HOLY_HAND_GRENADE, x, y, z, world);
}
/**
* Gets the amount of gravity to apply to the thrown entity with each tick.
*/
@Override
protected float getGravityVelocity() {
return 0.03F;
}
@Override
protected void registerData() {
//noop
}
@Override
public void tick() {
super.tick();
if (count == 2) {
for (int particles = 0; particles < rand.nextInt(2) + 1; particles++) {
world.addParticle(ParticleTypes.ENTITY_EFFECT, getPosX() + world.rand.nextDouble(), getPosY() + world.rand.nextDouble(), getPosZ() + world.rand.nextDouble(), 0D, 0D, 0D);
}
count = 0;
} else {
count++;
}
}
/**
* Called when this EntityThrowable hits a block or entity.
*/
@Override
protected void onImpact(RayTraceResult result) {
if (world.isRemote) {
return;
}
remove();
//just making sure that player doesn't see the particles on client when the grenade is thrown
if (ticksExisted > 3 || result.getType() != RayTraceResult.Type.ENTITY || !(((EntityRayTraceResult) result).getEntity() instanceof PlayerEntity)) {
ConcussiveExplosion.grenadeConcussiveExplosion(this, playerThrower, getPositionVec());
}
}
@Override
public ItemStack getItem() {
return new ItemStack(ModItems.HOLY_HAND_GRENADE);
}
@Override
public IPacket<?> createSpawnPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
}
| 28.85567 | 174 | 0.7592 |
4c46b2c9bedc7920ff9a45f5b5c1316ab1671869 | 22,971 | /* This file was generated by SableCC's ObjectMacro. */
package org.sablecc.objectmacro.codegeneration.java.macro;
class InternalsInitializer {
private final String _paramName;
InternalsInitializer(
String paramName) {
this._paramName = paramName;
}
void setHeader(
MHeader mHeader) {
throw ObjectMacroException.incorrectType("MHeader", this._paramName);
}
void setPackageDeclaration(
MPackageDeclaration mPackageDeclaration) {
throw ObjectMacroException.incorrectType("MPackageDeclaration",
this._paramName);
}
void setImportJavaUtil(
MImportJavaUtil mImportJavaUtil) {
throw ObjectMacroException.incorrectType("MImportJavaUtil",
this._paramName);
}
void setContext(
MContext mContext) {
throw ObjectMacroException.incorrectType("MContext", this._paramName);
}
void setInternalsInitializer(
MInternalsInitializer mInternalsInitializer) {
throw ObjectMacroException.incorrectType("MInternalsInitializer",
this._paramName);
}
void setParentInternalsSetter(
MParentInternalsSetter mParentInternalsSetter) {
throw ObjectMacroException.incorrectType("MParentInternalsSetter",
this._paramName);
}
void setCycleDetectorClass(
MCycleDetectorClass mCycleDetectorClass) {
throw ObjectMacroException.incorrectType("MCycleDetectorClass",
this._paramName);
}
void setSuperMacro(
MSuperMacro mSuperMacro) {
throw ObjectMacroException.incorrectType("MSuperMacro",
this._paramName);
}
void setSuperDirective(
MSuperDirective mSuperDirective) {
throw ObjectMacroException.incorrectType("MSuperDirective",
this._paramName);
}
void setClassValue(
MClassValue mClassValue) {
throw ObjectMacroException.incorrectType("MClassValue",
this._paramName);
}
void setClassMacroValue(
MClassMacroValue mClassMacroValue) {
throw ObjectMacroException.incorrectType("MClassMacroValue",
this._paramName);
}
void setClassStringValue(
MClassStringValue mClassStringValue) {
throw ObjectMacroException.incorrectType("MClassStringValue",
this._paramName);
}
void setClassCacheBuilder(
MClassCacheBuilder mClassCacheBuilder) {
throw ObjectMacroException.incorrectType("MClassCacheBuilder",
this._paramName);
}
void setVersionEnumeration(
MVersionEnumeration mVersionEnumeration) {
throw ObjectMacroException.incorrectType("MVersionEnumeration",
this._paramName);
}
void setMacroFactory(
MMacroFactory mMacroFactory) {
throw ObjectMacroException.incorrectType("MMacroFactory",
this._paramName);
}
void setMacroCreatorMethod(
MMacroCreatorMethod mMacroCreatorMethod) {
throw ObjectMacroException.incorrectType("MMacroCreatorMethod",
this._paramName);
}
void setSwitchVersion(
MSwitchVersion mSwitchVersion) {
throw ObjectMacroException.incorrectType("MSwitchVersion",
this._paramName);
}
void setMacroCaseInit(
MMacroCaseInit mMacroCaseInit) {
throw ObjectMacroException.incorrectType("MMacroCaseInit",
this._paramName);
}
void setVersion(
MVersion mVersion) {
throw ObjectMacroException.incorrectType("MVersion", this._paramName);
}
void setMacro(
MMacro mMacro) {
throw ObjectMacroException.incorrectType("MMacro", this._paramName);
}
void setAppliedVersion(
MAppliedVersion mAppliedVersion) {
throw ObjectMacroException.incorrectType("MAppliedVersion",
this._paramName);
}
void setConstructor(
MConstructor mConstructor) {
throw ObjectMacroException.incorrectType("MConstructor",
this._paramName);
}
void setInitInternal(
MInitInternal mInitInternal) {
throw ObjectMacroException.incorrectType("MInitInternal",
this._paramName);
}
void setInitParam(
MInitParam mInitParam) {
throw ObjectMacroException.incorrectType("MInitParam", this._paramName);
}
void setInitMacroValue(
MInitMacroValue mInitMacroValue) {
throw ObjectMacroException.incorrectType("MInitMacroValue",
this._paramName);
}
void setInitStringValue(
MInitStringValue mInitStringValue) {
throw ObjectMacroException.incorrectType("MInitStringValue",
this._paramName);
}
void setSetMacrosCall(
MSetMacrosCall mSetMacrosCall) {
throw ObjectMacroException.incorrectType("MSetMacrosCall",
this._paramName);
}
void setSuperCall(
MSuperCall mSuperCall) {
throw ObjectMacroException.incorrectType("MSuperCall", this._paramName);
}
void setAddMacroCall(
MAddMacroCall mAddMacroCall) {
throw ObjectMacroException.incorrectType("MAddMacroCall",
this._paramName);
}
void setAddStringCall(
MAddStringCall mAddStringCall) {
throw ObjectMacroException.incorrectType("MAddStringCall",
this._paramName);
}
void setSingleMacroAdd(
MSingleMacroAdd mSingleMacroAdd) {
throw ObjectMacroException.incorrectType("MSingleMacroAdd",
this._paramName);
}
void setSingleStringAdd(
MSingleStringAdd mSingleStringAdd) {
throw ObjectMacroException.incorrectType("MSingleStringAdd",
this._paramName);
}
void setAddAllMacro(
MAddAllMacro mAddAllMacro) {
throw ObjectMacroException.incorrectType("MAddAllMacro",
this._paramName);
}
void setAddAllString(
MAddAllString mAddAllString) {
throw ObjectMacroException.incorrectType("MAddAllString",
this._paramName);
}
void setTypeVerifier(
MTypeVerifier mTypeVerifier) {
throw ObjectMacroException.incorrectType("MTypeVerifier",
this._paramName);
}
void setAbstractTypeVerifier(
MAbstractTypeVerifier mAbstractTypeVerifier) {
throw ObjectMacroException.incorrectType("MAbstractTypeVerifier",
this._paramName);
}
void setFactoryComparison(
MFactoryComparison mFactoryComparison) {
throw ObjectMacroException.incorrectType("MFactoryComparison",
this._paramName);
}
void setIsBuilt(
MIsBuilt mIsBuilt) {
throw ObjectMacroException.incorrectType("MIsBuilt", this._paramName);
}
void setDirectiveApplier(
MDirectiveApplier mDirectiveApplier) {
throw ObjectMacroException.incorrectType("MDirectiveApplier",
this._paramName);
}
void setNoneDirective(
MNoneDirective mNoneDirective) {
throw ObjectMacroException.incorrectType("MNoneDirective",
this._paramName);
}
void setDirectivesInitVerification(
MDirectivesInitVerification mDirectivesInitVerification) {
throw ObjectMacroException.incorrectType("MDirectivesInitVerification",
this._paramName);
}
void setParamMacroRefBuilder(
MParamMacroRefBuilder mParamMacroRefBuilder) {
throw ObjectMacroException.incorrectType("MParamMacroRefBuilder",
this._paramName);
}
void setInternalMacroRefBuilder(
MInternalMacroRefBuilder mInternalMacroRefBuilder) {
throw ObjectMacroException.incorrectType("MInternalMacroRefBuilder",
this._paramName);
}
void setInternalMacroSetter(
MInternalMacroSetter mInternalMacroSetter) {
throw ObjectMacroException.incorrectType("MInternalMacroSetter",
this._paramName);
}
void setParamMacroRef(
MParamMacroRef mParamMacroRef) {
throw ObjectMacroException.incorrectType("MParamMacroRef",
this._paramName);
}
void setInternalMacroRef(
MInternalMacroRef mInternalMacroRef) {
throw ObjectMacroException.incorrectType("MInternalMacroRef",
this._paramName);
}
void setParamStringRef(
MParamStringRef mParamStringRef) {
throw ObjectMacroException.incorrectType("MParamStringRef",
this._paramName);
}
void setParamStringRefBuilder(
MParamStringRefBuilder mParamStringRefBuilder) {
throw ObjectMacroException.incorrectType("MParamStringRefBuilder",
this._paramName);
}
void setInternalStringRef(
MInternalStringRef mInternalStringRef) {
throw ObjectMacroException.incorrectType("MInternalStringRef",
this._paramName);
}
void setInternalStringRefBuilder(
MInternalStringRefBuilder mInternalStringRefBuilder) {
throw ObjectMacroException.incorrectType("MInternalStringRefBuilder",
this._paramName);
}
void setInternalStringSetter(
MInternalStringSetter mInternalStringSetter) {
throw ObjectMacroException.incorrectType("MInternalStringSetter",
this._paramName);
}
void setInitInternalsMethod(
MInitInternalsMethod mInitInternalsMethod) {
throw ObjectMacroException.incorrectType("MInitInternalsMethod",
this._paramName);
}
void setInitDirectives(
MInitDirectives mInitDirectives) {
throw ObjectMacroException.incorrectType("MInitDirectives",
this._paramName);
}
void setNewDirective(
MNewDirective mNewDirective) {
throw ObjectMacroException.incorrectType("MNewDirective",
this._paramName);
}
void setSetMacrosMethod(
MSetMacrosMethod mSetMacrosMethod) {
throw ObjectMacroException.incorrectType("MSetMacrosMethod",
this._paramName);
}
void setMacroBuilder(
MMacroBuilder mMacroBuilder) {
throw ObjectMacroException.incorrectType("MMacroBuilder",
this._paramName);
}
void setInitDirectiveCall(
MInitDirectiveCall mInitDirectiveCall) {
throw ObjectMacroException.incorrectType("MInitDirectiveCall",
this._paramName);
}
void setInitInternalsCall(
MInitInternalsCall mInitInternalsCall) {
throw ObjectMacroException.incorrectType("MInitInternalsCall",
this._paramName);
}
void setAbstractBuilder(
MAbstractBuilder mAbstractBuilder) {
throw ObjectMacroException.incorrectType("MAbstractBuilder",
this._paramName);
}
void setEmptyBuilderWithContext(
MEmptyBuilderWithContext mEmptyBuilderWithContext) {
throw ObjectMacroException.incorrectType("MEmptyBuilderWithContext",
this._paramName);
}
void setContextCacheBuilder(
MContextCacheBuilder mContextCacheBuilder) {
throw ObjectMacroException.incorrectType("MContextCacheBuilder",
this._paramName);
}
void setNewCacheBuilder(
MNewCacheBuilder mNewCacheBuilder) {
throw ObjectMacroException.incorrectType("MNewCacheBuilder",
this._paramName);
}
void setRedefinedApplyInitializer(
MRedefinedApplyInitializer mRedefinedApplyInitializer) {
throw ObjectMacroException.incorrectType("MRedefinedApplyInitializer",
this._paramName);
}
void setParamMacroField(
MParamMacroField mParamMacroField) {
throw ObjectMacroException.incorrectType("MParamMacroField",
this._paramName);
}
void setParamStringField(
MParamStringField mParamStringField) {
throw ObjectMacroException.incorrectType("MParamStringField",
this._paramName);
}
void setInternalMacroField(
MInternalMacroField mInternalMacroField) {
throw ObjectMacroException.incorrectType("MInternalMacroField",
this._paramName);
}
void setInternalStringField(
MInternalStringField mInternalStringField) {
throw ObjectMacroException.incorrectType("MInternalStringField",
this._paramName);
}
void setContextField(
MContextField mContextField) {
throw ObjectMacroException.incorrectType("MContextField",
this._paramName);
}
void setMacroValueField(
MMacroValueField mMacroValueField) {
throw ObjectMacroException.incorrectType("MMacroValueField",
this._paramName);
}
void setStringValueField(
MStringValueField mStringValueField) {
throw ObjectMacroException.incorrectType("MStringValueField",
this._paramName);
}
void setDirectiveFields(
MDirectiveFields mDirectiveFields) {
throw ObjectMacroException.incorrectType("MDirectiveFields",
this._paramName);
}
void setApplyInternalsInitializer(
MApplyInternalsInitializer mApplyInternalsInitializer) {
throw ObjectMacroException.incorrectType("MApplyInternalsInitializer",
this._paramName);
}
void setRedefinedInternalsSetter(
MRedefinedInternalsSetter mRedefinedInternalsSetter) {
throw ObjectMacroException.incorrectType("MRedefinedInternalsSetter",
this._paramName);
}
void setStringPart(
MStringPart mStringPart) {
throw ObjectMacroException.incorrectType("MStringPart",
this._paramName);
}
void setEolPart(
MEolPart mEolPart) {
throw ObjectMacroException.incorrectType("MEolPart", this._paramName);
}
void setParamInsertPart(
MParamInsertPart mParamInsertPart) {
throw ObjectMacroException.incorrectType("MParamInsertPart",
this._paramName);
}
void setIndentPart(
MIndentPart mIndentPart) {
throw ObjectMacroException.incorrectType("MIndentPart",
this._paramName);
}
void setInsertMacroPart(
MInsertMacroPart mInsertMacroPart) {
throw ObjectMacroException.incorrectType("MInsertMacroPart",
this._paramName);
}
void setInitStringBuilder(
MInitStringBuilder mInitStringBuilder) {
throw ObjectMacroException.incorrectType("MInitStringBuilder",
this._paramName);
}
void setSetInternal(
MSetInternal mSetInternal) {
throw ObjectMacroException.incorrectType("MSetInternal",
this._paramName);
}
void setNewStringValue(
MNewStringValue mNewStringValue) {
throw ObjectMacroException.incorrectType("MNewStringValue",
this._paramName);
}
void setParamRef(
MParamRef mParamRef) {
throw ObjectMacroException.incorrectType("MParamRef", this._paramName);
}
void setAddIndent(
MAddIndent mAddIndent) {
throw ObjectMacroException.incorrectType("MAddIndent", this._paramName);
}
void setStringValueArg(
MStringValueArg mStringValueArg) {
throw ObjectMacroException.incorrectType("MStringValueArg",
this._paramName);
}
void setStringValue(
MStringValue mStringValue) {
throw ObjectMacroException.incorrectType("MStringValue",
this._paramName);
}
void setMacroArg(
MMacroArg mMacroArg) {
throw ObjectMacroException.incorrectType("MMacroArg", this._paramName);
}
void setStringArg(
MStringArg mStringArg) {
throw ObjectMacroException.incorrectType("MStringArg", this._paramName);
}
void setParamArg(
MParamArg mParamArg) {
throw ObjectMacroException.incorrectType("MParamArg", this._paramName);
}
void setContextParam(
MContextParam mContextParam) {
throw ObjectMacroException.incorrectType("MContextParam",
this._paramName);
}
void setContextArg(
MContextArg mContextArg) {
throw ObjectMacroException.incorrectType("MContextArg",
this._paramName);
}
void setGetInternalTail(
MGetInternalTail mGetInternalTail) {
throw ObjectMacroException.incorrectType("MGetInternalTail",
this._paramName);
}
void setStringParam(
MStringParam mStringParam) {
throw ObjectMacroException.incorrectType("MStringParam",
this._paramName);
}
void setMacroParam(
MMacroParam mMacroParam) {
throw ObjectMacroException.incorrectType("MMacroParam",
this._paramName);
}
void setAbstract(
MAbstract mAbstract) {
throw ObjectMacroException.incorrectType("MAbstract", this._paramName);
}
void setMacrosParam(
MMacrosParam mMacrosParam) {
throw ObjectMacroException.incorrectType("MMacrosParam",
this._paramName);
}
void setPublic(
MPublic mPublic) {
throw ObjectMacroException.incorrectType("MPublic", this._paramName);
}
void setOverride(
MOverride mOverride) {
throw ObjectMacroException.incorrectType("MOverride", this._paramName);
}
void setClassNone(
MClassNone mClassNone) {
throw ObjectMacroException.incorrectType("MClassNone", this._paramName);
}
void setClassBeforeFirst(
MClassBeforeFirst mClassBeforeFirst) {
throw ObjectMacroException.incorrectType("MClassBeforeFirst",
this._paramName);
}
void setClassAfterLast(
MClassAfterLast mClassAfterLast) {
throw ObjectMacroException.incorrectType("MClassAfterLast",
this._paramName);
}
void setClassSeparator(
MClassSeparator mClassSeparator) {
throw ObjectMacroException.incorrectType("MClassSeparator",
this._paramName);
}
void setExInternalException(
MExInternalException mExInternalException) {
throw ObjectMacroException.incorrectType("MExInternalException",
this._paramName);
}
void setExObjectMacroException(
MExObjectMacroException mExObjectMacroException) {
throw ObjectMacroException.incorrectType("MExObjectMacroException",
this._paramName);
}
void setExIncorrectType(
MExIncorrectType mExIncorrectType) {
throw ObjectMacroException.incorrectType("MExIncorrectType",
this._paramName);
}
void setExObjectMacroErrorHead(
MExObjectMacroErrorHead mExObjectMacroErrorHead) {
throw ObjectMacroException.incorrectType("MExObjectMacroErrorHead",
this._paramName);
}
void setExParameterNull(
MExParameterNull mExParameterNull) {
throw ObjectMacroException.incorrectType("MExParameterNull",
this._paramName);
}
void setExMacroNullInList(
MExMacroNullInList mExMacroNullInList) {
throw ObjectMacroException.incorrectType("MExMacroNullInList",
this._paramName);
}
void setExCannotModify(
MExCannotModify mExCannotModify) {
throw ObjectMacroException.incorrectType("MExCannotModify",
this._paramName);
}
void setExCyclicReference(
MExCyclicReference mExCyclicReference) {
throw ObjectMacroException.incorrectType("MExCyclicReference",
this._paramName);
}
void setExVersionNull(
MExVersionNull mExVersionNull) {
throw ObjectMacroException.incorrectType("MExVersionNull",
this._paramName);
}
void setMacroInternalException(
MMacroInternalException mMacroInternalException) {
throw ObjectMacroException.incorrectType("MMacroInternalException",
this._paramName);
}
void setExVersionsDifferent(
MExVersionsDifferent mExVersionsDifferent) {
throw ObjectMacroException.incorrectType("MExVersionsDifferent",
this._paramName);
}
void setObjectMacroUserErrorHead(
MObjectMacroUserErrorHead mObjectMacroUserErrorHead) {
throw ObjectMacroException.incorrectType("MObjectMacroUserErrorHead",
this._paramName);
}
void setUserErrorIncorrectType(
MUserErrorIncorrectType mUserErrorIncorrectType) {
throw ObjectMacroException.incorrectType("MUserErrorIncorrectType",
this._paramName);
}
void setUserErrorMacroNullInList(
MUserErrorMacroNullInList mUserErrorMacroNullInList) {
throw ObjectMacroException.incorrectType("MUserErrorMacroNullInList",
this._paramName);
}
void setUserErrorCyclicReference(
MUserErrorCyclicReference mUserErrorCyclicReference) {
throw ObjectMacroException.incorrectType("MUserErrorCyclicReference",
this._paramName);
}
void setUserErrorParameterNull(
MUserErrorParameterNull mUserErrorParameterNull) {
throw ObjectMacroException.incorrectType("MUserErrorParameterNull",
this._paramName);
}
void setUserErrorCannotModify(
MUserErrorCannotModify mUserErrorCannotModify) {
throw ObjectMacroException.incorrectType("MUserErrorCannotModify",
this._paramName);
}
void setUserErrorVersionNull(
MUserErrorVersionNull mUserErrorVersionNull) {
throw ObjectMacroException.incorrectType("MUserErrorVersionNull",
this._paramName);
}
void setUserErrorVersionsDifferent(
MUserErrorVersionsDifferent mUserErrorVersionsDifferent) {
throw ObjectMacroException.incorrectType("MUserErrorVersionsDifferent",
this._paramName);
}
void setUserErrorInternalException(
MUserErrorInternalException mUserErrorInternalException) {
throw ObjectMacroException.incorrectType("MUserErrorInternalException",
this._paramName);
}
}
| 27.152482 | 80 | 0.65513 |
973c6ef0cda92e4ddefcb967942853e080a64d25 | 2,174 | package com.tianzhi.shop520.entity.shop;
/**
* 商品信息
*/
public class GoodsInfo {
protected String Id;
protected String name;
protected boolean isChoosed;
private String imageUrl;
private String desc;
private double price;
private int count;
private int position;// 绝对位置,只在ListView构造的购物车中,在删除时有效
private String goodsImg;
private double discountPrice;
public double getDiscountPrice() {
return discountPrice;
}
public void setDiscountPrice(double discountPrice) {
this.discountPrice = discountPrice;
}
public String getGoodsImg() {
return goodsImg;
}
public void setGoodsImg(String goodsImg) {
this.goodsImg = goodsImg;
}
public GoodsInfo(String id, String name, String desc, double price, int count,
String goodsImg,double discountPrice) {
Id = id;
this.name = name;
this.desc = desc;
this.price = price;
this.count = count;
this.goodsImg=goodsImg;
this.discountPrice=discountPrice;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChoosed() {
return isChoosed;
}
public void setChoosed(boolean isChoosed) {
this.isChoosed = isChoosed;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
| 19.763636 | 82 | 0.597976 |
33c4a49b8dee224ec0dee864c73f5491fa6b2a99 | 9,619 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.jemmysupport.bundlelookup;
/*
* ComponentGeneratorTest.java
*
* Created on July 11, 2002, 2:27 PM
*/
import java.io.*;
import junit.framework.*;
import org.netbeans.junit.*;
import org.netbeans.jemmy.*;
import org.netbeans.jemmy.operators.*;
import org.netbeans.jellytools.*;
import org.netbeans.jellytools.actions.PasteAction;
import org.netbeans.jellytools.modules.jemmysupport.*;
/** JUnit test suite with Jemmy/Jelly2 support
*
* @author <a href="mailto:[email protected]">Adam Sotona</a>
* @version 1.0
*/
public class ResourceBundleLookupTest extends JellyTestCase {
/** constructor required by JUnit
* @param testName method name to be used as testcase
*/
public ResourceBundleLookupTest(String testName) {
super(testName);
}
/** method used for explicit testsuite definition
*/
public static junit.framework.Test suite() {
TestSuite suite = new NbTestSuite();
suite.addTest(new ResourceBundleLookupTest("testSearch1"));
suite.addTest(new ResourceBundleLookupTest("testSearch2"));
suite.addTest(new ResourceBundleLookupTest("testSearch3"));
suite.addTest(new ResourceBundleLookupTest("testSearch4"));
suite.addTest(new ResourceBundleLookupTest("testSearch5"));
suite.addTest(new ResourceBundleLookupTest("testSearch6"));
suite.addTest(new ResourceBundleLookupTest("testResultsPopup"));
return suite;
}
/** method called before each testcase
*/
protected void setUp() throws IOException {
}
/** method called after each testcase
*/
protected void tearDown() {
}
/** Use for internal test execution inside IDE
* @param args command line arguments
*/
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
/** simple test case
*/
public void testSearch1() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
op.setSearchedText("testvalue");
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.checkCaseSensitiveText(false);
op.checkSubstringText(false);
if (op.cbRegularExpressionText().isEnabled())
op.checkRegularExpressionText(false);
op.search();
op.verifyStatus("Found 2 keys.");
op.close();
}
/** simple test case
*/
public void testSearch2() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
op.setSearchedText("testvalue");
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.checkCaseSensitiveText(true);
op.checkSubstringText(true);
if (op.cbRegularExpressionText().isEnabled())
op.checkRegularExpressionText(false);
op.search();
op.verifyStatus("Found 2 keys.");
op.close();
}
/** simple test case
*/
public void testSearch3() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
op.setSearchedText("testvalue");
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.checkCaseSensitiveText(false);
op.checkSubstringText(true);
if (op.cbRegularExpressionText().isEnabled())
op.checkRegularExpressionText(false);
op.search();
op.verifyStatus("Found 4 keys.");
op.close();
}
/** simple test case
*/
public void testSearch4() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
if (!op.cbRegularExpressionText().isEnabled()) return;
op.setSearchedText("te[s]t.alue");
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.checkCaseSensitiveText(false);
op.checkSubstringText(false);
op.checkRegularExpressionText(true);
op.search();
op.verifyStatus("Found 2 keys.");
op.close();
}
/** simple test case
*/
public void testSearch5() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
if (!op.cbRegularExpressionText().isEnabled()) return;
op.setSearchedText("te[s]t.alue");
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.checkCaseSensitiveText(true);
op.checkSubstringText(true);
op.checkRegularExpressionText(true);
op.search();
op.verifyStatus("Found 2 keys.");
op.close();
}
/** simple test case
*/
public void testSearch6() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
if (!op.cbRegularExpressionText().isEnabled()) return;
op.setSearchedText("te[s]t.alue");
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.checkCaseSensitiveText(false);
op.checkSubstringText(true);
op.checkRegularExpressionText(true);
op.search();
op.verifyStatus("Found 4 keys.");
op.close();
}
/** simple test case
*/
public void testResultsPopup() throws Exception {
ResourceBundleLookupOperator op=ResourceBundleLookupOperator.invoke();
op.setSearchedText("testvalue");
op.checkCaseSensitiveText(true);
op.checkSubstringText(false);
op.checkRegularExpressionText(false);
op.checkUseResourceBundleFilter(true);
op.setFilterText("org.netbeans.modules.jemmysupport.bundlelookup.data");
op.search();
op.verifyStatus("Found 1 keys.");
int i=op.tabSearchResults().findCellRow("testkey");
op.tabSearchResults().selectCell(i, 0);
op.tabSearchResults().clickForPopup();
JPopupMenuOperator popup=new JPopupMenuOperator();
new JMenuItemOperator(popup, "Copy: java.util.ResourceBundle.getBundle(\"org.netbeans.modules.jemmysupport.bundlelookup.data.Bundle\").getString(\"testkey\")");
new JMenuItemOperator(popup, "Copy: org.openide.util.NbBundle.getBundle(\"org.netbeans.modules.jemmysupport.bundlelookup.data.Bundle\").getString(\"testkey\")");
new JMenuItemOperator(popup, "Copy: org.netbeans.jellytools.Bundle.getString(\"org.netbeans.modules.jemmysupport.bundlelookup.data.Bundle\", \"testkey\")");
new JMenuItemOperator(popup, "Copy: org.netbeans.jellytools.Bundle.getStringTrimmed(\"org.netbeans.modules.jemmysupport.bundlelookup.data.Bundle\", \"testkey\")").push();
op.setSearchedText("");
op.txtSearchedText().clickMouse();
new PasteAction().performShortcut(op.txtSearchedText());
assertEquals("org.netbeans.jellytools.Bundle.getStringTrimmed(\"org.netbeans.modules.jemmysupport.bundlelookup.data.Bundle\", \"testkey\")", op.getSearchedText());
op.setSearchedText("");
op.verify();
op.close();
}
}
| 40.586498 | 178 | 0.681568 |
9bd07b76bb3754efab64d0cf3b58950526ae2699 | 2,567 | /*
* Copyright (c) 2006-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.gmaven.plugin;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.sonatype.sisu.litmus.testsupport.TestSupport;
import org.codehaus.gmaven.adapter.GroovyRuntime;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link GroovyRuntimeFactory}.
*
* These tests assume that the underlying {@link java.util.ServiceLoader} functions,
* so we by-pass it and only validate the handling around the loader.
*/
public class GroovyRuntimeFactoryTest
extends TestSupport
{
private GroovyRuntimeFactory underTest;
@Mock
private ClassLoader classLoader;
private List<GroovyRuntime> services;
@Before
public void setUp() throws Exception {
services = new ArrayList<GroovyRuntime>();
underTest = new GroovyRuntimeFactory()
{
@Override
protected Iterator<GroovyRuntime> findServices(final ClassLoader classLoader) {
return services.iterator();
}
};
}
/**
* If no service is found, ISE should be thrown.
*/
@Test(expected = IllegalStateException.class)
public void create_noServices() {
underTest.create(classLoader);
fail();
}
/**
* If more than one service is found, ISE should be thrown.
*/
@Test(expected = IllegalStateException.class)
public void create_multipuleServices() {
services.add(mock(GroovyRuntime.class));
services.add(mock(GroovyRuntime.class));
underTest.create(classLoader);
fail();
}
/**
* Single service should return non-null value.
*/
@Test
public void create_singleService() {
services.add(mock(GroovyRuntime.class));
GroovyRuntime runtime = underTest.create(classLoader);
assertThat(runtime, notNullValue());
}
}
| 27.602151 | 85 | 0.730425 |
a5b2de12a41fbd4308ac53a9a59b3305adacff5a | 183 | package com.knewless.core.dailyProgress.dto;
import lombok.Data;
import java.time.LocalDate;
@Data
public class ActivityDto {
private LocalDate date;
private int seconds;
}
| 16.636364 | 44 | 0.765027 |
b54cc9f09903bee7a2266d78e04bfdfd4b55921e | 330 | package sdm.sccpms.gift;
import java.util.LinkedList;
import java.util.List;
public class BinaryGiftGivingStrategy implements GiftGivingStrategyInterface {
@Override
public List<Gift> getGifts(List<Gift> gifts, float goodness) {
if (goodness >= .5) {
return gifts;
} else {
return new LinkedList<Gift>();
}
}
}
| 18.333333 | 78 | 0.724242 |
d23e8c316b6ae104c02f6612f9030b66b0e8f1f4 | 79 | package com.atguigu.gulimall.seckill.config;
public class ScheduledConfig {
}
| 15.8 | 44 | 0.810127 |
2befc9db8c6c4b23c5ffc43e3bade2d7ac69de18 | 162 | package com.cardealer.car_dealer.util;
public interface Parser {
String toJsonString(Object obj);
<T> T exportFileContent(String str, Class<T> klass);
}
| 23.142857 | 56 | 0.740741 |
be7623d01b311dabb053b296f795798f34ad7f69 | 13,876 | /*
* TopStack (c) Copyright 2012-2013 Transcend Computing, 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.msi.tough.engine.aws.ec2;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.IntNode;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.network.Direction;
import org.dasein.cloud.network.FirewallSupport;
import org.dasein.cloud.network.NetworkServices;
import org.dasein.cloud.network.Protocol;
import org.hibernate.Session;
import org.slf4j.Logger;
import com.msi.tough.cf.AccountType;
import com.msi.tough.cf.CFType;
import com.msi.tough.cf.ec2.AuthorizeSecurityGroupIngressType;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.HibernateUtil;
import com.msi.tough.core.HibernateUtil.Operation;
import com.msi.tough.core.JsonUtil;
import com.msi.tough.engine.core.BaseProvider;
import com.msi.tough.engine.core.CallStruct;
import com.msi.tough.engine.resource.Resource;
import com.msi.tough.model.ResourcesBean;
import com.msi.tough.utils.ConfigurationUtil;
import com.msi.tough.utils.Constants;
import com.msi.tough.utils.SecurityGroupUtils;
public class SecurityGroupIngress extends BaseProvider {
private static Logger logger = Appctx.getLogger(SecurityGroupIngress.class
.getName());
public static String TYPE = "AWS::EC2::SecurityGroupIngress";
@Override
public CFType create0(final CallStruct call) throws Exception {
final AccountType ac = call.getAc();
String avz = (String) call.getProperty(Constants.AVAILABILITYZONE);
if (avz == null) {
avz = ac.getDefZone();
}
String groupName = (String) call.getProperty(Constants.GROUPNAME);
if (groupName == null) {
groupName = (String) call.getProperty(Constants.GROUPID);
}
if (groupName == null) {
throw new RuntimeException("SecurityGroupName cannot be blank");
}
groupName = SecurityGroupUtils.getProviderId(groupName, avz,
call.getAc());
String ipProtocol = (String) call.getProperty(Constants.IPPROTOCOL);
if (ipProtocol == null) {
ipProtocol = "tcp";
}
final String cidrIp = (String) call.getProperty(Constants.CIDRIP);
final String sourceSecurityGroupName = (String) call
.getProperty(Constants.SOURCESECURITYGROUPNAME);
final String sourceSecurityGroupOwnerId = (String) call
.getProperty(Constants.SOURCESECURITYGROUPOWNERID);
if (cidrIp == null && sourceSecurityGroupName == null) {
throw new RuntimeException(
"CidrIP and SourceSecurityGroupName both cannot be blank");
}
if (cidrIp != null && sourceSecurityGroupName != null) {
throw new RuntimeException(
"CidrIP and SourceSecurityGroupName both cannot be provided");
}
final AuthorizeSecurityGroupIngressType ret = new AuthorizeSecurityGroupIngressType();
final String retry = (String) ConfigurationUtil.getConfiguration(Arrays
.asList(new String[] { "AWS::EC2::retryCount",
"AWS::EC2::AuthorizeSecurityGroupIngress" }));
final int retrycnt = retry == null ? 1 : Integer.parseInt(retry);
call.setAvailabilityZone(avz);
final CloudProvider cloudProvider = call.getCloudProvider();
final NetworkServices network = cloudProvider.getNetworkServices();
final FirewallSupport firewall = network.getFirewallSupport();
final int fromPort = Integer.parseInt(""
+ call.getRequiredProperty(Constants.FROMPORT));
final int toPort = Integer.parseInt(""
+ call.getRequiredProperty(Constants.TOPORT));
for (int i = 0; i < retrycnt; i++) {
try {
// ec2.authorizeSecurityGroupIngress(req);
if (cidrIp != null) {
firewall.authorize(groupName, Direction.INGRESS, cidrIp,
Protocol.TCP, fromPort, toPort);
} else {
firewall.authorize(groupName, Direction.INGRESS,
sourceSecurityGroupName, Protocol.TCP, fromPort,
toPort);
}
break;
} catch (final Exception e) {
e.printStackTrace();
continue;
}
}
logger.info("Ingress set ");
final Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.GROUPNAME, groupName);
params.put(Constants.IPPROTOCOL, ipProtocol);
if (cidrIp != null) {
params.put(Constants.CIDRIP, cidrIp);
}
if (sourceSecurityGroupName != null) {
params.put(Constants.SOURCESECURITYGROUPNAME,
sourceSecurityGroupName);
params.put(Constants.SOURCESECURITYGROUPOWNERID,
sourceSecurityGroupOwnerId);
}
params.put(Constants.FROMPORT, fromPort);
params.put(Constants.TOPORT, toPort);
HibernateUtil.withNewSession(new Operation<Object>() {
@Override
public Object ex(final Session s, final Object... args)
throws Exception {
final ResourcesBean resBean = getResourceBean(s);
resBean.setResourceData(JsonUtil.toJsonString(params));
s.save(resBean);
return null;
}
});
return ret;
}
@Override
public Resource delete0(final CallStruct call) throws Exception {
final AccountType ac = call.getAc();
String avz = (String) call.getProperty(Constants.AVAILABILITYZONE);
if (avz == null) {
avz = ac.getDefZone();
}
final ResourcesBean rbean = call.getResourcesBean();
Map<String, Object> resourceMap = null;
if (rbean != null) {
final String hp = rbean.getResourceData();
if (hp != null) {
final JsonNode jn = JsonUtil.load(hp);
resourceMap = JsonUtil.toMap(jn);
}
}
String groupName = (String) call.getProperty(Constants.GROUPNAME);
if (groupName == null && resourceMap != null) {
final Object node = resourceMap.get(Constants.GROUPNAME);
if (node != null) {
if (node instanceof String) {
groupName = (String) node;
}
if (node instanceof JsonNode) {
groupName = ((JsonNode) node).getTextValue();
}
}
}
String ipProtocol = (String) call.getProperty(Constants.IPPROTOCOL);
if (ipProtocol == null && resourceMap != null) {
final Object node = resourceMap.get(Constants.IPPROTOCOL);
if (node != null) {
if (node instanceof String) {
ipProtocol = (String) node;
}
if (node instanceof JsonNode) {
ipProtocol = ((JsonNode) node).getTextValue();
}
}
}
if (ipProtocol == null) {
ipProtocol = "TCP";
}
String cidrIp = (String) call.getProperty(Constants.CIDRIP);
if (cidrIp == null && resourceMap != null) {
final Object node = resourceMap.get(Constants.CIDRIP);
if (node != null) {
if (node instanceof String) {
cidrIp = (String) node;
}
if (node instanceof JsonNode) {
cidrIp = ((JsonNode) node).getTextValue();
}
}
}
String sourceSecurityGroupName = (String) call
.getProperty(Constants.SOURCESECURITYGROUPNAME);
if (sourceSecurityGroupName == null && resourceMap != null) {
final Object node = resourceMap
.get(Constants.SOURCESECURITYGROUPNAME);
if (node != null) {
if (node instanceof String) {
sourceSecurityGroupName = (String) node;
}
if (node instanceof JsonNode) {
sourceSecurityGroupName = ((JsonNode) node).getTextValue();
}
}
}
String sourceSecurityGroupOwnerId = (String) call
.getProperty(Constants.SOURCESECURITYGROUPOWNERID);
if (sourceSecurityGroupOwnerId == null && resourceMap != null) {
final Object node = resourceMap
.get(Constants.SOURCESECURITYGROUPOWNERID);
if (node != null) {
if (node instanceof String) {
sourceSecurityGroupOwnerId = (String) node;
}
if (node instanceof JsonNode) {
sourceSecurityGroupOwnerId = ((JsonNode) node)
.getTextValue();
}
}
}
String fromPort = null;
String toPort = null;
if (fromPort == null && resourceMap != null) {
final Object node = resourceMap.get(Constants.FROMPORT);
if (node != null) {
if (node instanceof String) {
fromPort = (String) node;
}
if (node instanceof IntNode) {
fromPort = ((IntNode) node).getValueAsText();
}
}
}
if (toPort == null && resourceMap != null) {
final Object node = resourceMap.get(Constants.TOPORT);
if (node != null) {
if (node instanceof String) {
toPort = (String) node;
}
if (node instanceof IntNode) {
toPort = ((IntNode) node).getValueAsText();
}
}
}
// if (call.getProperty(Constants.FROMPORT) instanceof Integer
// || call.getProperty(Constants.FROMPORT) instanceof String) {
// fromPort = Integer.parseInt(call.getProperty(Constants.FROMPORT)
// .toString());
// }
// if (call.getProperty(Constants.TOPORT) instanceof Integer
// || call.getProperty(Constants.TOPORT) instanceof String) {
// toPort = Integer.parseInt(call.getProperty(Constants.TOPORT)
// .toString());
// }
//
// if (resourceMap != null && fromPort == -1) {
// final JsonNode node = (JsonNode) resourceMap
// .get(Constants.FROMPORT);
// if (node != null) {
// final String s = node.getTextValue();
// fromPort = Integer.parseInt(s);
// }
// }
// if (resourceMap != null && toPort == -1) {
// final JsonNode node = (JsonNode) resourceMap.get(Constants.TOPORT);
// if (node != null) {
// final String s = node.getTextValue();
// toPort = Integer.parseInt(s);
// }
// }
if (fromPort == null || toPort == null) {
return null;
}
if (cidrIp == null && sourceSecurityGroupName == null
&& resourceMap != null) {
final JsonNode node = (JsonNode) resourceMap.get(Constants.CIDRIP);
if (node != null) {
cidrIp = node.getTextValue();
}
final JsonNode node1 = (JsonNode) resourceMap
.get(Constants.SOURCESECURITYGROUPNAME);
if (node1 != null) {
sourceSecurityGroupName = node1.getTextValue();
}
final JsonNode node2 = (JsonNode) resourceMap
.get(Constants.SOURCESECURITYGROUPOWNERID);
if (node2 != null) {
sourceSecurityGroupOwnerId = node2.getTextValue();
}
}
final CloudProvider cloudProvider = call.getCloudProvider();
final NetworkServices network = cloudProvider.getNetworkServices();
final FirewallSupport firewall = network.getFirewallSupport();
final String retry = (String) ConfigurationUtil.getConfiguration(Arrays
.asList(new String[] { "AWS::EC2::retryCount",
"AWS::EC2::AuthorizeSecurityGroupIngress" }));
final int retrycnt = retry == null ? 1 : Integer.parseInt(retry);
for (int i = 0; i < retrycnt; i++) {
try {
if (cidrIp != null) {
firewall.revoke(groupName, Direction.INGRESS, cidrIp,
Protocol.TCP, Integer.parseInt(fromPort),
Integer.parseInt(toPort));
} else {
firewall.revoke(groupName, sourceSecurityGroupName,
Protocol.TCP, Integer.parseInt(fromPort),
Integer.parseInt(toPort));
}
break;
} catch (final Exception e) {
e.printStackTrace();
continue;
}
}
logger.info("Ingress revoked " + groupName + " " + fromPort + " "
+ cidrIp);
return null;
}
@Override
protected boolean isResource() {
return true;
}
}
| 40.104046 | 94 | 0.566734 |
a441ca72c5b0124bf20bad776cc2c30c2a710dac | 224 | // Automatically created - do not modify - CSOFF
///CLOVER:OFF
package com.opengamma.livedata.msg;
public enum LiveDataSubscriptionResult {
SUCCESS,
NOT_PRESENT,
NOT_AUTHORIZED,
INTERNAL_ERROR;
}
///CLOVER:ON - CSON
| 20.363636 | 48 | 0.754464 |
58ff65d783c8a198367b1a70ef3853be09a58db8 | 3,946 | package org.tessell.gwt.user.client.ui;
import org.tessell.gwt.dom.client.*;
import org.tessell.util.Stubs;
import org.tessell.widgets.StubWidget;
import com.google.gwt.event.dom.client.HasAllDragAndDropHandlers;
/**
* Attempts to mimick drag/drag behavior just enough for us to
* reliably unit test behavior in presenter tests.
*
* Note that some browsers are pickier than others; e.g. Chrome
* seems fairly lenient, and does not care if the user does not
* call "setData" or "preventDefault" in dragstart. Firefox does.
*
* This attempts to match the most-strict behavior, so that unit
* tests have the best chance of ensuring success in actual browsers.
*/
class StubDragLogic {
public static HasAllDragAndDropHandlers currentDraggable;
public static StubDragStartEvent currentStart;
public static StubDragOverEvent currentOver;
public static HasAllDragAndDropHandlers currentOverOwner;
public static StubDropEvent currentDrop;
private final HasAllDragAndDropHandlers owner;
private boolean hasDragOver;
private static void reset() {
currentDraggable = null;
currentStart = null;
currentOver = null;
currentOverOwner = null;
currentDrop = null;
}
static {
Stubs.addAfterTestReset(() -> reset());
}
StubDragLogic(HasAllDragAndDropHandlers owner) {
this.owner = owner;
}
void markHasDragOverHandler() {
hasDragOver = true;
}
void dragStart() {
ensureDraggable();
if (currentStart != null) {
currentDraggable.fireEvent(new StubDragEndEvent());
}
currentDraggable = owner;
currentStart = new StubDragStartEvent();
owner.fireEvent(currentStart);
}
void dragEnd() {
owner.fireEvent(new StubDragEndEvent());
}
void dragEnter() {
owner.fireEvent(new StubDragEnterEvent());
}
void dragLeave() {
owner.fireEvent(new StubDragLeaveEvent());
}
void dragOver() {
ensureCanBeDraggedOver();
currentOver = new StubDragOverEvent();
currentOverOwner = owner;
owner.fireEvent(currentOver);
}
void drop() {
// implicitly dragOver so that unit tests can be less verbose
if (currentOverOwner != owner) {
dragOver();
}
ensureCanBeDroppedOn();
currentDrop = new StubDropEvent(currentStart.mimeType, currentStart.data);
owner.fireEvent(currentDrop);
if (!currentDrop.prevented) {
throw new IllegalStateException("addDropHandler should call preventDefault()");
}
currentDraggable.fireEvent(new StubDragEndEvent());
reset();
}
private void ensureCanBeDraggedOver() {
if (currentDraggable == null) {
throw new IllegalStateException("No stub dragStart() was called");
}
if (currentStart.mimeType == null && currentStart.data == null) {
throw new IllegalStateException("Firefox requires setData to be called in drag start");
}
}
private void ensureCanBeDroppedOn() {
if (currentDraggable == null) {
throw new IllegalStateException("No stub dragStart() was called");
}
if (currentStart.mimeType == null && currentStart.data == null) {
throw new IllegalStateException("Firefox requires setData to be called in drag start");
}
if (!hasDragOver) {
throw new IllegalStateException("addDragOverHandler must be called to get drop events");
}
if (!currentOver.prevented) {
throw new IllegalStateException("addDragOverHandler should call preventDefault() if it wants to drop");
}
}
private void ensureDraggable() {
String draggable = ((StubWidget) owner).getIsElement().getAttribute("draggable");
if ("false".equals(draggable)) {
throw new IllegalStateException("Element must have draggable=true");
}
// these are draggable by default
if (owner instanceof IsAnchor || owner instanceof IsImage) {
return;
}
if (!"true".equals(draggable)) {
throw new IllegalStateException("Element must have draggable=true");
}
}
}
| 29.893939 | 109 | 0.706285 |
6e66256ae6d59309f8a94ccc4fb73aabba022e13 | 3,520 | /* Copyright 2019 The TensorFlow Authors. 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 org.tensorflow.lite.nnapi;
import org.tensorflow.lite.Delegate;
import org.tensorflow.lite.TensorFlowLite;
/**
* Implementation of {@link Delegate} for NNAPI inference. Only for use by packages in
* org.tensorflow.lite.
*
* @hide
*/
public class NnApiDelegateImpl implements NnApiDelegate.PrivateInterface, Delegate, AutoCloseable {
private static final long INVALID_DELEGATE_HANDLE = 0;
private long delegateHandle;
public NnApiDelegateImpl(NnApiDelegate.Options options) {
// Ensure the native TensorFlow Lite libraries are available.
TensorFlowLite.init();
delegateHandle =
createDelegate(
options.getExecutionPreference(),
options.getAcceleratorName(),
options.getCacheDir(),
options.getModelToken(),
options.getMaxNumberOfDelegatedPartitions(),
/*overrideDisallowCpu=*/ options.getUseNnapiCpu() != null,
/*disallowCpuValue=*/ options.getUseNnapiCpu() != null
? !options.getUseNnapiCpu().booleanValue()
: true,
options.getAllowFp16(),
options.getNnApiSupportLibraryHandle());
}
@Override
public long getNativeHandle() {
return delegateHandle;
}
/**
* Frees TFLite resources in C runtime.
*
* <p>User is expected to call this method explicitly.
*/
@Override
public void close() {
if (delegateHandle != INVALID_DELEGATE_HANDLE) {
deleteDelegate(delegateHandle);
delegateHandle = INVALID_DELEGATE_HANDLE;
}
}
/**
* Returns the latest error code returned by an NNAPI call or zero if NO calls to NNAPI failed.
* The error code is reset when the delegate is associated with an <a
* href=https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/Interpreter>interpreter</a>.
*
* <p>For details on NNAPI error codes see <a
* href="https://developer.android.com/ndk/reference/group/neural-networks#resultcode">the NNAPI
* documentation</a>.
*
* @throws IllegalStateException if the method is called after {@link #close() close}.
*/
@Override
public int getNnapiErrno() {
checkNotClosed();
return getNnapiErrno(delegateHandle);
}
private void checkNotClosed() {
if (delegateHandle == INVALID_DELEGATE_HANDLE) {
throw new IllegalStateException("Should not access delegate after it has been closed.");
}
}
private static native long createDelegate(
int preference,
String deviceName,
String cacheDir,
String modelToken,
int maxDelegatedPartitions,
boolean overrideDisallowCpu,
boolean disallowCpuValue,
boolean allowFp16,
long nnApiSupportLibraryHandle);
private static native void deleteDelegate(long delegateHandle);
private static native int getNnapiErrno(long delegateHandle);
}
| 32.897196 | 104 | 0.69517 |
e0b50ba9ffb2987f142c588c78bc5bf6916cdfaf | 947 | package com.isa.ISA.DTO;
import java.util.ArrayList;
import com.isa.ISA.dbModel.enums.TipAdmina;
public class AdminDTO {
private String username;
private String pass;
private TipAdmina tipAdmina;
private long[] pozBio;
private String email;
public AdminDTO() {
}
public String getUsername() {
return username;
}
public String getPass() {
return pass;
}
public TipAdmina getTipAdmina() {
return tipAdmina;
}
public long[] getPozBio() {
return pozBio;
}
public void setUsername(String username) {
this.username = username;
}
public void setPass(String pass) {
this.pass = pass;
}
public void setTipAdmina(TipAdmina tipAdmina) {
this.tipAdmina = tipAdmina;
}
public void setPozBio(long[] pozBio) {
this.pozBio = pozBio;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 16.050847 | 49 | 0.657867 |
44300684b51a6d0bf0f0b02554abec0c9a985bcc | 229 | package models.purchase;
public class NormalFee implements PurchaseFee {
Double fee;
public NormalFee(Double fee) {
this.fee = fee;
}
@Override
public Double getFee() {
return fee;
}
}
| 14.3125 | 47 | 0.611354 |
2422138f09095063ca85c85a2fead15bbf727e28 | 1,740 | package com.kaglobal.malladmin.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.*;
import lombok.Data;
/**
* 品牌表VO
*
* @author bianj
* @version 2020-10-19
*/
@Data
@ApiModel(description = "品牌表VO")
public class PmsBrandSaveVO {
/** id */
@ApiModelProperty(value = "" , required = true)
@NotNull(message = "不能为空")
private Long id;
/** name */
@ApiModelProperty(value = "", position = 1 )
@Length(max=64, message = "不能大于64")
private String name;
/** 首字母 */
@ApiModelProperty(value = "首字母", position = 2 )
@Length(max=8, message = "首字母不能大于8")
private String firstLetter;
/** sort */
@ApiModelProperty(value = "", position = 3 )
private Integer sort;
/** 是否为品牌制造商:0->不是;1->是 */
@ApiModelProperty(value = "是否为品牌制造商:0->不是;1->是", position = 4 )
private Integer factoryStatus;
/** showStatus */
@ApiModelProperty(value = "", position = 5 )
private Integer showStatus;
/** 产品数量 */
@ApiModelProperty(value = "产品数量", position = 6 )
private Integer productCount;
/** 产品评论数量 */
@ApiModelProperty(value = "产品评论数量", position = 7 )
private Integer productCommentCount;
/** 品牌logo */
@ApiModelProperty(value = "品牌logo", position = 8 )
@Length(max=255, message = "品牌logo不能大于255")
private String logo;
/** 专区大图 */
@ApiModelProperty(value = "专区大图", position = 9 )
@Length(max=255, message = "专区大图不能大于255")
private String bigPic;
/** 品牌故事 */
@ApiModelProperty(value = "品牌故事", position = 10 )
@Length(max=65535, message = "品牌故事不能大于65535")
private String brandStory;
} | 30 | 67 | 0.643678 |
98196584aae2aac3ef6bfb7f6d59f67091de758c | 853 | package datawave.ingest.mapreduce.job.writer;
import java.io.IOException;
import java.util.Map;
import datawave.ingest.mapreduce.job.BulkIngestKey;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import org.apache.accumulo.core.data.Value;
import com.google.common.collect.Multimap;
/**
* A simple context writer that simply passes the key and value directly to the context.
*
*
*
*/
public class BulkContextWriter extends AbstractContextWriter<BulkIngestKey,Value> {
@Override
protected void flush(Multimap<BulkIngestKey,Value> entries, TaskInputOutputContext<?,?,BulkIngestKey,Value> context) throws IOException,
InterruptedException {
for (Map.Entry<BulkIngestKey,Value> entry : entries.entries()) {
context.write(entry.getKey(), entry.getValue());
}
}
}
| 27.516129 | 140 | 0.725674 |
ca7c96136cc1ad1b7cba165975e2dc1e2edc0984 | 6,434 | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, Lotus
* Development Corporation., http://www.lotus.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xml.serializer;
import java.util.Hashtable;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import org.apache.xml.res.XMLErrorResources;
import org.apache.xml.res.XMLMessages;
import org.xml.sax.ContentHandler;
/**
* Factory for creating serializers.
*/
public abstract class SerializerFactory
{
/*
* Associates output methods to serializer classes.
* (Don't use this right now. -sb
*/
// private static Hashtable _serializers = new Hashtable();
/**
* Associates output methods to default output formats.
*/
private static Hashtable m_formats = new Hashtable();
/**
* Returns a serializer for the specified output method. Returns
* null if no implementation exists that supports the specified
* output method. For a list of the default output methods see
* {@link Method}.
*
* @param format The output format
* @return A suitable serializer, or null
* @throws IllegalArgumentException (apparently -sc) if method is
* null or an appropriate serializer can't be found
* @throws WrappedRuntimeException (apparently -sc) if an
* exception is thrown while trying to find serializer
*/
public static Serializer getSerializer(Properties format)
{
Serializer ser = null;
try
{
Class cls;
String method = format.getProperty(OutputKeys.METHOD);
if (method == null)
throw new IllegalArgumentException(
"The output format has a null method name");
String className;
className =
format.getProperty(OutputPropertiesFactory.S_KEY_CONTENT_HANDLER);
if (null == className)
{
throw new IllegalArgumentException(
"The output format must have a '"
+ OutputPropertiesFactory.S_KEY_CONTENT_HANDLER + "' property!");
}
cls = Class.forName(className);
// _serializers.put(method, cls);
Object obj = cls.newInstance();
if (obj instanceof SerializationHandler)
{
// this is one of the supplied serializers
ser = (Serializer) cls.newInstance();
ser.setOutputFormat(format);
}
else
{
/*
* This must be a user defined Serializer.
* It had better implement ContentHandler.
*/
if (obj instanceof ContentHandler)
{
/*
* The user defined serializer defines ContentHandler,
* but we need to wrap it with ToXMLSAXHandler which
* will collect SAX-like events and emit true
* SAX ContentHandler events to the users handler.
*/
className = SerializerConstants.DEFAULT_SAX_SERIALIZER;
cls = Class.forName(className);
SerializationHandler sh =
(SerializationHandler) cls.newInstance();
sh.setContentHandler( (ContentHandler) obj);
sh.setOutputFormat(format);
ser = sh;
}
else
{
// user defined serializer does not implement
// ContentHandler, ... very bad
throw new Exception(
XMLMessages.createXMLMessage(
XMLErrorResources.ER_SERIALIZER_NOT_CONTENTHANDLER,
new Object[] { className}));
}
}
}
catch (Exception e)
{
throw new org.apache.xml.utils.WrappedRuntimeException(e);
}
return ser;
}
}
| 34.591398 | 79 | 0.640814 |
52a0d2dc951459074cea3b0d72fc9367bd030c10 | 3,011 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.portlet.container.properties;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apereo.portal.portlet.om.IPortletWindow;
import org.apereo.portal.url.IPortalRequestUtils;
import org.apereo.portal.utils.Populator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Provides some extra information from the {@link HttpServletRequest} to the portlet as properties.
*
*/
@Service("httpRequestPropertiesManager")
public class HttpRequestPropertiesManager extends BaseRequestPropertiesManager {
private IPortalRequestUtils portalRequestUtils;
@Autowired
public void setPortalRequestUtils(IPortalRequestUtils portalRequestUtils) {
this.portalRequestUtils = portalRequestUtils;
}
@Override
public <P extends Populator<String, String>> void populateRequestProperties(
HttpServletRequest portletRequest,
IPortletWindow portletWindow,
P propertiesPopulator) {
final HttpServletRequest httpServletRequest =
this.portalRequestUtils.getOriginalPortalRequest(portletRequest);
final String remoteAddr = httpServletRequest.getRemoteAddr();
if (remoteAddr != null) {
propertiesPopulator.put("REMOTE_ADDR", remoteAddr);
}
final String remoteHost = httpServletRequest.getRemoteHost();
if (remoteHost != null) {
propertiesPopulator.put("REMOTE_HOST", remoteHost);
}
final String method = httpServletRequest.getMethod();
if (method != null) {
propertiesPopulator.put("REQUEST_METHOD", method);
}
@SuppressWarnings("unchecked")
final Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
final String name = headerNames.nextElement();
@SuppressWarnings("unchecked")
final Enumeration<String> values = httpServletRequest.getHeaders(name);
while (values.hasMoreElements()) {
propertiesPopulator.put(name, values.nextElement());
}
}
}
}
| 40.146667 | 100 | 0.721023 |
e50aa4f644150d4ff68c9b826f5e744f8e337706 | 2,009 | /*
* Copyright 2019 ConsenSys AG.
*
* 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 tech.pegasys.pantheon.ethereum.eth.sync.fastsync;
import static java.util.stream.Collectors.toList;
import tech.pegasys.pantheon.ethereum.core.BlockHeader;
import java.util.List;
import java.util.function.UnaryOperator;
public class FastSyncCheckpointFilter implements UnaryOperator<List<BlockHeader>> {
private final BlockHeader pivotBlockHeader;
public FastSyncCheckpointFilter(final BlockHeader pivotBlockHeader) {
this.pivotBlockHeader = pivotBlockHeader;
}
@Override
public List<BlockHeader> apply(final List<BlockHeader> blockHeaders) {
if (blockHeaders.isEmpty()) {
return blockHeaders;
}
if (lastHeaderNumberIn(blockHeaders) > pivotBlockHeader.getNumber()) {
return trimToPivotBlock(blockHeaders);
}
return blockHeaders;
}
private List<BlockHeader> trimToPivotBlock(final List<BlockHeader> blockHeaders) {
final List<BlockHeader> filteredHeaders =
blockHeaders.stream()
.filter(header -> header.getNumber() <= pivotBlockHeader.getNumber())
.collect(toList());
if (filteredHeaders.isEmpty()
|| lastHeaderNumberIn(filteredHeaders) != pivotBlockHeader.getNumber()) {
filteredHeaders.add(pivotBlockHeader);
}
return filteredHeaders;
}
private long lastHeaderNumberIn(final List<BlockHeader> filteredHeaders) {
return filteredHeaders.get(filteredHeaders.size() - 1).getNumber();
}
}
| 35.245614 | 118 | 0.745645 |
f5cf0efbf39df1b0a13da46b49506ffdb7d3d7b0 | 2,869 | /*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.xml.validation;
/**
* Immutable in-memory representation of grammar.
*
* <p>
* This object represents a set of constraints that can be checked/
* enforced against an XML document.
*
* <p>
* A {@link Schema} object is thread safe and applications are
* encouraged to share it across many parsers in many threads.
*
* <p>
* A {@link Schema} object is immutable in the sense that it shouldn't
* change the set of constraints once it is created. In other words,
* if an application validates the same document twice against the same
* {@link Schema}, it must always produce the same result.
*
* <p>
* A {@link Schema} object is usually created from {@link SchemaFactory}.
*
* <p>
* Two kinds of validators can be created from a {@link Schema} object.
* One is {@link Validator}, which provides highly-level validation
* operations that cover typical use cases. The other is
* {@link ValidatorHandler}, which works on top of SAX for better
* modularity.
*
* <p>
* This specification does not refine
* the {@link java.lang.Object#equals(java.lang.Object)} method.
* In other words, if you parse the same schema twice, you may
* still get <code>!schemaA.equals(schemaB)</code>.
*
* @author Kohsuke Kawaguchi
* @see <a href="http://www.w3.org/TR/xmlschema-1/">XML Schema Part 1: Structures</a>
* @see <a href="http://www.w3.org/TR/xml11/">Extensible Markup Language (XML) 1.1</a>
* @see <a href="http://www.w3.org/TR/REC-xml">Extensible Markup Language (XML) 1.0 (Second Edition)</a>
* @since 1.5
*/
public abstract class Schema {
/**
* Constructor for the derived class.
*
* <p>
* The constructor does nothing.
*/
protected Schema() {
}
/**
* Creates a new {@link Validator} for this {@link Schema}.
*
* <p>A validator enforces/checks the set of constraints this object
* represents.</p>
*
* <p>Implementors should assure that the properties set on the
* {@link SchemaFactory} that created this {@link Schema} are also
* set on the {@link Validator} constructed.</p>
*
* @return
* Always return a non-null valid object.
*/
public abstract Validator newValidator();
/**
* Creates a new {@link ValidatorHandler} for this {@link Schema}.
*
* <p>Implementors should assure that the properties set on the
* {@link SchemaFactory} that created this {@link Schema} are also
* set on the {@link ValidatorHandler} constructed.</p>
*
* @return
* Always return a non-null valid object.
*/
public abstract ValidatorHandler newValidatorHandler();
}
| 27.32381 | 104 | 0.654932 |
c4703dedc29999e1755903eef7a58594cdc59976 | 2,383 | /*
* Copyright 2018 tweerlei Wruck + Buchmeier GbR - http://www.tweerlei.de/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.tweerlei.dbgrazer.web.formatter.impl;
import java.io.IOException;
import java.util.Locale;
import java.util.TimeZone;
import de.tweerlei.common.codec.HexCodec;
/**
* Plain format for CSV export
*
* @author Robert Wruck
*/
public class ExportDataFormatterImpl extends AbstractDataFormatter
{
/**
* Constructor
* @param tsfmt Timestamp date format
* @param ldfmt Long date format
* @param sdfmt Short date format
* @param ifmt Integer format
* @param ffmt Float format
* @param locale Locale
* @param tz Time zone
* @param sizeLimit Size limit (characters) for formatted output
*/
public ExportDataFormatterImpl(String tsfmt, String ldfmt, String sdfmt, String ifmt, String ffmt, Locale locale, TimeZone tz, int sizeLimit)
{
super(tsfmt, ldfmt, sdfmt, ifmt, ffmt, locale, tz, sizeLimit);
}
@Override
protected String formatNull()
{
return ("");
}
@Override
protected String formatEmptyString()
{
return ("");
}
@Override
protected String formatNonemptyString(String s)
{
return (s);
}
@Override
protected String formatPassword(String value)
{
return ("");
}
@Override
protected String formatBoolean(boolean b)
{
return (b ? "1" : "0");
}
@Override
protected String formatException(Object value, Exception e)
{
return ("<" + value.getClass().getName() + ": " + e.getMessage() + ">");
}
@Override
protected String formatBinary(byte[] data, int size)
{
try {
final HexCodec hb = new HexCodec(false, null, 0, null);
return (hb.encode(data, 0, size));
}
catch (IOException e)
{
return (formatException(data, e));
}
}
@Override
protected String formatSpecial(String s)
{
return ("<" + s + ">");
}
}
| 23.135922 | 142 | 0.689467 |
d54111be6ccf2064b2a5b831e9cb009717c026dd | 1,594 | package si.vilfa.junglechronicles.Events;
import com.badlogic.gdx.utils.Array;
import si.vilfa.junglechronicles.Component.Loggable;
import java.util.HashMap;
/**
* @author luka
* @date 05/12/2021
* @package si.vilfa.junglechronicles.Events
**/
public abstract class EventDispatcher implements Loggable
{
private final HashMap<EventType, Array<EventListener>> listeners;
public EventDispatcher()
{
this.listeners = new HashMap<>();
}
public EventDispatcher registerEventListener(EventType eventType, EventListener eventListener)
{
if (listeners.containsKey(eventType))
{
listeners.get(eventType).add(eventListener);
} else
{
listeners.put(eventType, new Array<>(new EventListener[]{ eventListener }));
}
return this;
}
public EventDispatcher unregisterEventListener(EventListener eventListener)
{
for (EventType key : listeners.keySet())
{
while (listeners.get(key).contains(eventListener, false))
{
listeners.get(key).removeValue(eventListener, false);
}
}
return this;
}
protected void dispatchEvent(EventType eventType, Object... eventData)
{
for (EventListener listener : listeners.getOrDefault(eventType, new Array<>()))
{
listener.handleEvent(createEvent(eventType, eventData));
}
}
protected Event createEvent(EventType eventType, Object... eventData)
{
return new Event(eventType, this, eventData);
}
}
| 27.016949 | 98 | 0.646801 |
f24d352376e3f197118e561cf1406670d775c5d9 | 1,496 | /*
* Copyright 2014-2018 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.dbflute.helper.jdbc.sqlfile;
import java.io.File;
import java.util.List;
import org.dbflute.helper.jdbc.sqlfile.DfSqlFileGetter;
import org.junit.Assert;
import org.dbflute.unit.EngineTestCase;
import org.dbflute.util.DfResourceUtil;
/**
* @author jflute
* @since 0.5.7 (2007/11/03 Saturday)
*/
public class DfSqlFileGetterTest extends EngineTestCase {
public void test_getSqlFileList() throws Exception {
final DfSqlFileGetter getter = new DfSqlFileGetter();
final File buildDir = DfResourceUtil.getBuildDir(getClass());
final String canonicalPath = DfResourceUtil.getCanonicalPath(buildDir);
final List<File> sqlFileList = getter.getSqlFileList(canonicalPath);
if (sqlFileList.size() < 2) {
Assert.fail();
}
for (File file : sqlFileList) {
log(file);
}
}
}
| 32.521739 | 79 | 0.71123 |
b53483761bf052090c648baf6bf62159bce96b61 | 1,187 | package com.capg.p1;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "MyAccounts")
public class Account {
@Id
@Column(name = "accountNumber")
private int accId;
@Column(name=" AccountName")
private String accountHolderName;
private int balance;
public Account() {
super();
// TODO Auto-generated constructor stub
}
public Account(int accId, String accountHolderName, int balance) {
super();
this.accId = accId;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
public int getAccId() {
return accId;
}
public void setAccId(int accId) {
this.accId = accId;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account [accId=" + accId + ", accountHolderName=" + accountHolderName + ", balance=" + balance + "]";
}
} | 18.546875 | 111 | 0.712721 |
08ace509ed12e502f41cda8c4e7158157bb99c1f | 2,189 | package com.boot.mytt.core.redisson;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
/**
* redisson bean管理
*/
@Configuration
public class RedissonConfig {
/**
* Redisson客户端注册
* 单机模式
*/
@Bean(destroyMethod = "shutdown")
public RedissonClient createRedissonClient() throws IOException {
// Config config = new Config();
// SingleServerConfig singleServerConfig = config.useSingleServer();
// singleServerConfig.setAddress("redis://127.0.0.1:6379");
// singleServerConfig.setPassword("12345");
// singleServerConfig.setTimeout(3000);
// return Redisson.create(config)
// 本例子使用的是yaml格式的配置文件,读取使用Config.fromYAML,如果是Json文件,则使用Config.fromJSON
Config config = Config.fromYAML(RedissonConfig.class.getClassLoader().getResource("redisson-config.yml"));
return Redisson.create(config);
}
/**
* 主从模式 哨兵模式
*
**/
/* @Bean
public RedissonClient getRedisson() {
RedissonClient redisson;
Config config = new Config();
config.useMasterSlaveServers()
//可以用"rediss://"来启用SSL连接
.setMasterAddress("redis://***(主服务器IP):6379").setPassword("web2017")
.addSlaveAddress("redis://***(从服务器IP):6379")
.setReconnectionTimeout(10000)
.setRetryInterval(5000)
.setTimeout(10000)
.setConnectTimeout(10000);//(连接超时,单位:毫秒 默认值:3000);
// 哨兵模式config.useSentinelServers().setMasterName("mymaster").setPassword("web2017").addSentinelAddress("***(哨兵IP):26379", "***(哨兵IP):26379", "***(哨兵IP):26380");
redisson = Redisson.create(config);
return redisson;
}*/
@Bean
public RedissonDistributeLocker redissonLocker(RedissonClient redissonClient) {
RedissonDistributeLocker locker = new RedissonDistributeLocker(redissonClient);
RedissonLockUtils.setLocker(locker);
return locker;
}
} | 32.191176 | 169 | 0.65418 |
12e4454897a730742d7f79aae6fc37a52736ea0d | 1,799 | /*
* Copyright 2018 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.springframework.cloud.stream.app.twitter.trend.processor;
import java.util.function.Function;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import twitter4j.Trends;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
/**
* @author Christian Tzolov
*/
@Configuration
@EnableConfigurationProperties({ TwitterTrendProcessorProperties.class })
public class TwitterTrendProcessorFunctionConfiguration {
private static final Log logger = LogFactory.getLog(TwitterTrendProcessorFunctionConfiguration.class);
@Bean
public Function<Message<?>, Trends> trend(TwitterTrendProcessorProperties properties, Twitter twitter) {
return message -> {
try {
int woeid = properties.getLocationId().getValue(message, int.class);
return twitter.getPlaceTrends(woeid);
}
catch (TwitterException e) {
logger.error("Twitter API error!", e);
}
return null;
};
}
}
| 32.709091 | 105 | 0.776543 |
73ecdfcf30637afc2abc9091d19aaab299dab5a0 | 144 | package net.tcpshield.tcpshieldapi.response;
import java.util.ArrayList;
public class NetworksResponse extends ArrayList<NetworkResponse> {
}
| 20.571429 | 66 | 0.833333 |
abbae265d6659c2dfd1e332d9c670d5effa23cff | 4,254 | package com.global_relay.globalrelayimagedownloaderproj.view.fragments;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.global_relay.globalrelayimagedownloaderproj.R;
import com.global_relay.globalrelayimagedownloaderproj.view.activities.MainActivity;
import com.global_relay.globalrelayimagedownloaderproj.view_model.ShareImageDownloadViewModel;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ImagePreviewFragment extends Fragment implements Observer<String> {
private ShareImageDownloadViewModel shareImageDownloadViewModel;
private MutableLiveData<String> webData;
@BindView(R.id.btnUrlLoader)
public MaterialButton btnUrlLoader;
@BindView(R.id.editImageUrl)
public TextInputEditText editImageUrl;
@BindView(R.id.webViewImagePreview)
public WebView webViewImagePreview;
public ImagePreviewFragment() {
}
public static ImagePreviewFragment newInstance() {
ImagePreviewFragment fragment = new ImagePreviewFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_preview, container, false);
ButterKnife.bind(this, rootView);
setupWebViewImagePreview();
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
shareImageDownloadViewModel = ViewModelProviders.of(getActivity()).get(ShareImageDownloadViewModel.class);
webData = shareImageDownloadViewModel.getWebData();
webData.observe(getViewLifecycleOwner(), this);
}
private void setupWebViewImagePreview() {
WebSettings webSettings = webViewImagePreview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(true);
webViewImagePreview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webViewImagePreview.setWebViewClient(new AppWebViewClient());
}
private void loadWebViewImagePreview(String data) {
webViewImagePreview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
}
@OnClick({R.id.btnUrlLoader})
public void doClick(View view) {
if (view.getId() == R.id.btnUrlLoader) {
String url = editImageUrl.getText().toString();
if (!Patterns.WEB_URL.matcher(url).matches()) {
editImageUrl.setError(getResources().getString(R.string.invalid_url));
return;
}
shareImageDownloadViewModel.startLoadingData(url);
}
}
@Override
public void onChanged(String webData) {
loadWebViewImagePreview(webData);
}
private static class AppWebViewClient extends WebViewClient {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//super.onReceivedSslError(view, handler, error);
handler.proceed();
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
}
}
| 36.358974 | 114 | 0.744476 |
a709b1ad97cb3f8ef3936d2dc650b5bd2d01bef4 | 552 | package counterforevennumbers;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Class CounterTest.
* Tests Counter class.
*
* @author Mishin Yura ([email protected])
* @since 17.09.2018
*/
public class CounterTest {
/**
* Test add.
*/
@Test
public void whenSumEvenNumbersFromOneToTenThenThirty() {
Counter counter = new Counter();
int expect = 30;
int result = counter.add(1, 10);
assertThat(result, is(expect));
}
}
| 19.714286 | 60 | 0.648551 |
3d506a2c4f1430bb485bbf9d7177c34880879e03 | 1,850 | package gameplayer.front_end.application_scene;
import java.io.File;
import gameplayer.back_end.resources.FrontEndResources;
import gameplayer.front_end.background_display.BackgroundDisplayFactory;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
public abstract class AbstractNavigationPlayerScene extends AbstractPlayerScene implements INavigationDisplay {
private MenuBar myNavigation;
private BorderPane myRoot;
private Background myBackground;
public AbstractNavigationPlayerScene(double aWidth, double aHeight) {
initializeRoot();
initializeScene(aWidth, aHeight);
addNavigation();
}
@Override
public void addNavigationMenu(ImageView aImage, String[] aStringArray, @SuppressWarnings("unchecked") EventHandler<ActionEvent> ... aHandler) {
myNavigation.getMenus().add(getGUIGenerator().createMenu(aImage, aStringArray, aHandler));
}
protected BorderPane getRoot() {
return myRoot;
}
private void initializeRoot() {
myRoot = new BorderPane();
myRoot.setId("pane");
}
public void setBackground(String aFile, double aWidth, double aHeight) {
myBackground = new BackgroundDisplayFactory().buildBackgroundDisplay(aFile, aWidth, aHeight);
myRoot.setBackground(myBackground);
}
private void initializeScene(double aWidth, double aHeight) {
myScene = new Scene(myRoot, aWidth, aHeight);
File file = new File(FrontEndResources.STYLESHEET.getStringResource());
myScene.getStylesheets().add(file.toURI().toString());
getOptions().setMaxWidth(aWidth * .45);
}
private void addNavigation() {
myNavigation = new MenuBar();
myRoot.setTop(myNavigation);
myRoot.setCenter(getOptions());
}
}
| 31.355932 | 144 | 0.784324 |
b5e38367510d9f29610539ea0d0e9c54e8730960 | 4,890 | /*
* Copyright (c) 2021 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.integrations.destination.cassandra;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.datastax.oss.driver.api.core.servererrors.InvalidQueryException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class CassandraCqlProviderIT {
private static final String CASSANDRA_KEYSPACE = "cassandra_keyspace";
private static final String CASSANDRA_TABLE = "cassandra_table";
private CassandraCqlProvider cassandraCqlProvider;
private CassandraNameTransformer nameTransformer;
@BeforeAll
void setup() {
var cassandraContainer = CassandraContainerInitializr.initContainer();
var cassandraConfig = TestDataFactory.createCassandraConfig(
cassandraContainer.getUsername(),
cassandraContainer.getPassword(),
cassandraContainer.getHost(),
cassandraContainer.getFirstMappedPort());
this.cassandraCqlProvider = new CassandraCqlProvider(cassandraConfig);
this.nameTransformer = new CassandraNameTransformer(cassandraConfig);
cassandraCqlProvider.createKeySpaceIfNotExists(CASSANDRA_KEYSPACE, 1);
cassandraCqlProvider.createTableIfNotExists(CASSANDRA_KEYSPACE, CASSANDRA_TABLE);
}
@AfterEach
void clean() {
cassandraCqlProvider.truncate(CASSANDRA_KEYSPACE, CASSANDRA_TABLE);
}
@Test
void testCreateKeySpaceIfNotExists() {
String keyspace = nameTransformer.outputKeyspace("test_keyspace");
assertDoesNotThrow(() -> cassandraCqlProvider.createKeySpaceIfNotExists(keyspace, 1));
}
@Test
void testCreateTableIfNotExists() {
String table = nameTransformer.outputTable("test_stream");
assertDoesNotThrow(() -> cassandraCqlProvider.createTableIfNotExists(CASSANDRA_KEYSPACE, table));
}
@Test
void testInsert() {
// given
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, CASSANDRA_TABLE, "{\"property\":\"data1\"}");
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, CASSANDRA_TABLE, "{\"property\":\"data2\"}");
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, CASSANDRA_TABLE, "{\"property\":\"data3\"}");
// when
var resultSet = cassandraCqlProvider.select(CASSANDRA_KEYSPACE, CASSANDRA_TABLE);
// then
assertThat(resultSet)
.isNotNull()
.hasSize(3)
.anyMatch(r -> r.getData().equals("{\"property\":\"data1\"}"))
.anyMatch(r -> r.getData().equals("{\"property\":\"data2\"}"))
.anyMatch(r -> r.getData().equals("{\"property\":\"data3\"}"));
}
@Test
void testTruncate() {
// given
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, CASSANDRA_TABLE, "{\"property\":\"data1\"}");
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, CASSANDRA_TABLE, "{\"property\":\"data2\"}");
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, CASSANDRA_TABLE, "{\"property\":\"data3\"}");
// when
cassandraCqlProvider.truncate(CASSANDRA_KEYSPACE, CASSANDRA_TABLE);
var resultSet = cassandraCqlProvider.select(CASSANDRA_KEYSPACE, CASSANDRA_TABLE);
// then
assertThat(resultSet)
.isNotNull()
.isEmpty();
}
@Test
void testDropTableIfExists() {
// given
String table = nameTransformer.outputTmpTable("test_stream");
cassandraCqlProvider.createTableIfNotExists(CASSANDRA_KEYSPACE, table);
// when
cassandraCqlProvider.dropTableIfExists(CASSANDRA_KEYSPACE, table);
// then
assertThrows(InvalidQueryException.class, () -> cassandraCqlProvider.select(CASSANDRA_KEYSPACE, table));
}
@Test
void testCopy() {
// given
String tmpTable = nameTransformer.outputTmpTable("test_stream_copy");
cassandraCqlProvider.createTableIfNotExists(CASSANDRA_KEYSPACE, tmpTable);
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, tmpTable, "{\"property\":\"data1\"}");
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, tmpTable, "{\"property\":\"data2\"}");
cassandraCqlProvider.insert(CASSANDRA_KEYSPACE, tmpTable, "{\"property\":\"data3\"}");
String rawTable = nameTransformer.outputTable("test_stream_copy");
cassandraCqlProvider.createTableIfNotExists(CASSANDRA_KEYSPACE, rawTable);
// when
cassandraCqlProvider.copy(CASSANDRA_KEYSPACE, tmpTable, rawTable);
var resultSet = cassandraCqlProvider.select(CASSANDRA_KEYSPACE, rawTable);
// then
assertThat(resultSet)
.isNotNull()
.hasSize(3)
.anyMatch(r -> r.getData().equals("{\"property\":\"data1\"}"))
.anyMatch(r -> r.getData().equals("{\"property\":\"data2\"}"))
.anyMatch(r -> r.getData().equals("{\"property\":\"data3\"}"));
}
}
| 35.955882 | 108 | 0.729652 |
f200ebe70e5e6fa97d448af02aedf8e6b2216729 | 3,616 | package org.apache.ctakes.assertion.medfacts.cleartk.windowed.context.feature.extractor;
import org.apache.ctakes.typesystem.type.syntax.BaseToken;
import org.apache.ctakes.typesystem.type.textsem.IdentifiedAnnotation;
import org.apache.uima.jcas.JCas;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.extractor.CleartkExtractorException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author SPF , chip-nlp
* @version %I%
* @since 12/26/2018
*/
public class WindowedContextWordWindowExtractor extends AbstractWindowedFeatureExtractor1<IdentifiedAnnotation> {
private HashMap<String, Double> termVals = null;
private static final Pattern linePatt = Pattern.compile( "^([^ ]+) : (.+)$" );
private static double[] weights = new double[ 50 ];
static {
weights[ 0 ] = 1.0;
for ( int i = 1; i < weights.length; i++ ) {
weights[ i ] = 1.0 / i;
}
}
public WindowedContextWordWindowExtractor( String resourceFilename ) {
termVals = new HashMap<>();
InputStream is = getClass().getClassLoader().getResourceAsStream( resourceFilename );
Scanner scanner = new Scanner( is );
Matcher m = null;
double max = 0.0;
double maxNeg = 0.0;
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine().trim();
m = linePatt.matcher( line );
if ( m.matches() ) {
double val = Double.parseDouble( m.group( 2 ) );
termVals.put( m.group( 1 ), val );
if ( Math.abs( val ) > max ) {
max = Math.abs( val );
}
if ( val < maxNeg ) {
maxNeg = val;
}
}
}
try {
is.close();
} catch ( IOException e ) {
e.printStackTrace();
}
max = max - maxNeg;
for ( String key : termVals.keySet() ) {
termVals.put( key, (termVals.get( key ) - maxNeg) / max );
}
}
@Override
public List<Feature> extract( JCas view, IdentifiedAnnotation mention )
throws CleartkExtractorException {
ArrayList<Feature> feats = new ArrayList<>();
final List<BaseToken> tokens = _baseTokens;
int startIndex = -1;
int endIndex = -1;
for ( int i = 0; i < tokens.size(); i++ ) {
if ( tokens.get( i ).getBegin() == mention.getBegin() ) {
startIndex = i;
}
if ( tokens.get( i ).getEnd() == mention.getEnd() ) {
endIndex = i;
}
}
double score = 0.0;
double z = 0.0;
String key = null;
double weight;
for ( int i = 0; i < tokens.size(); i++ ) {
key = tokens.get( i ).getCoveredText().toLowerCase();
int dist = Math.min( Math.abs( startIndex - i ), Math.abs( endIndex - i ) );
weight = weightFunction( dist );
z += weight;
if ( termVals.containsKey( key ) ) {
score += (weight * termVals.get( key ));
}
}
score /= z; // weight by actual amount of context so we don't penalize begin/end of sentence.
feats.add( new Feature( "WORD_SCORE", score ) );
return feats;
}
private static final double weightFunction( int dist ) {
if ( dist >= weights.length ) {
return 0.0;
}
// quick decay
// return 1.0 / dist;
// linear decay
// return 1.0 - dist * (1.0/50.0);
// no decay:
return 1.0;
}
}
| 29.16129 | 113 | 0.578263 |
ec52f8e991853d3832d6cbbcf529f83ec3bb53dd | 1,496 | /* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package edu.umass.cs.mallet.base.classify;
import edu.umass.cs.mallet.base.classify.ClassifierEvaluating;
/**
* Created: Apr 13, 2005
*
* @author <A HREF="mailto:[email protected]>[email protected]</A>
* @version $Id: AbstractClassifierEvaluating.java,v 1.1 2005/04/19 17:44:36 casutton Exp $
*/
public abstract class AbstractClassifierEvaluating implements ClassifierEvaluating {
private int numIterToWait = 0;
private int numIterToSkip = 10;
private boolean alwaysEvaluateWhenFinished = true;
public void setNumIterToWait (int numIterToWait)
{
this.numIterToWait = numIterToWait;
}
public void setNumIterToSkip (int numIterToSkip)
{
this.numIterToSkip = numIterToSkip;
}
public void setAlwaysEvaluateWhenFinished (boolean alwaysEvaluateWhenFinished)
{
this.alwaysEvaluateWhenFinished = alwaysEvaluateWhenFinished;
}
protected boolean shouldDoEvaluate (int iter, boolean finished)
{
if (alwaysEvaluateWhenFinished && finished) return true;
return ((iter > numIterToWait) && (iter % numIterToSkip == 0));
}
}
| 34 | 91 | 0.750668 |
5ebfb3b25e7e1dd4c615a1258ebe051b3224f6e2 | 2,303 | /*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID 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.opensaml.xml.security.keyinfo;
import java.util.List;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.credential.StaticCredentialResolver;
/**
* Simple implementation of {@link KeyInfoCredentialResolver} which just stores and returns a static set of credentials.
*
* <p>
* Note: no filtering or other evaluation of the credentials is performed. Any Criteria
* specified are ignored. For a similar Collection-based KeyInfoCredentialResolver implementation which does support
* evaluation and filtering based on supplied evaluable criteria, see {@link CollectionKeyInfoCredentialResolver}.
* </p>
*
* <p>
* This implementation might also be used at the end of a chain of KeyInfoCredentialResolvers in
* order to supply a default, fallback set of credentials, if none could otherwise be resolved.
* </p>
*/
public class StaticKeyInfoCredentialResolver extends StaticCredentialResolver implements KeyInfoCredentialResolver {
/**
* Constructor.
*
* @param credentials collection of credentials to be held by this resolver
*/
public StaticKeyInfoCredentialResolver(List<Credential> credentials) {
super(credentials);
}
/**
* Constructor.
*
* @param credential a single credential to be held by this resolver
*/
public StaticKeyInfoCredentialResolver(Credential credential) {
super(credential);
}
}
| 38.383333 | 120 | 0.748155 |
871cf6cdb28257d29cab94b20ce3e918f5d1f53d | 1,053 | package mekanism.common.integration.crafttweaker.recipe.handler;
import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
import mekanism.api.recipes.GasToGasRecipe;
import net.minecraft.world.item.crafting.Recipe;
@IRecipeHandler.For(GasToGasRecipe.class)
public class GasToGasRecipeHandler extends MekanismRecipeHandler<GasToGasRecipe> {
@Override
public String dumpToCommandString(IRecipeManager manager, GasToGasRecipe recipe) {
return buildCommandString(manager, recipe, recipe.getInput(), recipe.getOutputDefinition());
}
@Override
public <U extends Recipe<?>> boolean doesConflict(IRecipeManager manager, GasToGasRecipe recipe, U o) {
//Only support if the other is a gas to gas recipe and don't bother checking the reverse as the recipe type's generics
// ensures that it is of the same type
return o instanceof GasToGasRecipe other && ingredientConflicts(recipe.getInput(), other.getInput());
}
} | 47.863636 | 126 | 0.779677 |
d11b7bd55764be78d1b67e0f8bc2b1992d4d1e1a | 2,406 | package adt.linkedList.set;
import adt.linkedList.SingleLinkedListImpl;
import adt.linkedList.SingleLinkedListNode;
public class SetLinkedListImpl<T> extends SingleLinkedListImpl<T> implements SetLinkedList<T> {
@Override
public void removeDuplicates() {
if (!isEmpty()) {
SingleLinkedListNode auxHeadA = this.getHead();
SingleLinkedListImpl newNodeB = new SingleLinkedListImpl();
newNodeB.insert(auxHeadA.getData());
while (!auxHeadA.isNIL()) {
if (newNodeB.search(auxHeadA.getData()) == null) {
newNodeB.insert(auxHeadA.getData());
}
auxHeadA = auxHeadA.getNext();
}
this.setHead(newNodeB.getHead());
}
}
@Override
public SetLinkedList<T> union(SetLinkedList<T> otherSet) {
if (otherSet.isEmpty()) {
return this;
}
if (!isEmpty()) {
SingleLinkedListNode auxHead = this.head;
SetLinkedList<T> auxSet = new SetLinkedListImpl<>();
while (!auxHead.isNIL()) {
if (otherSet.search((T) auxHead.getData()) == null) {
otherSet.insert((T) auxHead.getData());
}
auxHead = auxHead.getNext();
}
}
return otherSet;
}
@Override
public SetLinkedList<T> intersection(SetLinkedList<T> otherSet) {
if (!otherSet.isEmpty()) {
return this;
}
if (!isEmpty()) {
SetLinkedList<T> result = new SetLinkedListImpl<>();
if (otherSet != null) {
if (!isEmpty()) {
SingleLinkedListNode<T> auxHeadA = this.head;
while (!auxHeadA.isNIL()) {
if (otherSet.search((T) auxHeadA.getData()) != null) {
result.insert(auxHeadA.getData());
}
auxHeadA = auxHeadA.getNext();
}
}
}
return result;
}
return this;
}
@Override
public void concatenate(SetLinkedList<T> otherSet) {
if (!otherSet.isEmpty()){
if (!isEmpty()){
SingleLinkedListNode<T> auxHead = this.head;
while (!auxHead.getNext().isNIL()){
auxHead = auxHead.getNext();
}
SingleLinkedListImpl<T> a = (SingleLinkedListImpl<T>) otherSet;
auxHead.setNext(a.getHead());
}
}
}
}
| 28.305882 | 95 | 0.545303 |
6411973e75f909387a7e65aa869c602b83622f05 | 1,489 | package com.danyy.zk.listener;
import com.danyy.zk.watcher.ZkWatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 监听器回调处理线程池
*/
public class ListenerProcessPool {
private final static Logger LOGGER = LoggerFactory.getLogger(ZkWatcher.class);
private volatile ThreadPoolExecutor processPool;
public ListenerProcessPool() {
this(2);
}
public ListenerProcessPool(int listenerPoolSize) {
processPool = new ThreadPoolExecutor(1, listenerPoolSize, 30000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100), new ThreadProcessFactory());
}
/**
* 执行监听回调函数
*
* @param path 监听的节点
* @param manager 回调信息
*/
public void invoker(final String path, final ListenerManager manager) {
if (manager != null) {
processPool.submit(new Runnable() {
public void run() {
Listener listener = manager.getListener();
if (listener != null) {
try {
listener.listen(path, manager.getEventType(), manager.getData());
} catch (Exception e) {
LOGGER.error("Invoker listener callback error.", e);
}
}
}
});
}
}
}
| 29.78 | 163 | 0.591672 |
bd5c265fc9a01e587e5aa94de78ee0dc506b90c7 | 1,282 | /*
* Software Name : ATK
*
* Copyright (C) 2007 - 2012 France Télé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.
*
* ------------------------------------------------------------------
* File Name : MyJTextArea.java
*
* Created : 24/06/2010
* Author(s) : HENAFF Mari-Mai
*/
package com.orange.atk.compUI;
import java.awt.Rectangle;
import javax.swing.JTextArea;
import javax.swing.JViewport;
public class MyJTextArea extends JTextArea {
public MyJTextArea() {
super();
}
public MyJTextArea(int row, int col) {
super(row, col);
}
public void scrollRectToVisible(Rectangle aRect) {
if(hasFocus() || getParent() instanceof JViewport)
super.scrollRectToVisible(aRect);
}
}
| 27.276596 | 76 | 0.645086 |
dbb626245b7e1837c8b21270139f1967cec00aa7 | 876 | package common;
/*
* defines constants used by both client and server
* whole message would look like: (length)##(msg type)##(msg body)
* message body would look like: (game status);(player name);(player score);(player attempts);(hint word)
*
*/
public class Constants {
/*
* used to separate different parts( length, type, body)
*/
public static final String MSG_DELIMETER = "##";
/*
* used to separate different fields in the msg body
*/
public static final String GAME_MESSAGE_DELIMETER=";";
/*
* define the position of each part in the whole message
*/
public static final int MSG_LENGTH_INDEX = 0;
public static final int MSG_TYPE_INDEX = 1;
public static final int MSG_BODY_INDEX = 2;
/**
* why 8192?
*/
public static final int MAX_MSG_LENGTH=8192;
}
| 24.333333 | 105 | 0.634703 |
98171f0129b29a4f44fcf477a32c43f8b28b78d4 | 3,975 | /*
* Copyright 1999-2020 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.nacos.core.remote.control;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**
* tps record.
*
* @author liuzunfei
* @version $Id: TpsRecorder.java, v 0.1 2021年01月09日 12:38 PM liuzunfei Exp $
*/
public class TpsRecorder {
private long startTime;
private int slotSize;
private List<TpsSlot> slotList;
public TpsRecorder(long startTime, int recordSize) {
this.startTime = startTime;
this.slotSize = recordSize + 1;
slotList = new ArrayList<>(slotSize);
for (int i = 0; i < slotSize; i++) {
slotList.add(new TpsSlot());
}
}
/**
* get slot of the timestamp second,create if not exist.
*
* @param timeStamp the timestamp second.
* @return
*/
public TpsSlot createPointIfAbsent(long timeStamp) {
long distance = timeStamp - startTime;
long secondDiff = distance / 1000;
long currentWindowTime = startTime + secondDiff * 1000;
int index = (int) secondDiff % slotSize;
if (slotList.get(index).second != currentWindowTime) {
slotList.get(index).reset(currentWindowTime);
}
return slotList.get(index);
}
/**
* get slot of the timestamp second,read only ,return nul if not exist.
*
* @param timeStamp the timestamp second.
* @return
*/
public TpsSlot getPoint(long timeStamp) {
long distance = timeStamp - startTime;
long secondDiff = distance / 1000;
long currentWindowTime = startTime + secondDiff * 1000;
int index = (int) secondDiff % slotSize;
TpsSlot tpsSlot = slotList.get(index);
if (tpsSlot.second != currentWindowTime) {
return null;
}
return tpsSlot;
}
private long maxTps = -1;
/**
* monitor/intercept.
*/
private String monitorType = MonitorType.MONITOR.type;
public long getMaxTps() {
return maxTps;
}
public void setMaxTps(long maxTps) {
this.maxTps = maxTps;
}
public boolean isInterceptMode() {
return MonitorType.INTERCEPT.type.equals(this.monitorType);
}
/**
* clearLimitRule.
*/
public void clearLimitRule() {
this.setMonitorType(MonitorType.MONITOR.type);
this.setMaxTps(-1);
}
public String getMonitorType() {
return monitorType;
}
public void setMonitorType(String monitorType) {
this.monitorType = monitorType;
}
static class TpsSlot {
long second = 0L;
AtomicLong tps = new AtomicLong();
AtomicLong interceptedTps = new AtomicLong();
public AtomicLong reset(long second) {
synchronized (this) {
if (this.second != second) {
this.second = second;
tps.set(0L);
interceptedTps.set(0);
}
}
return tps;
}
@Override
public String toString() {
return "TpsSlot{" + "second=" + second + ", tps=" + tps + '}';
}
}
public List<TpsSlot> getSlotList() {
return slotList;
}
}
| 27.040816 | 77 | 0.588428 |
ca2972b81156e2f18490a72b1c3d0c775412d9cd | 748 | package net.evendanan.coffeetable;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import net.evendanan.coffeetable.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
}
} | 27.703704 | 87 | 0.804813 |
986f2f8239265c86521ff1b7d87fb0841daa3972 | 1,352 | package ru.job4j.coffeemachine;
import org.junit.Test;
import ru.job4j.coffemachine.CoffeeMachine;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* Class CoffeeMachineTest is testing CoffeeMachine's method.
*
* @author Evgeny Shpytev (mailto:[email protected]).
* @version 1.
* @since 21.11.2018.
*/
public class CoffeeMachineTest {
@Test
public void ourChangeIs15() {
CoffeeMachine coffeeMachine = new CoffeeMachine();
int[] result = coffeeMachine.change(50, 35);
int[] expect = {10, 5};
assertThat(result, is(expect));
}
@Test
public void ourChangeIs65() {
CoffeeMachine coffeeMachine = new CoffeeMachine();
int[] result = coffeeMachine.change(100, 35);
int[] expect = {10, 10, 10, 10, 10, 10, 5};
assertThat(result, is(expect));
}
@Test
public void ourChangeIs18() {
CoffeeMachine coffeeMachine = new CoffeeMachine();
int[] result = coffeeMachine.change(53, 35);
int[] expect = {10, 5, 2, 1};
assertThat(result, is(expect));
}
@Test
public void ourChangeIs16() {
CoffeeMachine coffeeMachine = new CoffeeMachine();
int[] result = coffeeMachine.change(51, 35);
int[] expect = {10, 5, 1};
assertThat(result, is(expect));
}
}
| 27.591837 | 61 | 0.630917 |
0f8c766b74547643dc9c308398ce9e675060a3a3 | 52,416 | /*-
* Copyright (C) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle Berkeley
* DB Java Edition made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle Berkeley DB Java Edition for a copy of the
* license and additional information.
*/
package com.sleepycat.je.dbi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.DbInternal;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.util.StringDbt;
import com.sleepycat.je.util.TestUtils;
import com.sleepycat.utilint.StringUtils;
/**
* Various unit tests for CursorImpl.
*/
@RunWith(Parameterized.class)
public class DbCursorTest extends DbCursorTestBase {
@Parameters
public static List<Object[]> genParams() {
return Arrays.asList(new Object[][]{{false}, {true}});
}
public DbCursorTest(boolean keyPrefixing) {
super();
this.keyPrefixing = keyPrefixing;
customName = (keyPrefixing) ? "keyPrefixing" : "";
}
private boolean alreadyTornDown = false;
/**
* Put a small number of data items into the database in a specific order
* and ensure that they read back in ascending order.
*/
@Test
public void testSimpleGetPut()
throws Throwable {
try {
initEnv(false);
doSimpleCursorPuts();
DataWalker dw = new DataWalker(simpleDataMap) {
@Override
void perData(String foundKey, String foundData) {
assertTrue(foundKey.compareTo(prevKey) >= 0);
prevKey = foundKey;
}
};
dw.walkData();
assertTrue(dw.nEntries == simpleKeyStrings.length);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Test the internal Cursor.advanceCursor() entrypoint.
*/
@Test
public void testCursorAdvance()
throws Throwable {
try {
initEnv(false);
doSimpleCursorPuts();
StringDbt foundKey = new StringDbt();
StringDbt foundData = new StringDbt();
String prevKey = "";
OperationStatus status = cursor.getFirst(foundKey, foundData,
LockMode.DEFAULT);
/*
* Advance forward and then back to the first. Rest of scan
* should be as normal.
*/
DbInternal.advanceCursor(cursor, foundKey, foundData);
DbInternal.retrieveNext
(cursor, foundKey, foundData, LockMode.DEFAULT, GetMode.PREV);
int nEntries = 0;
while (status == OperationStatus.SUCCESS) {
String foundKeyString = foundKey.getString();
String foundDataString = foundData.getString();
assertTrue(foundKeyString.compareTo(prevKey) >= 0);
prevKey = foundKeyString;
nEntries++;
status = cursor.getNext(foundKey, foundData, LockMode.DEFAULT);
}
assertTrue(nEntries == simpleKeyStrings.length);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Put a small number of data items into the database in a specific order
* and ensure that they read back in descending order.
*/
@Test
public void testSimpleGetPutBackwards()
throws Throwable {
try {
initEnv(false);
doSimpleCursorPuts();
DataWalker dw = new BackwardsDataWalker(simpleDataMap) {
@Override
void perData(String foundKey, String foundData) {
if (!prevKey.equals("")) {
assertTrue(foundKey.compareTo(prevKey) <= 0);
}
prevKey = foundKey;
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
dw.walkData();
assertTrue(dw.nEntries == simpleKeyStrings.length);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Put a small number of data items into the database in a specific order
* and ensure that they read back in descending order. When "quux" is
* found, insert "fub" into the database and make sure that it is also read
* back in the cursor.
*/
@Test
public void testSimpleGetPut2()
throws Throwable {
try {
initEnv(false);
doSimpleGetPut2("quux", "fub");
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
public void doSimpleGetPut2(String whenFoundDoInsert,
String newKey)
throws DatabaseException {
doSimpleCursorPuts();
DataWalker dw =
new BackwardsDataWalker(whenFoundDoInsert, newKey, simpleDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (foundKey.equals(whenFoundDoInsert)) {
putAndVerifyCursor(cursor2, new StringDbt(newKey),
new StringDbt("ten"), true);
simpleDataMap.put(newKey, "ten");
}
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
dw.walkData();
assertTrue(dw.nEntries == simpleKeyStrings.length + 1);
}
/**
* Iterate through each of the keys in the list of "simple keys". For each
* one, create the database afresh, iterate through the entries in
* ascending order, and when the key being tested is found, insert the next
* highest key into the database. Make sure that the key just inserted is
* retrieved during the cursor walk. Lather, rinse, repeat.
*/
@Test
public void testSimpleGetPutNextKeyForwardTraverse()
throws Throwable {
try {
tearDown();
for (int i = 0; i < simpleKeyStrings.length; i++) {
setUp();
initEnv(false);
doSimpleGetPut(true,
simpleKeyStrings[i],
nextKey(simpleKeyStrings[i]),
1);
tearDown();
}
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Iterate through each of the keys in the list of "simple keys". For each
* one, create the database afresh, iterate through the entries in
* ascending order, and when the key being tested is found, insert the next
* lowest key into the database. Make sure that the key just inserted is
* not retrieved during the cursor walk. Lather, rinse, repeat.
*/
@Test
public void testSimpleGetPutPrevKeyForwardTraverse()
throws Throwable {
try {
tearDown();
for (int i = 0; i < simpleKeyStrings.length; i++) {
setUp();
initEnv(false);
doSimpleGetPut(true, simpleKeyStrings[i],
prevKey(simpleKeyStrings[i]), 0);
tearDown();
}
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Iterate through each of the keys in the list of "simple keys". For each
* one, create the database afresh, iterate through the entries in
* descending order, and when the key being tested is found, insert the
* next lowest key into the database. Make sure that the key just inserted
* is retrieved during the cursor walk. Lather, rinse, repeat.
*/
@Test
public void testSimpleGetPutPrevKeyBackwardsTraverse() {
try {
tearDown();
for (int i = 0; i < simpleKeyStrings.length; i++) {
setUp();
initEnv(false);
doSimpleGetPut(false, simpleKeyStrings[i],
prevKey(simpleKeyStrings[i]), 1);
tearDown();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Iterate through each of the keys in the list of "simple keys". For each
* one, create the database afresh, iterate through the entries in
* descending order, and when the key being tested is found, insert the
* next highest key into the database. Make sure that the key just
* inserted is not retrieved during the cursor walk. Lather, rinse,
* repeat.
*/
@Test
public void testSimpleGetPutNextKeyBackwardsTraverse()
throws Throwable {
try {
tearDown();
for (int i = 0; i < simpleKeyStrings.length; i++) {
setUp();
initEnv(false);
doSimpleGetPut(true, simpleKeyStrings[i],
prevKey(simpleKeyStrings[i]), 0);
tearDown();
}
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for the above four tests.
*/
private void doSimpleGetPut(boolean forward,
String whenFoundDoInsert,
String newKey,
int additionalEntries)
throws DatabaseException {
doSimpleCursorPuts();
DataWalker dw;
if (forward) {
dw = new DataWalker(whenFoundDoInsert, newKey, simpleDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (foundKey.equals(whenFoundDoInsert)) {
putAndVerifyCursor(cursor2, new StringDbt(newKey),
new StringDbt("ten"), true);
simpleDataMap.put(newKey, "ten");
}
}
};
} else {
dw = new BackwardsDataWalker(whenFoundDoInsert,
newKey,
simpleDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (foundKey.equals(whenFoundDoInsert)) {
putAndVerifyCursor(cursor2, new StringDbt(newKey),
new StringDbt("ten"), true);
simpleDataMap.put(newKey, "ten");
}
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
}
dw.walkData();
assertEquals(simpleKeyStrings.length + additionalEntries, dw.nEntries);
}
/**
* Put a small number of data items into the database in a specific order
* and ensure that they read back in descending order. Replace the data
* portion for each one, then read back again and make sure it was replaced
* properly.
*/
@Test
public void testSimpleReplace()
throws Throwable {
try {
initEnv(false);
doSimpleReplace();
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
public void doSimpleReplace()
throws DatabaseException {
doSimpleCursorPuts();
DataWalker dw =
new DataWalker(simpleDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
String newData = foundData + "x";
cursor.putCurrent(new StringDbt(newData));
simpleDataMap.put(foundKey, newData);
}
};
dw.walkData();
dw = new DataWalker(simpleDataMap) {
@Override
void perData(String foundKey, String foundData) {
assertTrue(foundData.equals(simpleDataMap.get(foundKey)));
}
};
dw.walkData();
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* ascending order. After each element is retrieved, insert the next
* lowest key into the tree. Ensure that the element just inserted is not
* returned by the cursor. Ensure that the elements are returned in
* ascending order. Lather, rinse, repeat.
*/
@Test
public void testLargeGetPutPrevKeyForwardTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutPrevKeyForwardTraverse();
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutPrevKeyForwardTraverse()
throws DatabaseException {
Hashtable dataMap = new Hashtable();
doLargePut(dataMap, N_KEYS);
DataWalker dw = new DataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
assertTrue(foundKey.compareTo(prevKey) >= 0);
putAndVerifyCursor(cursor2,
new StringDbt(prevKey(foundKey)),
new StringDbt
(Integer.toString(dataMap.size() +
nEntries)),
true);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
assertTrue(dw.nEntries == N_KEYS);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree
* in ascending order. Ensure that count() always returns 1 for each
* data item returned.
*/
@Test
public void testLargeCount()
throws Throwable {
try {
initEnv(false);
doLargeCount();
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeCount()
throws DatabaseException {
Hashtable dataMap = new Hashtable();
doLargePut(dataMap, N_KEYS);
DataWalker dw = new DataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
assertTrue(cursor.count() == 1);
assertTrue(foundKey.compareTo(prevKey) >= 0);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
assertTrue(dw.nEntries == N_KEYS);
}
public void xxtestGetPerf()
throws Throwable {
try {
initEnv(false);
final int N = 50000;
int count = 0;
doLargePutPerf(N);
StringDbt foundKey = new StringDbt();
StringDbt foundData = new StringDbt();
OperationStatus status;
status = cursor.getFirst(foundKey, foundData, LockMode.DEFAULT);
while (status == OperationStatus.SUCCESS) {
status = cursor.getNext(foundKey, foundData, LockMode.DEFAULT);
count++;
}
assertTrue(count == N);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Insert a bunch of key/data pairs. Read them back and replace each of
* the data. Read the pairs back again and make sure the replace did the
* right thing.
*/
@Test
public void testLargeReplace()
throws Throwable {
try {
initEnv(false);
Hashtable dataMap = new Hashtable();
doLargePut(dataMap, N_KEYS);
DataWalker dw = new DataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
String newData = foundData + "x";
cursor.putCurrent(new StringDbt(newData));
dataMap.put(foundKey, newData);
}
};
dw.walkData();
dw = new DataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData) {
assertTrue(foundData.equals(dataMap.get(foundKey)));
dataMap.remove(foundKey);
}
};
dw.walkData();
assertTrue(dw.nEntries == N_KEYS);
assertTrue(dataMap.size() == 0);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* descending order. After each element is retrieved, insert the next
* highest key into the tree. Ensure that the element just inserted is not
* returned by the cursor. Ensure that the elements are returned in
* descending order. Lather, rinse, repeat.
*/
@Test
public void testLargeGetPutNextKeyBackwardsTraverse()
throws Throwable {
try {
tearDown();
for (int i = 0; i < N_ITERS; i++) {
setUp();
initEnv(false);
doLargeGetPutNextKeyBackwardsTraverse();
tearDown();
}
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutNextKeyBackwardsTraverse()
throws DatabaseException {
Hashtable dataMap = new Hashtable();
doLargePut(dataMap, N_KEYS);
DataWalker dw = new BackwardsDataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (!prevKey.equals("")) {
assertTrue(foundKey.compareTo(prevKey) <= 0);
}
putAndVerifyCursor(cursor2,
new StringDbt(nextKey(foundKey)),
new StringDbt
(Integer.toString(dataMap.size() +
nEntries)),
true);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
assertTrue(dw.nEntries == N_KEYS);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* ascending order. After each element is retrieved, insert the next
* highest key into the tree. Ensure that the element just inserted is
* returned by the cursor. Ensure that the elements are returned in
* ascending order. Lather, rinse, repeat.
*/
@Test
public void testLargeGetPutNextKeyForwardTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutNextKeyForwardTraverse(N_KEYS);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutNextKeyForwardTraverse(int nKeys)
throws DatabaseException {
Hashtable dataMap = new Hashtable();
Hashtable addedDataMap = new Hashtable();
doLargePut(dataMap, nKeys);
DataWalker dw = new DataWalker(dataMap, addedDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
assertTrue(foundKey.compareTo(prevKey) >= 0);
if (addedDataMap.get(foundKey) == null) {
String newKey = nextKey(foundKey);
String newData =
Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
addedDataMap.put(newKey, newData);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
} else {
addedDataMap.remove(foundKey);
}
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
if (addedDataMap.size() > 0) {
System.out.println(addedDataMap);
fail("addedDataMap still has entries");
}
assertTrue(dw.nEntries == nKeys * 2);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* descending order. After each element is retrieved, insert the next
* lowest key into the tree. Ensure that the element just inserted is
* returned by the cursor. Ensure that the elements are returned in
* descending order. Lather, rinse, repeat.
*/
@Test
public void testLargeGetPutPrevKeyBackwardsTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutPrevKeyBackwardsTraverse(N_KEYS);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutPrevKeyBackwardsTraverse(int nKeys)
throws DatabaseException {
Hashtable dataMap = new Hashtable();
Hashtable addedDataMap = new Hashtable();
doLargePut(dataMap, nKeys);
DataWalker dw = new BackwardsDataWalker(dataMap, addedDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (!prevKey.equals("")) {
assertTrue(foundKey.compareTo(prevKey) <= 0);
}
if (addedDataMap.get(foundKey) == null) {
String newKey = prevKey(foundKey);
String newData =
Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
addedDataMap.put(newKey, newData);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
} else {
addedDataMap.remove(foundKey);
}
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
if (addedDataMap.size() > 0) {
System.out.println(addedDataMap);
fail("addedDataMap still has entries");
}
assertTrue(dw.nEntries == nKeys * 2);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* ascending order. After each element is retrieved, insert the next
* highest and next lowest keys into the tree. Ensure that the next
* highest element just inserted is returned by the cursor. Ensure that
* the elements are returned in ascending order. Lather, rinse, repeat.
*/
@Test
public void testLargeGetPutBothKeyForwardTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutBothKeyForwardTraverse(N_KEYS);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutBothKeyForwardTraverse(int nKeys)
throws DatabaseException {
Hashtable dataMap = new Hashtable();
Hashtable addedDataMap = new Hashtable();
doLargePut(dataMap, nKeys);
DataWalker dw = new DataWalker(dataMap, addedDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
assertTrue(foundKey.compareTo(prevKey) >= 0);
if (addedDataMap.get(foundKey) == null) {
String newKey = nextKey(foundKey);
String newData =
Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
addedDataMap.put(newKey, newData);
newKey = prevKey(foundKey);
newData = Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
} else {
addedDataMap.remove(foundKey);
}
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
if (addedDataMap.size() > 0) {
System.out.println(addedDataMap);
fail("addedDataMap still has entries");
}
assertTrue(dw.nEntries == nKeys * 2);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* descending order. After each element is retrieved, insert the next
* highest and next lowest keys into the tree. Ensure that the next lowest
* element just inserted is returned by the cursor. Ensure that the
* elements are returned in descending order. Lather, rinse, repeat.
*/
@Test
public void testLargeGetPutBothKeyBackwardsTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutBothKeyBackwardsTraverse(N_KEYS);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutBothKeyBackwardsTraverse(int nKeys)
throws DatabaseException {
Hashtable dataMap = new Hashtable();
Hashtable addedDataMap = new Hashtable();
doLargePut(dataMap, nKeys);
DataWalker dw = new BackwardsDataWalker(dataMap, addedDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (!prevKey.equals("")) {
assertTrue(foundKey.compareTo(prevKey) <= 0);
}
if (addedDataMap.get(foundKey) == null) {
String newKey = nextKey(foundKey);
String newData =
Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
newKey = prevKey(foundKey);
newData = Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
addedDataMap.put(newKey, newData);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
} else {
addedDataMap.remove(foundKey);
}
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
if (addedDataMap.size() > 0) {
System.out.println(addedDataMap);
fail("addedDataMap still has entries");
}
assertTrue(dw.nEntries == nKeys * 2);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* ascending order. After each element is retrieved, insert a new random
* key/data pair into the tree. Ensure that the element just inserted is
* returned by the cursor if it is greater than the current element.
* Ensure that the elements are returned in ascending order. Lather,
* rinse, repeat.
*/
@Test
public void testLargeGetPutRandomKeyForwardTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutRandomKeyForwardTraverse(N_KEYS);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutRandomKeyForwardTraverse(int nKeys)
throws DatabaseException {
Hashtable dataMap = new Hashtable();
Hashtable addedDataMap = new Hashtable();
doLargePut(dataMap, nKeys);
DataWalker dw = new DataWalker(dataMap, addedDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
assertTrue(foundKey.compareTo(prevKey) >= 0);
byte[] key = new byte[N_KEY_BYTES];
TestUtils.generateRandomAlphaBytes(key);
String newKey = StringUtils.fromUTF8(key);
String newData =
Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
if (newKey.compareTo(foundKey) > 0) {
addedDataMap.put(newKey, newData);
extraVisibleEntries++;
}
if (addedDataMap.get(foundKey) == null) {
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
} else {
if (addedDataMap.remove(foundKey) == null) {
fail(foundKey + " not found in either datamap");
}
}
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
if (addedDataMap.size() > 0) {
System.out.println(addedDataMap);
fail("addedDataMap still has entries");
}
assertTrue(dw.nEntries == nKeys + dw.extraVisibleEntries);
}
/**
* Insert N_KEYS data items into a tree. Iterate through the tree in
* descending order. After each element is retrieved, insert a new random
* key/data pair into the tree. Ensure that the element just inserted is
* returned by the cursor if it is less than the current element. Ensure
* that the elements are returned in descending order. Lather, rinse,
* repeat.
*/
@Test
public void testLargeGetPutRandomKeyBackwardsTraverse()
throws Throwable {
try {
initEnv(false);
doLargeGetPutRandomKeyBackwardsTraverse(N_KEYS);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetPutRandomKeyBackwardsTraverse(int nKeys)
throws DatabaseException {
Hashtable dataMap = new Hashtable();
Hashtable addedDataMap = new Hashtable();
doLargePut(dataMap, nKeys);
DataWalker dw = new BackwardsDataWalker(dataMap, addedDataMap) {
@Override
void perData(String foundKey, String foundData)
throws DatabaseException {
if (!prevKey.equals("")) {
assertTrue(foundKey.compareTo(prevKey) <= 0);
}
byte[] key = new byte[N_KEY_BYTES];
TestUtils.generateRandomAlphaBytes(key);
String newKey = StringUtils.fromUTF8(key);
String newData =
Integer.toString(dataMap.size() + nEntries);
putAndVerifyCursor(cursor2,
new StringDbt(newKey),
new StringDbt(newData),
true);
if (newKey.compareTo(foundKey) < 0) {
addedDataMap.put(newKey, newData);
extraVisibleEntries++;
}
if (addedDataMap.get(foundKey) == null) {
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
} else {
if (addedDataMap.remove(foundKey) == null) {
fail(foundKey + " not found in either datamap");
}
}
}
@Override
OperationStatus getFirst(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getLast(foundKey, foundData,
LockMode.DEFAULT);
}
@Override
OperationStatus getData(StringDbt foundKey,
StringDbt foundData)
throws DatabaseException {
return cursor.getPrev(foundKey, foundData,
LockMode.DEFAULT);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
if (addedDataMap.size() > 0) {
System.out.println(addedDataMap);
fail("addedDataMap still has entries");
}
assertTrue(dw.nEntries == nKeys + dw.extraVisibleEntries);
}
/**
* Insert N_KEYS data items into a tree. Set a btreeComparison function.
* Iterate through the tree in ascending order. Ensure that the elements
* are returned in ascending order.
*/
@Test
public void testLargeGetForwardTraverseWithNormalComparisonFunction()
throws Throwable {
try {
tearDown();
btreeComparisonFunction = btreeComparator;
setUp();
initEnv(false);
doLargeGetForwardTraverseWithNormalComparisonFunction();
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetForwardTraverseWithNormalComparisonFunction()
throws DatabaseException {
Hashtable dataMap = new Hashtable();
doLargePut(dataMap, N_KEYS);
DataWalker dw = new DataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData) {
assertTrue(foundKey.compareTo(prevKey) >= 0);
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
assertTrue(dw.nEntries == N_KEYS);
}
/**
* Insert N_KEYS data items into a tree. Set a reverse order
* btreeComparison function. Iterate through the tree in ascending order.
* Ensure that the elements are returned in ascending order.
*/
@Test
public void testLargeGetForwardTraverseWithReverseComparisonFunction()
throws Throwable {
try {
tearDown();
btreeComparisonFunction = reverseBtreeComparator;
setUp();
initEnv(false);
doLargeGetForwardTraverseWithReverseComparisonFunction();
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
/**
* Helper routine for above.
*/
private void doLargeGetForwardTraverseWithReverseComparisonFunction()
throws DatabaseException {
Hashtable dataMap = new Hashtable();
doLargePut(dataMap, N_KEYS);
DataWalker dw = new DataWalker(dataMap) {
@Override
void perData(String foundKey, String foundData) {
if (prevKey.length() != 0) {
assertTrue(foundKey.compareTo(prevKey) <= 0);
}
prevKey = foundKey;
assertTrue(dataMap.get(foundKey) != null);
dataMap.remove(foundKey);
}
};
dw.walkData();
if (dataMap.size() > 0) {
fail("dataMap still has entries");
}
assertTrue(dw.nEntries == N_KEYS);
}
@Test
public void testNullKeyAndDataParams()
throws Throwable {
try {
initEnv(false);
/* Put some data so that we can get a cursor. */
doSimpleCursorPuts();
DataWalker dw = new DataWalker(simpleDataMap) {
@Override
void perData(String foundKey, String foundData) {
/* getCurrent() */
try {
cursor.getCurrent(
new StringDbt(""), null,
LockMode.DEFAULT);
} catch (Throwable IAE) {
fail("null data is allowed");
}
try {
cursor.getCurrent(
null, new StringDbt(""),
LockMode.DEFAULT);
} catch (Throwable IAE) {
fail("null key is allowed");
}
/* getFirst() */
try {
Cursor c = cursor.dup(true);
c.getFirst(
new StringDbt(""), null,
LockMode.DEFAULT);
c.close();
} catch (Throwable IAE) {
fail("null data is allowed");
}
try {
Cursor c = cursor.dup(true);
c.getFirst(
null, new StringDbt(""),
LockMode.DEFAULT);
c.close();
} catch (Throwable IAE) {
fail("null key is allowed");
}
/* getNext(), getPrev, getNextDup,
getNextNoDup, getPrevNoDup */
try {
Cursor c = cursor.dup(true);
c.getNext(
new StringDbt(""),
null, LockMode.DEFAULT);
c.close();
} catch (Throwable IAE) {
fail("null data is allowed");
}
try {
Cursor c = cursor.dup(true);
c.getNext(
null, new StringDbt(""),
LockMode.DEFAULT);
c.close();
} catch (Throwable IAE) {
fail("null key is allowed");
}
/* putXXX() */
try {
cursor.put(new StringDbt(""), null);
fail("didn't throw IllegalArgumentException");
} catch (IllegalArgumentException IAE) {
} catch (DatabaseException DBE) {
fail("threw DatabaseException not " +
"IllegalArgumentException");
}
try {
cursor.put(null, new StringDbt(""));
fail("didn't throw IllegalArgumentException");
} catch (IllegalArgumentException IAE) {
} catch (DatabaseException DBE) {
fail("threw DatabaseException not " +
"IllegalArgumentException");
}
}
};
dw.walkData();
assertTrue(dw.nEntries == simpleKeyStrings.length);
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
@Test
public void testCursorOutOfBoundsBackwards()
throws Throwable {
try {
initEnv(false);
doSimpleCursorPuts();
StringDbt foundKey = new StringDbt();
StringDbt foundData = new StringDbt();
OperationStatus status;
status = cursor.getFirst(foundKey, foundData, LockMode.DEFAULT);
assertEquals(OperationStatus.SUCCESS, status);
assertEquals("aaa", foundKey.getString());
assertEquals("four", foundData.getString());
status = cursor.getPrev(foundKey, foundData, LockMode.DEFAULT);
assertEquals(OperationStatus.NOTFOUND, status);
status = cursor.getNext(foundKey, foundData, LockMode.DEFAULT);
assertEquals(OperationStatus.SUCCESS, status);
assertEquals("bar", foundKey.getString());
assertEquals("two", foundData.getString());
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
@Test
public void testCursorOutOfBoundsForwards()
throws Throwable {
try {
initEnv(false);
doSimpleCursorPuts();
StringDbt foundKey = new StringDbt();
StringDbt foundData = new StringDbt();
OperationStatus status;
status = cursor.getLast(foundKey, foundData, LockMode.DEFAULT);
assertEquals(OperationStatus.SUCCESS, status);
assertEquals("quux", foundKey.getString());
assertEquals("seven", foundData.getString());
status = cursor.getNext(foundKey, foundData, LockMode.DEFAULT);
assertEquals(OperationStatus.NOTFOUND, status);
status = cursor.getPrev(foundKey, foundData, LockMode.DEFAULT);
assertEquals(OperationStatus.SUCCESS, status);
assertEquals("mumble", foundKey.getString());
assertEquals("eight", foundData.getString());
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
@Test
public void testTwiceClosedCursor()
throws Throwable {
try {
initEnv(false);
doSimpleCursorPuts();
Cursor cursor = exampleDb.openCursor(null, null);
cursor.close();
try {
cursor.close();
} catch (Exception e) {
fail("Caught Exception while re-closing a Cursor.");
}
try {
cursor.put
(new StringDbt("bogus"), new StringDbt("thingy"));
fail("Expected IllegalStateException for re-use of cursor");
} catch (IllegalStateException DBE) {
}
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
@Test
public void testTreeSplittingWithDeletedIdKey()
throws Throwable {
treeSplittingWithDeletedIdKeyWorker();
}
@Test
public void testTreeSplittingWithDeletedIdKeyWithUserComparison()
throws Throwable {
tearDown();
btreeComparisonFunction = btreeComparator;
setUp();
treeSplittingWithDeletedIdKeyWorker();
}
static private Comparator btreeComparator = new BtreeComparator();
static private Comparator reverseBtreeComparator =
new ReverseBtreeComparator();
private void treeSplittingWithDeletedIdKeyWorker()
throws Throwable {
initEnv(false);
StringDbt data = new StringDbt("data");
Cursor cursor = exampleDb.openCursor(null, null);
cursor.put(new StringDbt("AGPFX"), data);
cursor.put(new StringDbt("AHHHH"), data);
cursor.put(new StringDbt("AIIII"), data);
cursor.put(new StringDbt("AAAAA"), data);
cursor.put(new StringDbt("AABBB"), data);
cursor.put(new StringDbt("AACCC"), data);
cursor.close();
exampleDb.delete(null, new StringDbt("AGPFX"));
exampleEnv.compress();
cursor = exampleDb.openCursor(null, null);
cursor.put(new StringDbt("AAAAB"), data);
cursor.put(new StringDbt("AAAAC"), data);
cursor.close();
validateDatabase();
}
}
| 35.06087 | 99 | 0.495631 |
28e14e782d9e5a0880a17730cebf87b2020a18ef | 139 | package com.example.scavengerhunt.ViewModels;
import androidx.lifecycle.ViewModel;
public class LocationViewModel extends ViewModel {
}
| 17.375 | 50 | 0.834532 |
9907eca1bd07a416483ccfcb74df9660e6c160a7 | 9,569 | package technology.tabula;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.awt.geom.PathIterator.*;
class ObjectExtractorStreamEngine extends PDFGraphicsStreamEngine {
protected List<Ruling> rulings;
private AffineTransform pageTransform;
private boolean extractRulingLines = true;
private Logger logger;
private int clipWindingRule = -1;
private GeneralPath currentPath = new GeneralPath();
private static final float RULING_MINIMUM_LENGTH = 0.01f;
protected ObjectExtractorStreamEngine(PDPage page) {
super(page);
logger = LoggerFactory.getLogger(ObjectExtractorStreamEngine.class);
rulings = new ArrayList<>();
// Calculate page transform:
pageTransform = new AffineTransform();
PDRectangle pageCropBox = getPage().getCropBox();
int rotationAngleInDegrees = getPage().getRotation();
if (Math.abs(rotationAngleInDegrees) == 90 || Math.abs(rotationAngleInDegrees) == 270) {
double rotationAngleInRadians = rotationAngleInDegrees * (Math.PI / 180.0);
pageTransform = AffineTransform.getRotateInstance(rotationAngleInRadians, 0, 0);
} else {
double deltaX = 0;
double deltaY = pageCropBox.getHeight();
pageTransform.concatenate(AffineTransform.getTranslateInstance(deltaX, deltaY));
}
pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
pageTransform.translate(-pageCropBox.getLowerLeftX(), -pageCropBox.getLowerLeftY());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) {
currentPath.moveTo((float) p0.getX(), (float) p0.getY());
currentPath.lineTo((float) p1.getX(), (float) p1.getY());
currentPath.lineTo((float) p2.getX(), (float) p2.getY());
currentPath.lineTo((float) p3.getX(), (float) p3.getY());
currentPath.closePath();
}
@Override
public void clip(int windingRule) {
// The clipping path will not be updated until the succeeding painting
// operator is called.
clipWindingRule = windingRule;
}
@Override
public void closePath() {
currentPath.closePath();
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) {
currentPath.curveTo(x1, y1, x2, y2, x3, y3);
}
@Override
public void drawImage(PDImage arg0) {}
@Override
public void endPath() {
if (clipWindingRule != -1) {
currentPath.setWindingRule(clipWindingRule);
getGraphicsState().intersectClippingPath(currentPath);
clipWindingRule = -1;
}
currentPath.reset();
}
@Override
public void fillAndStrokePath(int arg0) {
strokeOrFillPath(true);
}
@Override
public void fillPath(int arg0) {
strokeOrFillPath(true);
}
@Override
public Point2D getCurrentPoint() {
return currentPath.getCurrentPoint();
}
@Override
public void lineTo(float x, float y) {
currentPath.lineTo(x, y);
}
@Override
public void moveTo(float x, float y) {
currentPath.moveTo(x, y);
}
@Override
public void shadingFill(COSName arg0) {}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
@Override
public void strokePath() {
strokeOrFillPath(false);
}
private void strokeOrFillPath(boolean isFill) {
if (!extractRulingLines) {
currentPath.reset();
return;
}
boolean didNotPassedTheFilter = filterPathBySegmentType();
if (didNotPassedTheFilter) return;
// TODO: how to implement color filter?
// Skip the first path operation and save it as the starting point.
PathIterator pathIterator = currentPath.getPathIterator(getPageTransform());
float[] coordinates = new float[6];
int currentSegment;
Point2D.Float startPoint = getStartPoint(pathIterator);
Point2D.Float last_move = startPoint;
Point2D.Float endPoint = null;
Line2D.Float line;
PointComparator pointComparator = new PointComparator();
while (!pathIterator.isDone()) {
pathIterator.next();
// This can be the last segment, when pathIterator.isDone, but we need to
// process it otherwise us-017.pdf fails the last value.
try {
currentSegment = pathIterator.currentSegment(coordinates);
} catch (IndexOutOfBoundsException ex) {
continue;
}
switch (currentSegment) {
case SEG_LINETO:
endPoint = new Point2D.Float(coordinates[0], coordinates[1]);
if (startPoint == null || endPoint == null) {
break;
}
line = getLineBetween(startPoint, endPoint, pointComparator);
verifyLineIntersectsClipping(line);
break;
case SEG_MOVETO:
last_move = new Point2D.Float(coordinates[0], coordinates[1]);
endPoint = last_move;
break;
case SEG_CLOSE:
// According to PathIterator docs:
// "The preceding sub-path should be closed by appending a line
// segment back to the point corresponding to the most recent
// SEG_MOVETO."
if (startPoint == null || endPoint == null) {
break;
}
line = getLineBetween(endPoint, last_move, pointComparator);
verifyLineIntersectsClipping(line);
break;
}
startPoint = endPoint;
}
currentPath.reset();
}
private boolean filterPathBySegmentType() {
PathIterator pathIterator = currentPath.getPathIterator(pageTransform);
float[] coordinates = new float[6];
int currentSegmentType = pathIterator.currentSegment(coordinates);
if (currentSegmentType != SEG_MOVETO) {
currentPath.reset();
return true;
}
pathIterator.next();
while (!pathIterator.isDone()) {
currentSegmentType = pathIterator.currentSegment(coordinates);
if (currentSegmentType != SEG_LINETO && currentSegmentType != SEG_CLOSE && currentSegmentType != SEG_MOVETO) {
currentPath.reset();
return true;
}
pathIterator.next();
}
return false;
}
private Point2D.Float getStartPoint(PathIterator pathIterator) {
float[] startPointCoordinates = new float[6];
pathIterator.currentSegment(startPointCoordinates);
float x = Utils.round(startPointCoordinates[0], 2);
float y = Utils.round(startPointCoordinates[1], 2);
return new Point2D.Float(x, y);
}
private Line2D.Float getLineBetween(Point2D.Float pointA, Point2D.Float pointB, PointComparator pointComparator) {
if (pointComparator.compare(pointA, pointB) == -1) {
return new Line2D.Float(pointA, pointB);
}
return new Line2D.Float(pointB, pointA);
}
private void verifyLineIntersectsClipping(Line2D.Float line) {
Rectangle2D currentClippingPath = currentClippingPath();
if (line.intersects(currentClippingPath)) {
Ruling ruling = new Ruling(line.getP1(), line.getP2()).intersect(currentClippingPath);
if (ruling.length() > RULING_MINIMUM_LENGTH) {
rulings.add(ruling);
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
public AffineTransform getPageTransform() {
return pageTransform;
}
public Rectangle2D currentClippingPath() {
Shape currentClippingPath = getGraphicsState().getCurrentClippingPath();
Shape transformedClippingPath = getPageTransform().createTransformedShape(currentClippingPath);
return transformedClippingPath.getBounds2D();
}
// TODO: repeated in SpreadsheetExtractionAlgorithm.
class PointComparator implements Comparator<Point2D> {
@Override
public int compare(Point2D p1, Point2D p2) {
float p1X = Utils.round(p1.getX(), 2);
float p1Y = Utils.round(p1.getY(), 2);
float p2X = Utils.round(p2.getX(), 2);
float p2Y = Utils.round(p2.getY(), 2);
if (p1Y > p2Y)
return 1;
if (p1Y < p2Y)
return -1;
if (p1X > p2X)
return 1;
if (p1X < p2X)
return -1;
return 0;
}
}
}
| 35.180147 | 122 | 0.601839 |
cb73516f5cdf5449ef863f877a3e40c34533a8e9 | 257 | package com.store.catalog.dao;
import com.store.catalog.model.Category;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface CategoryDao extends CrudRepository<Category, Long> {
}
| 23.363636 | 69 | 0.832685 |
6d5e35553588674706f8870d0aae589bb8352948 | 4,836 | package com.example.aidongprover2;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Hobby> hobbyList = new ArrayList<>();
private HobbyAdapter adapter;
private DrawerLayout mDrawerLayout;
private TextView header_user_name;
private NavigationView mNavView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavView = (NavigationView) findViewById(R.id.nav_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
View headerView = mNavView.getHeaderView(0);
header_user_name = (TextView)headerView.findViewById(R.id.username);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("爱动");
ActionBar actionBar = getSupportActionBar();
TitleSet.setNav(actionBar,mNavView,mDrawerLayout);
initHobbies();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
GridLayoutManager layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
adapter = new HobbyAdapter(hobbyList);
recyclerView.setAdapter(adapter);
TitleSet.setTitleCenter(toolbar,"爱动");
TitleSet.setNavBtn(mNavView,mDrawerLayout);
ShowWelcome();
}
private void initHobbies(){
hobbyList.clear();
Hobby baskerball = new Hobby("篮球",R.mipmap.baketball);
hobbyList.add(baskerball);
Hobby football = new Hobby("足球",R.mipmap.fb);
hobbyList.add(football);
Hobby tennis = new Hobby("网球",R.mipmap.tb);
hobbyList.add(tennis);
Hobby dance = new Hobby("跳舞",R.mipmap.dance);
hobbyList.add(dance);
Hobby badminton = new Hobby("羽毛球",R.mipmap.tb2);
hobbyList.add(badminton);
Hobby baseball = new Hobby("棒球",R.mipmap.bbb);
hobbyList.add(baseball);
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.toolbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.register_mainAc:
Intent intent = new Intent(MyApplication.getContext(),LoginUsers.class);
ActivityData.setLoOrRe(0);
MyApplication.getContext().startActivity(intent);
break;
case R.id.login_mainAc:
Intent intent1 = new Intent(MyApplication.getContext(),LoginUsers.class);
ActivityData.setLoOrRe(1);
MyApplication.getContext().startActivity(intent1);
break;
case R.id.aboutUs:
Intent intent2 = new Intent(MyApplication.getContext(),AboutUsActivity.class);
startActivity(intent2);
break;
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
break;
default:
}
return true;
}
@Override
public void onRestart(){
header_user_name.setText(User.getUserName());
NetWorkRequest.a = 0;
ActivityData.setActivityId(1);
ActivityData.setShop(0);
super.onRestart();
}
private void ShowWelcome(){
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("必须要说的话:");
dialog.setMessage("朋友您好,我是爱动的负责人。\n在您体验爱动之前有以下几点须知:1、资讯板块的新闻暂时转载自虎扑网站;\n2、学习板块中的资料是我们收集整理好的,希望能帮助到您;\n3、若您在使用爱动的过程中遇到bug,请及时将bug情况反馈给我们,点击右上角“关于我们”即可获取我们的联系方式;\n5、爱动目前处于测试阶段,希望您使用游客模式进行身份认证。\n\n最后,感谢您对爱动的支持,祝生活愉快^。");
dialog.setCancelable(false);
dialog.setNegativeButton("没问题", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.show();
}
}
| 36.916031 | 225 | 0.676592 |
949c9f16c6b37b1b7028d07ea19618891379d15c | 2,433 | package com.baseflow.flutter.plugin.geolocator.tasks;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import com.baseflow.flutter.plugin.geolocator.Codec;
import com.baseflow.flutter.plugin.geolocator.data.LocationOptions;
import io.flutter.plugin.common.PluginRegistry;
abstract class LocationUsingLocationManagerTask extends Task<LocationOptions> {
private static final long TWO_MINUTES = 120000;
private final Context mAndroidContext;
final LocationOptions mLocationOptions;
LocationUsingLocationManagerTask(TaskContext<LocationOptions> context) {
super(context);
PluginRegistry.Registrar registrar = context.getRegistrar();
mAndroidContext = registrar.activity() != null ? registrar.activity() : registrar.activeContext();
mLocationOptions = context.getOptions();
}
public abstract void startTask();
LocationManager getLocationManager() {
return (LocationManager) mAndroidContext.getSystemService(Activity.LOCATION_SERVICE);
}
public static boolean isBetterLocation(Location location, Location bestLocation) {
if (bestLocation == null)
return true;
Long timeDelta = location.getTime() - bestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer)
return true;
if (isSignificantlyOlder)
return false;
float accuracyDelta = (int)(location.getAccuracy() - bestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
boolean isFromSameProvider = false;
if(location.getProvider() != null) {
isFromSameProvider = location.getProvider().equals(bestLocation.getProvider());
}
if (isMoreAccurate)
return true;
if (isNewer && !isLessAccurate)
return true;
//noinspection RedundantIfStatement
if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider)
return true;
return false;
}
}
| 33.328767 | 107 | 0.681463 |
46a006817cf3bee3099686ffcfeb26be29a89c1d | 18,728 | /*
* XML Type: CT_TransformEffect
* Namespace: http://schemas.openxmlformats.org/drawingml/2006/main
* Java type: org.openxmlformats.schemas.drawingml.x2006.main.CTTransformEffect
*
* Automatically generated - do not modify.
*/
package org.openxmlformats.schemas.drawingml.x2006.main.impl;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.QNameSet;
/**
* An XML CT_TransformEffect(@http://schemas.openxmlformats.org/drawingml/2006/main).
*
* This is a complex type.
*/
public class CTTransformEffectImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements org.openxmlformats.schemas.drawingml.x2006.main.CTTransformEffect {
private static final long serialVersionUID = 1L;
public CTTransformEffectImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final QName[] PROPERTY_QNAME = {
new QName("", "sx"),
new QName("", "sy"),
new QName("", "kx"),
new QName("", "ky"),
new QName("", "tx"),
new QName("", "ty"),
};
/**
* Gets the "sx" attribute
*/
@Override
public java.lang.Object getSx() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[0]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_default_attribute_value(PROPERTY_QNAME[0]);
}
return (target == null) ? null : target.getObjectValue();
}
}
/**
* Gets (as xml) the "sx" attribute
*/
@Override
public org.openxmlformats.schemas.drawingml.x2006.main.STPercentage xgetSx() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STPercentage target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_store().find_attribute_user(PROPERTY_QNAME[0]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_default_attribute_value(PROPERTY_QNAME[0]);
}
return target;
}
}
/**
* True if has "sx" attribute
*/
@Override
public boolean isSetSx() {
synchronized (monitor()) {
check_orphaned();
return get_store().find_attribute_user(PROPERTY_QNAME[0]) != null;
}
}
/**
* Sets the "sx" attribute
*/
@Override
public void setSx(java.lang.Object sx) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[0]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(PROPERTY_QNAME[0]);
}
target.setObjectValue(sx);
}
}
/**
* Sets (as xml) the "sx" attribute
*/
@Override
public void xsetSx(org.openxmlformats.schemas.drawingml.x2006.main.STPercentage sx) {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STPercentage target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_store().find_attribute_user(PROPERTY_QNAME[0]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_store().add_attribute_user(PROPERTY_QNAME[0]);
}
target.set(sx);
}
}
/**
* Unsets the "sx" attribute
*/
@Override
public void unsetSx() {
synchronized (monitor()) {
check_orphaned();
get_store().remove_attribute(PROPERTY_QNAME[0]);
}
}
/**
* Gets the "sy" attribute
*/
@Override
public java.lang.Object getSy() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[1]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_default_attribute_value(PROPERTY_QNAME[1]);
}
return (target == null) ? null : target.getObjectValue();
}
}
/**
* Gets (as xml) the "sy" attribute
*/
@Override
public org.openxmlformats.schemas.drawingml.x2006.main.STPercentage xgetSy() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STPercentage target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_store().find_attribute_user(PROPERTY_QNAME[1]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_default_attribute_value(PROPERTY_QNAME[1]);
}
return target;
}
}
/**
* True if has "sy" attribute
*/
@Override
public boolean isSetSy() {
synchronized (monitor()) {
check_orphaned();
return get_store().find_attribute_user(PROPERTY_QNAME[1]) != null;
}
}
/**
* Sets the "sy" attribute
*/
@Override
public void setSy(java.lang.Object sy) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[1]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(PROPERTY_QNAME[1]);
}
target.setObjectValue(sy);
}
}
/**
* Sets (as xml) the "sy" attribute
*/
@Override
public void xsetSy(org.openxmlformats.schemas.drawingml.x2006.main.STPercentage sy) {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STPercentage target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_store().find_attribute_user(PROPERTY_QNAME[1]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STPercentage)get_store().add_attribute_user(PROPERTY_QNAME[1]);
}
target.set(sy);
}
}
/**
* Unsets the "sy" attribute
*/
@Override
public void unsetSy() {
synchronized (monitor()) {
check_orphaned();
get_store().remove_attribute(PROPERTY_QNAME[1]);
}
}
/**
* Gets the "kx" attribute
*/
@Override
public int getKx() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[2]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_default_attribute_value(PROPERTY_QNAME[2]);
}
return (target == null) ? 0 : target.getIntValue();
}
}
/**
* Gets (as xml) the "kx" attribute
*/
@Override
public org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle xgetKx() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_store().find_attribute_user(PROPERTY_QNAME[2]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_default_attribute_value(PROPERTY_QNAME[2]);
}
return target;
}
}
/**
* True if has "kx" attribute
*/
@Override
public boolean isSetKx() {
synchronized (monitor()) {
check_orphaned();
return get_store().find_attribute_user(PROPERTY_QNAME[2]) != null;
}
}
/**
* Sets the "kx" attribute
*/
@Override
public void setKx(int kx) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[2]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(PROPERTY_QNAME[2]);
}
target.setIntValue(kx);
}
}
/**
* Sets (as xml) the "kx" attribute
*/
@Override
public void xsetKx(org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle kx) {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_store().find_attribute_user(PROPERTY_QNAME[2]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_store().add_attribute_user(PROPERTY_QNAME[2]);
}
target.set(kx);
}
}
/**
* Unsets the "kx" attribute
*/
@Override
public void unsetKx() {
synchronized (monitor()) {
check_orphaned();
get_store().remove_attribute(PROPERTY_QNAME[2]);
}
}
/**
* Gets the "ky" attribute
*/
@Override
public int getKy() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[3]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_default_attribute_value(PROPERTY_QNAME[3]);
}
return (target == null) ? 0 : target.getIntValue();
}
}
/**
* Gets (as xml) the "ky" attribute
*/
@Override
public org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle xgetKy() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_store().find_attribute_user(PROPERTY_QNAME[3]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_default_attribute_value(PROPERTY_QNAME[3]);
}
return target;
}
}
/**
* True if has "ky" attribute
*/
@Override
public boolean isSetKy() {
synchronized (monitor()) {
check_orphaned();
return get_store().find_attribute_user(PROPERTY_QNAME[3]) != null;
}
}
/**
* Sets the "ky" attribute
*/
@Override
public void setKy(int ky) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[3]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(PROPERTY_QNAME[3]);
}
target.setIntValue(ky);
}
}
/**
* Sets (as xml) the "ky" attribute
*/
@Override
public void xsetKy(org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle ky) {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_store().find_attribute_user(PROPERTY_QNAME[3]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STFixedAngle)get_store().add_attribute_user(PROPERTY_QNAME[3]);
}
target.set(ky);
}
}
/**
* Unsets the "ky" attribute
*/
@Override
public void unsetKy() {
synchronized (monitor()) {
check_orphaned();
get_store().remove_attribute(PROPERTY_QNAME[3]);
}
}
/**
* Gets the "tx" attribute
*/
@Override
public java.lang.Object getTx() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[4]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_default_attribute_value(PROPERTY_QNAME[4]);
}
return (target == null) ? null : target.getObjectValue();
}
}
/**
* Gets (as xml) the "tx" attribute
*/
@Override
public org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate xgetTx() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_store().find_attribute_user(PROPERTY_QNAME[4]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_default_attribute_value(PROPERTY_QNAME[4]);
}
return target;
}
}
/**
* True if has "tx" attribute
*/
@Override
public boolean isSetTx() {
synchronized (monitor()) {
check_orphaned();
return get_store().find_attribute_user(PROPERTY_QNAME[4]) != null;
}
}
/**
* Sets the "tx" attribute
*/
@Override
public void setTx(java.lang.Object tx) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[4]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(PROPERTY_QNAME[4]);
}
target.setObjectValue(tx);
}
}
/**
* Sets (as xml) the "tx" attribute
*/
@Override
public void xsetTx(org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate tx) {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_store().find_attribute_user(PROPERTY_QNAME[4]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_store().add_attribute_user(PROPERTY_QNAME[4]);
}
target.set(tx);
}
}
/**
* Unsets the "tx" attribute
*/
@Override
public void unsetTx() {
synchronized (monitor()) {
check_orphaned();
get_store().remove_attribute(PROPERTY_QNAME[4]);
}
}
/**
* Gets the "ty" attribute
*/
@Override
public java.lang.Object getTy() {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[5]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_default_attribute_value(PROPERTY_QNAME[5]);
}
return (target == null) ? null : target.getObjectValue();
}
}
/**
* Gets (as xml) the "ty" attribute
*/
@Override
public org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate xgetTy() {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_store().find_attribute_user(PROPERTY_QNAME[5]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_default_attribute_value(PROPERTY_QNAME[5]);
}
return target;
}
}
/**
* True if has "ty" attribute
*/
@Override
public boolean isSetTy() {
synchronized (monitor()) {
check_orphaned();
return get_store().find_attribute_user(PROPERTY_QNAME[5]) != null;
}
}
/**
* Sets the "ty" attribute
*/
@Override
public void setTy(java.lang.Object ty) {
synchronized (monitor()) {
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(PROPERTY_QNAME[5]);
if (target == null) {
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(PROPERTY_QNAME[5]);
}
target.setObjectValue(ty);
}
}
/**
* Sets (as xml) the "ty" attribute
*/
@Override
public void xsetTy(org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate ty) {
synchronized (monitor()) {
check_orphaned();
org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate target = null;
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_store().find_attribute_user(PROPERTY_QNAME[5]);
if (target == null) {
target = (org.openxmlformats.schemas.drawingml.x2006.main.STCoordinate)get_store().add_attribute_user(PROPERTY_QNAME[5]);
}
target.set(ty);
}
}
/**
* Unsets the "ty" attribute
*/
@Override
public void unsetTy() {
synchronized (monitor()) {
check_orphaned();
get_store().remove_attribute(PROPERTY_QNAME[5]);
}
}
}
| 33.989111 | 175 | 0.595205 |
81de8d9bb334be8c0240a6cc623b5ffccc98ed36 | 1,521 | package com.yunfei.home;
import com.yunfei.common.res.ResPresenter;
import com.yunfei.entity.NewItem;
import com.yunfei.net.BaseResponse;
import com.yunfei.net.NewsService;
import com.yunfei.net.RetrofitUtil;
import com.yunfei.net.ServerException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import rx.functions.Action1;
/**
* Created by yunfei on 2016/12/12.
* email [email protected]
*
* 可以添加的逻辑 记录请求时间 再一段时间内再去请求
* 根据是否有数据请求
*/
public class NewItemPresenter extends ResPresenter<List<NewItem>, NiewItemView> {
private final NewsService mNewsService;
public static int Count = 0;
private final String mType;
//应该判断是否为第一次 选择 显示的 loading
public NewItemPresenter(NewsService mNewsService, String type) {
this.mNewsService = mNewsService;
this.mType = type;
Count++;
}
public void getNews() {
addSuscription(mNewsService.
getNewsByType(mType)
.compose(
RetrofitUtil.<List<NewItem>, BaseResponse<List<NewItem>>>getSimpleHttpTransformer())
.subscribe(getResNextAction()
, new Action1<Throwable>() {
@Override public void call(Throwable throwable) {
if (throwable instanceof ServerException) {
getMvpView().showError(throwable.getMessage());
} else if (throwable instanceof TimeoutException) {
getMvpView().showError(throwable.getMessage());
} else {
}
}
}));
}
}
| 27.654545 | 96 | 0.668639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.