text
stringlengths 10
2.72M
|
|---|
package slimeknights.tconstruct.world.block;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBush;
import net.minecraft.block.SoundType;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.common.IShearable;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import javax.annotation.Nonnull;
import slimeknights.mantle.block.EnumBlock;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.world.TinkerWorld;
import slimeknights.tconstruct.world.block.BlockSlimeGrass.FoliageType;
public class BlockTallSlimeGrass extends BlockBush implements IShearable {
public static PropertyEnum<SlimePlantType> TYPE = PropertyEnum.create("type", SlimePlantType.class);
public static PropertyEnum<FoliageType> FOLIAGE = BlockSlimeGrass.FOLIAGE;
public BlockTallSlimeGrass() {
setCreativeTab(TinkerRegistry.tabWorld);
this.setSoundType(SoundType.PLANT);
}
@SideOnly(Side.CLIENT)
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
for(SlimePlantType type : SlimePlantType.values()) {
for(FoliageType foliage : FoliageType.values()) {
list.add(new ItemStack(this, 1, getMetaFromState(getDefaultState().withProperty(TYPE, type).withProperty(FOLIAGE, foliage))));
}
}
}
/* State stuff */
@Nonnull
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, TYPE, FOLIAGE);
}
@Override
public int getMetaFromState(IBlockState state) {
int meta = (state.getValue(TYPE)).getMeta();
meta |= (state.getValue(FOLIAGE)).ordinal() << 2;
return meta;
}
@Nonnull
@Override
public IBlockState getStateFromMeta(int meta) {
int type = meta & 3;
if(type >= SlimePlantType.values().length) {
type = 0;
}
int foliage = meta >> 2;
if(foliage >= FoliageType.values().length) {
foliage = 0;
}
IBlockState state = getDefaultState();
state = state.withProperty(TYPE, SlimePlantType.values()[type]);
state = state.withProperty(FOLIAGE, FoliageType.values()[foliage]);
return state;
}
/* Logic stuff */
@Override
public boolean isReplaceable(IBlockAccess worldIn, @Nonnull BlockPos pos) {
return true;
}
@Nonnull
@Override
public ItemStack getPickBlock(@Nonnull IBlockState state, RayTraceResult target, @Nonnull World world, @Nonnull BlockPos pos, EntityPlayer player) {
int meta = this.getMetaFromState(state);
return new ItemStack(Item.getItemFromBlock(this), 1, meta);
}
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune) {
return null;
}
@Override
public boolean canPlaceBlockAt(World worldIn, BlockPos pos) {
IBlockState soil = worldIn.getBlockState(pos.down());
Block ground = soil.getBlock();
return ground == TinkerWorld.slimeGrass || ground == TinkerWorld.slimeDirt;
}
/* Rendering Stuff */
/**
* Get the OffsetType for this Block. Determines if the model is rendered slightly offset.
*/
@Nonnull
@Override
@SideOnly(Side.CLIENT)
public Block.EnumOffsetType getOffsetType() {
return Block.EnumOffsetType.XYZ;
}
/* Forge/MC callbacks */
@Nonnull
@Override
public EnumPlantType getPlantType(IBlockAccess world, BlockPos pos) {
return TinkerWorld.slimePlantType;
}
@Override
public boolean isShearable(ItemStack item, IBlockAccess world, BlockPos pos) {
return true;
}
@Override
public List<ItemStack> onSheared(ItemStack item, IBlockAccess world, BlockPos pos, int fortune) {
IBlockState state = world.getBlockState(pos);
ItemStack stack = new ItemStack(this, 1, getMetaFromState(state));
return Lists.newArrayList(stack);
}
public enum SlimePlantType implements IStringSerializable, EnumBlock.IEnumMeta {
TALL_GRASS,
FERN;
SlimePlantType() {
this.meta = this.ordinal();
}
public final int meta;
@Override
public int getMeta() {
return meta;
}
@Override
public String getName() {
return this.toString().toLowerCase(Locale.US);
}
}
}
|
package org.deeplearning4j.util;
import java.io.DataInputStream;
import java.io.IOException;
/**
* Created by endy on 16-7-27.
*/
public class ByteUtil {
private ByteUtil(){}
public static String readString(DataInputStream dis , int maxSize) throws IOException{
byte[] bytes = new byte[maxSize];
byte b = dis.readByte();
int i = -1;
StringBuilder sb = new StringBuilder();
while(b != 32 && b != 10){ //在ASCII中32表示space, 10表示换行符
i++;
bytes[i] = b;
b = dis.readByte();
if(i == 49){
sb.append(new String(bytes));
i=-1;
bytes = new byte[maxSize];
}
}
sb.append(new String(bytes,0,i+1));
return sb.toString();
}
}
|
package page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class TimeTrackPage {
@FindBy(linkText = "Settings")
private WebElement setting;
@FindBy(xpath = "//a[contains(text(),'Licenses')]")
private WebElement license;
public TimeTrackPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void clickOnSettings() {
try{
Thread.sleep(5000);
setting.click();
}
catch(Exception e){
e.printStackTrace();
}
}
public void clickOnLicense() {
license.click();
}
public void verifyHomePageDisplayed(WebDriver driver, String etitle , long ETO){
WebDriverWait wait = new WebDriverWait(driver, ETO);
wait.until(ExpectedConditions.titleContains(etitle));
String atitle = driver.getTitle();
Assert.assertEquals(atitle, etitle);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.SQLException;
import java.util.Set;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.dao.QueryTimeoutException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.lang.Nullable;
/**
* {@link SQLExceptionTranslator} implementation that analyzes the SQL state in
* the {@link SQLException} based on the first two digits (the SQL state "class").
* Detects standard SQL state values and well-known vendor-specific SQL states.
*
* <p>Not able to diagnose all problems, but is portable between databases and
* does not require special initialization (no database vendor detection, etc.).
* For more precise translation, consider {@link SQLErrorCodeSQLExceptionTranslator}.
*
* <p>This translator is commonly used as a {@link #setFallbackTranslator fallback}
* behind a primary translator such as {@link SQLErrorCodeSQLExceptionTranslator} or
* {@link SQLExceptionSubclassTranslator}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Thomas Risberg
* @see java.sql.SQLException#getSQLState()
* @see SQLErrorCodeSQLExceptionTranslator
* @see SQLExceptionSubclassTranslator
*/
public class SQLStateSQLExceptionTranslator extends AbstractFallbackSQLExceptionTranslator {
private static final Set<String> BAD_SQL_GRAMMAR_CODES = Set.of(
"07", // Dynamic SQL error
"21", // Cardinality violation
"2A", // Syntax error direct SQL
"37", // Syntax error dynamic SQL
"42", // General SQL syntax error
"65" // Oracle: unknown identifier
);
private static final Set<String> DATA_INTEGRITY_VIOLATION_CODES = Set.of(
"01", // Data truncation
"02", // No data found
"22", // Value out of range
"23", // Integrity constraint violation
"27", // Triggered data change violation
"44" // With check violation
);
private static final Set<String> DATA_ACCESS_RESOURCE_FAILURE_CODES = Set.of(
"08", // Connection exception
"53", // PostgreSQL: insufficient resources (e.g. disk full)
"54", // PostgreSQL: program limit exceeded (e.g. statement too complex)
"57", // DB2: out-of-memory exception / database not started
"58" // DB2: unexpected system error
);
private static final Set<String> TRANSIENT_DATA_ACCESS_RESOURCE_CODES = Set.of(
"JW", // Sybase: internal I/O error
"JZ", // Sybase: unexpected I/O error
"S1" // DB2: communication failure
);
private static final Set<String> PESSIMISTIC_LOCKING_FAILURE_CODES = Set.of(
"40", // Transaction rollback
"61" // Oracle: deadlock
);
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
// First, the getSQLState check...
String sqlState = getSqlState(ex);
if (sqlState != null && sqlState.length() >= 2) {
String classCode = sqlState.substring(0, 2);
if (logger.isDebugEnabled()) {
logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
}
if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
}
else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
if (indicatesDuplicateKey(sqlState, ex.getErrorCode())) {
return new DuplicateKeyException(buildMessage(task, sql, ex), ex);
}
return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
}
else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
}
else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
}
else if (PESSIMISTIC_LOCKING_FAILURE_CODES.contains(classCode)) {
if (indicatesCannotAcquireLock(sqlState)) {
return new CannotAcquireLockException(buildMessage(task, sql, ex), ex);
}
return new PessimisticLockingFailureException(buildMessage(task, sql, ex), ex);
}
}
// For MySQL: exception class name indicating a timeout?
// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
if (ex.getClass().getName().contains("Timeout")) {
return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
}
// Couldn't resolve anything proper - resort to UncategorizedSQLException.
return null;
}
/**
* Gets the SQL state code from the supplied {@link SQLException exception}.
* <p>Some JDBC drivers nest the actual exception from a batched update, so we
* might need to dig down into the nested exception.
* @param ex the exception from which the {@link SQLException#getSQLState() SQL state}
* is to be extracted
* @return the SQL state code
*/
@Nullable
private String getSqlState(SQLException ex) {
String sqlState = ex.getSQLState();
if (sqlState == null) {
SQLException nestedEx = ex.getNextException();
if (nestedEx != null) {
sqlState = nestedEx.getSQLState();
}
}
return sqlState;
}
/**
* Check whether the given SQL state (and the associated error code in case
* of a generic SQL state value) indicate a {@link DuplicateKeyException}:
* either SQL state 23505 as a specific indication, or the generic SQL state
* 23000 with well-known vendor codes (1 for Oracle, 1062 for MySQL/MariaDB,
* 2601/2627 for MS SQL Server).
* @param sqlState the SQL state value
* @param errorCode the error code value
*/
static boolean indicatesDuplicateKey(@Nullable String sqlState, int errorCode) {
return ("23505".equals(sqlState) ||
("23000".equals(sqlState) &&
(errorCode == 1 || errorCode == 1062 || errorCode == 2601 || errorCode == 2627)));
}
/**
* Check whether the given SQL state indicates a {@link CannotAcquireLockException},
* with SQL state 40001 as a specific indication.
* @param sqlState the SQL state value
*/
static boolean indicatesCannotAcquireLock(@Nullable String sqlState) {
return "40001".equals(sqlState);
}
}
|
package fr.ucbl.disp.vfos.controller;
import fr.ucbl.disp.vfos.controller.sensor.listner.SensorProcessedDataListener;
public abstract class AController implements SensorProcessedDataListener, Decide, Apply {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package org.garret.perst;
/**
* Interface used to fileter records in result set (ResultSet class)
*/
public interface Filter {
public boolean fit(Object obj);
}
|
package com.mahang.weather.model.db;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import com.mahang.weather.common.Constants;
public class WeatherProvider extends ContentProvider {
private DbOpenHelper mWeatherHelper;
private DbOpenHelper mCityHelper;
private static final int WEATHER = 1;
private static final int CITY = 2;
private static UriMatcher mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static{
mUriMatcher.addURI(Constants.DB_AUTHORITY, Constants.DB_WEATHER, WEATHER);
mUriMatcher.addURI(Constants.DB_AUTHORITY, Constants.DB_CITY, CITY);
}
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreate() {
mWeatherHelper = new DbOpenHelper(getContext(), Constants.DB_WEATHER_NAME, null, 1);
copyDatabaseFromAsset(Constants.DB_CITY_LIST_DB);
mCityHelper = new DbOpenHelper(getContext(), Constants.DB_CITY_LIST_DB, null, 1);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String orderBy) {
SQLiteDatabase db = null;
switch (mUriMatcher.match(uri)) {
case WEATHER:
db = mWeatherHelper.getReadableDatabase();
return db.query("WEATHER_INFO", projection, selection, selectionArgs, null, null, orderBy);
case CITY:
db = mCityHelper.getReadableDatabase();
return db.query("CITY_LIST", projection, selection, selectionArgs, null, null, orderBy);
default:
throw new IllegalArgumentException();
}
}
@Override
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
// TODO Auto-generated method stub
return 0;
}
private void copyDatabaseFromAsset(String db){
String path = "data/data/"+getContext().getPackageName()+"/databases";
String datebaseFileName = path+"/"+db;
File dir = new File(path);
if (!dir.exists())
dir.mkdir();
if (!new File(datebaseFileName).exists()){
try {
InputStream in = getContext().getAssets().open(db);
FileOutputStream out = new FileOutputStream(datebaseFileName);
byte[] buffer = new byte[8192];
int count = 0;
while ((count = in.read(buffer)) > 0)
out.write(buffer,0,count);
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.pwq.again;
import java.util.HashMap;
import java.util.Map;
/**
* Created by BF100500 on 2017/3/21.
*/
public class WorkThread implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
InThread inThread = new InThread("pwq");
inThread.start();
}
}
|
/**
* Project: CarPark
* File: Location.java
*/
package org.carpark;
import java.lang.IllegalArgumentException;
/**
* Store distance and direction of a car park
* @author Marjan Rahimi
* @version March 2005
*/
public class Location {
private int distance;
private Direction direction;
/**
* Construct a location
* @param distance the distance of the car park
* @param direction the direction of the car park
* @exception IllegalArgumentException
*/
public Location(int distance, Direction direction)throws IllegalArgumentException {
if (distance < 0 )
throw new IllegalArgumentException("Distance must be greater than 0!");
if (direction == Direction.UNDEFINED )
throw new IllegalArgumentException("Direction cannot be undefined!");
this.distance = distance;
this.direction = direction;
}
/**
* @return Returns the direction of the car park.
*/
public Direction getDirection() {
return direction;
}
/**
* @return Returns the distance of the car park.
*/
public int getDistance() {
return distance;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object anObject) {
if(anObject instanceof Location){
Location location = (Location)anObject;
return location.direction == direction && location.distance == distance;
}
return false;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Distance: " + distance + ", " + "Direction: " + direction;
}
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Method;
//
// Test loop optimizations, in particular scalar loop peeling and unrolling.
public class Main {
static final int LENGTH = 4 * 1024;
int[] a = new int[LENGTH];
int[] b = new int[LENGTH];
private static final int LENGTH_A = LENGTH;
private static final int LENGTH_B = 16;
private static final int RESULT_POS = 4;
double[][] mA;
double[][] mB;
double[][] mC;
public Main() {
mA = new double[LENGTH_A][];
mB = new double[LENGTH_B][];
mC = new double[LENGTH_B][];
for (int i = 0; i < LENGTH_A; i++) {
mA[i] = new double[LENGTH_B];
}
for (int i = 0; i < LENGTH_B; i++) {
mB[i] = new double[LENGTH_A];
mC[i] = new double[LENGTH_B];
}
}
private static final void initMatrix(double[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
m[i][j] = (double) (i * LENGTH / (j + 1));
}
}
}
private static final void initIntArray(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = i % 4;
}
}
private static final void initDoubleArray(double[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = (double)(i % 4);
}
}
/// CHECK-START: void Main.unrollingLoadStoreElimination(int[]) loop_optimization (before)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<Phi>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<IndAdd>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Add:i\d+>> Add [<<Get0>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<Phi>>,<<Add>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-START: void Main.unrollingLoadStoreElimination(int[]) loop_optimization (after)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<Phi>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<IndAdd>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Add:i\d+>> Add [<<Get0>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<Phi>>,<<Add>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: <<CheckA:z\d+>> GreaterThanOrEqual [<<IndAdd>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IfA:v\d+>> If [<<Const0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0A:i\d+>> ArrayGet [<<Array>>,<<IndAdd>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAddA:i\d+>> Add [<<IndAdd>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1A:i\d+>> ArrayGet [<<Array>>,<<IndAddA>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddA:i\d+>> Add [<<Get0A>>,<<Get1A>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<IndAdd>>,<<AddA>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
private static final void unrollingLoadStoreElimination(int[] a) {
for (int i = 0; i < LENGTH - 2; i++) {
a[i] += a[i + 1];
}
}
// Simple check that loop unrolling has happened.
//
/// CHECK-START: void Main.unrollingSwitch(int[]) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-START: void Main.unrollingSwitch(int[]) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: <<CheckA:z\d+>> GreaterThanOrEqual [<<AddI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IfA:v\d+>> If [<<Const0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<AddI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
private static final void unrollingSwitch(int[] a) {
for (int i = 0; i < LENGTH; i++) {
switch (i % 3) {
case 2:
a[i]++;
break;
default:
break;
}
}
}
// Simple check that loop unrolling has happened.
//
/// CHECK-START: void Main.unrollingSwapElements(int[]) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-START: void Main.unrollingSwapElements(int[]) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: <<CheckA:z\d+>> GreaterThanOrEqual [<<AddI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IfA:v\d+>> If [<<Const0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<AddI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
private static final void unrollingSwapElements(int[] array) {
for (int i = 0; i < LENGTH - 2; i++) {
if (array[i] > array[i + 1]) {
int temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
// Simple check that loop unrolling has happened.
//
/// CHECK-START: void Main.unrollingRInnerproduct(double[][], double[][], double[][], int, int) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 16 loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-START: void Main.unrollingRInnerproduct(double[][], double[][], double[][], int, int) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 16 loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: <<CheckA:z\d+>> GreaterThanOrEqual [<<AddI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IfA:v\d+>> If [<<Const0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<AddI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-NOT: ArraySet loop:<<Loop>> outer_loop:none
private static final void unrollingRInnerproduct(double[][] result,
double[][] a,
double[][] b,
int row,
int column) {
// computes the inner product of A[row,*] and B[*,column]
int i;
result[row][column] = 0.0f;
for (i = 0; i < LENGTH_B; i++) {
result[row][column] = result[row][column] + a[row][i] * b[i][column];
}
}
// nested loop
// [[[]]]
/// CHECK-START: void Main.unrollingInTheNest(int[], int[], int) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 128 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop2:B\d+>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop3:B\d+>> outer_loop:<<Loop2>>
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi3>>,<<Limit>>] loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: If [<<Check>>] loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: Add [<<Phi3>>,<<Const1>>] loop:<<Loop3>> outer_loop:<<Loop2>>
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-NOT: If
/// CHECK-START: void Main.unrollingInTheNest(int[], int[], int) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 128 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop2:B\d+>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop3:B\d+>> outer_loop:<<Loop2>>
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi3>>,<<Limit>>] loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: If [<<Check>>] loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: <<AddI:i\d+>> Add [<<Phi3>>,<<Const1>>] loop:<<Loop3>> outer_loop:<<Loop2>>
//
/// CHECK-DAG: If [<<Const0>>] loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop2>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop2>>
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-NOT: If
private static final void unrollingInTheNest(int[] a, int[] b, int x) {
for (int k = 0; k < 16; k++) {
for (int j = 0; j < 16; j++) {
for (int i = 0; i < 128; i++) {
b[x]++;
a[i] = a[i] + 1;
}
}
}
}
// nested loop:
// [
// if [] else []
// ]
/// CHECK-START: void Main.unrollingTwoLoopsInTheNest(int[], int[], int) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 128 loop:none
/// CHECK-DAG: <<XThres:i\d+>> IntConstant 100 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:none
//
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop2:B\d+>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<Check2:z\d+>> GreaterThanOrEqual [<<Phi2>>,<<Limit>>] loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: If [<<Check2>>] loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArrayGet loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArraySet loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<AddI2:i\d+>> Add [<<Phi2>>,<<Const1>>] loop:<<Loop2>> outer_loop:<<Loop1>>
//
/// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop3:B\d+>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<Check3:z\d+>> GreaterThanOrEqual [<<Phi3>>,<<Limit>>] loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: If [<<Check3>>] loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<AddI3:i\d+>> Add [<<Phi3>>,<<Const1>>] loop:<<Loop3>> outer_loop:<<Loop1>>
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-NOT: If
/// CHECK-START: void Main.unrollingTwoLoopsInTheNest(int[], int[], int) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 128 loop:none
/// CHECK-DAG: <<XThres:i\d+>> IntConstant 100 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:none
//
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop2:B\d+>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<Check2:z\d+>> GreaterThanOrEqual [<<Phi2>>,<<Limit>>] loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: If [<<Check2>>] loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArrayGet loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArraySet loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<AddI2:i\d+>> Add [<<Phi2>>,<<Const1>>] loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: If [<<Const0>>] loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArrayGet loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArraySet loop:<<Loop2>> outer_loop:<<Loop1>>
/// CHECK-DAG: Add [<<AddI2>>,<<Const1>>] loop:<<Loop2>> outer_loop:<<Loop1>>
//
/// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop3:B\d+>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<Check3:z\d+>> GreaterThanOrEqual [<<Phi3>>,<<Limit>>] loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: If [<<Check3>>] loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: <<AddI3:i\d+>> Add [<<Phi3>>,<<Const1>>] loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: If [<<Const0>>] loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArrayGet loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: ArraySet loop:<<Loop3>> outer_loop:<<Loop1>>
/// CHECK-DAG: Add [<<AddI3>>,<<Const1>>] loop:<<Loop3>> outer_loop:<<Loop1>>
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-NOT: If
private static final void unrollingTwoLoopsInTheNest(int[] a, int[] b, int x) {
for (int k = 0; k < 128; k++) {
if (x > 100) {
for (int j = 0; j < 128; j++) {
a[x]++;
}
} else {
for (int i = 0; i < 128; i++) {
b[x]++;
}
}
}
}
/// CHECK-START: int Main.unrollingSimpleLiveOuts(int[]) loop_optimization (before)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Const2:i\d+>> IntConstant 2 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
/// CHECK-DAG: <<PhiS:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<PhiT:i\d+>> Phi [<<Const2>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<AddI>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddS:i\d+>> Add [<<PhiS>>,<<Get0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddT:i\d+>> Mul [<<PhiT>>,<<Get0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<PhiI>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddArr:i\d+>> Add [<<AddS>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<PhiI>>,<<AddArr>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: <<STAdd:i\d+>> Add [<<PhiS>>,<<PhiT>>] loop:none
/// CHECK-DAG: <<ZCheck:i\d+>> DivZeroCheck [<<STAdd>>] env:[[<<PhiS>>,<<PhiT>>,<<STAdd>>,<<Const1>>,_,<<Array>>]] loop:none
/// CHECK-DAG: <<Div:i\d+>> Div [<<Const1>>,<<ZCheck>>] loop:none
/// CHECK-DAG: Return [<<Div>>] loop:none
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-START: int Main.unrollingSimpleLiveOuts(int[]) loop_optimization (after)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Const2:i\d+>> IntConstant 2 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
/// CHECK-DAG: <<PhiS:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<PhiT:i\d+>> Phi [<<Const2>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<AddI>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddS:i\d+>> Add [<<PhiS>>,<<Get0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddT:i\d+>> Mul [<<PhiT>>,<<Get0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<PhiI>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddArr:i\d+>> Add [<<AddS>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<PhiI>>,<<AddArr>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: GreaterThanOrEqual [<<AddI>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Const0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddIA:i\d+>> Add [<<AddI>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0A:i\d+>> ArrayGet [<<Array>>,<<AddIA>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddSA:i\d+>> Add [<<AddS>>,<<Get0A>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddTA:i\d+>> Mul [<<AddT>>,<<Get0A>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1A:i\d+>> ArrayGet [<<Array>>,<<AddI>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<AddArrA:i\d+>> Add [<<AddSA>>,<<Get1A>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<AddI>>,<<AddArrA>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-DAG: <<RetPhiS:i\d+>> Phi [<<PhiS>>,<<AddS>>] loop:none
/// CHECK-DAG: <<RetPhiT:i\d+>> Phi [<<PhiT>>,<<AddT>>] loop:none
/// CHECK-DAG: <<STAdd:i\d+>> Add [<<RetPhiS>>,<<RetPhiT>>] loop:none
/// CHECK-DAG: <<ZCheck:i\d+>> DivZeroCheck [<<STAdd>>] env:[[<<RetPhiS>>,<<RetPhiT>>,<<STAdd>>,<<Const1>>,_,<<Array>>]] loop:none
/// CHECK-DAG: <<Div:i\d+>> Div [<<Const1>>,<<ZCheck>>] loop:none
/// CHECK-DAG: Return [<<Div>>] loop:none
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static final int unrollingSimpleLiveOuts(int[] a) {
int s = 1;
int t = 2;
for (int i = 0; i < LENGTH - 2; i++) {
int temp = a[i + 1];
s += temp;
t *= temp;
a[i] += s;
}
return 1 / (s + t);
}
/// CHECK-START: int Main.unrollingLiveOutsNested(int[]) loop_optimization (before)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Const2:i\d+>> IntConstant 2 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
//
/// CHECK-DAG: <<OutPhiJ:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop0:B\d+>> outer_loop:none
/// CHECK-DAG: <<OutPhiS:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: <<OutPhiT:i\d+>> Phi [<<Const2>>,{{i\d+}}] loop:<<Loop0>> outer_loop:none
//
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<PhiS:i\d+>> Phi [<<OutPhiS>>,{{i\d+}}] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<PhiT:i\d+>> Phi [<<OutPhiT>>,{{i\d+}}] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: If [<<Check>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<AddI>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddS:i\d+>> Add [<<PhiS>>,<<Get0>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddT:i\d+>> Mul [<<PhiT>>,<<Get0>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<PhiI>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddArr:i\d+>> Add [<<AddS>>,<<Get1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArraySet [<<Array>>,<<PhiI>>,<<AddArr>>] loop:<<Loop1>> outer_loop:<<Loop0>>
//
/// CHECK-DAG: Add [<<OutPhiJ>>,<<Const1>>] loop:<<Loop0>> outer_loop:none
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-START: int Main.unrollingLiveOutsNested(int[]) loop_optimization (after)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Const2:i\d+>> IntConstant 2 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4094 loop:none
//
/// CHECK-DAG: <<OutPhiJ:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop0:B\d+>> outer_loop:none
/// CHECK-DAG: <<OutPhiS:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: <<OutPhiT:i\d+>> Phi [<<Const2>>,{{i\d+}}] loop:<<Loop0>> outer_loop:none
//
/// CHECK-DAG: <<PhiI:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<PhiS:i\d+>> Phi [<<OutPhiS>>,{{i\d+}}] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<PhiT:i\d+>> Phi [<<OutPhiT>>,{{i\d+}}] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<PhiI>>,<<Limit>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: If [<<Check>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddI:i\d+>> Add [<<PhiI>>,<<Const1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<AddI>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddS:i\d+>> Add [<<PhiS>>,<<Get0>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddT:i\d+>> Mul [<<PhiT>>,<<Get0>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<PhiI>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddArr:i\d+>> Add [<<AddS>>,<<Get1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArraySet [<<Array>>,<<PhiI>>,<<AddArr>>] loop:<<Loop1>> outer_loop:<<Loop0>>
//
/// CHECK-DAG: If [<<Const0>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddIA:i\d+>> Add [<<AddI>>,<<Const1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Get0A:i\d+>> ArrayGet [<<Array>>,<<AddIA>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddSA:i\d+>> Add [<<AddS>>,<<Get0A>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddTA:i\d+>> Mul [<<AddT>>,<<Get0A>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Get1A:i\d+>> ArrayGet [<<Array>>,<<AddI>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<AddArrA:i\d+>> Add [<<AddSA>>,<<Get1A>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArraySet [<<Array>>,<<AddI>>,<<AddArrA>>] loop:<<Loop1>> outer_loop:<<Loop0>>
//
/// CHECK-DAG: <<RetPhiS:i\d+>> Phi [<<PhiS>>,<<AddS>>] loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: <<RetPhiT:i\d+>> Phi [<<PhiT>>,<<AddT>>] loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: Add [<<OutPhiJ>>,<<Const1>>] loop:<<Loop0>> outer_loop:none
//
/// CHECK-DAG: <<RetAdd:i\d+>> Add [<<OutPhiS>>,<<OutPhiT>>] loop:none
/// CHECK-DAG: Return [<<RetAdd>>] loop:none
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static final int unrollingLiveOutsNested(int[] a) {
int s = 1;
int t = 2;
for (int j = 0; j < 16; j++) {
for (int i = 0; i < LENGTH - 2; i++) {
int temp = a[i + 1];
s += temp;
t *= temp;
a[i] += s;
}
}
return s + t;
}
/// CHECK-START: void Main.unrollingInstanceOf(int[], java.lang.Object[]) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: InstanceOf loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: InstanceOf
/// CHECK-START: void Main.unrollingInstanceOf(int[], java.lang.Object[]) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: InstanceOf loop:<<Loop>> outer_loop:none
/// CHECK-DAG: InstanceOf loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: InstanceOf
public void unrollingInstanceOf(int[] a, Object[] obj_array) {
for (int i = 0; i < LENGTH_B; i++) {
if (obj_array[i] instanceof Integer) {
a[i] += 1;
}
}
}
/// CHECK-START: void Main.unrollingDivZeroCheck(int[], int) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: DivZeroCheck loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: DivZeroCheck
/// CHECK-START: void Main.unrollingDivZeroCheck(int[], int) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: DivZeroCheck loop:<<Loop>> outer_loop:none
/// CHECK-DAG: DivZeroCheck loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: DivZeroCheck
public void unrollingDivZeroCheck(int[] a, int r) {
for (int i = 0; i < LENGTH_B; i++) {
a[i] += a[i] / r;
}
}
/// CHECK-START: void Main.unrollingTypeConversion(int[], double[]) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: TypeConversion loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: TypeConversion
/// CHECK-START: void Main.unrollingTypeConversion(int[], double[]) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: TypeConversion loop:<<Loop>> outer_loop:none
/// CHECK-DAG: TypeConversion loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: TypeConversion
public void unrollingTypeConversion(int[] a, double[] b) {
for (int i = 0; i < LENGTH_B; i++) {
a[i] = (int) b[i];
}
}
interface Itf {
}
class SubMain extends Main implements Itf {
}
/// CHECK-START: void Main.unrollingCheckCast(int[], java.lang.Object) loop_optimization (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: CheckCast loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: CheckCast
/// CHECK-START: void Main.unrollingCheckCast(int[], java.lang.Object) loop_optimization (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: CheckCast loop:<<Loop>> outer_loop:none
/// CHECK-DAG: CheckCast loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: CheckCast
public void unrollingCheckCast(int[] a, Object o) {
for (int i = 0; i < LENGTH_B; i++) {
if (((SubMain)o) == o) {
a[i] = i;
}
}
}
/// CHECK-START: void Main.noUnrollingOddTripCount(int[]) loop_optimization (before)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4095 loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<Phi>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<IndAdd>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Add:i\d+>> Add [<<Get0>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<Phi>>,<<Add>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: Phi
/// CHECK-NOT: If
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-START: void Main.noUnrollingOddTripCount(int[]) loop_optimization (after)
/// CHECK-DAG: Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: Phi
/// CHECK-NOT: If
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static final void noUnrollingOddTripCount(int[] a) {
for (int i = 0; i < LENGTH - 1; i++) {
a[i] += a[i + 1];
}
}
/// CHECK-START: void Main.noUnrollingNotKnownTripCount(int[], int) loop_optimization (before)
/// CHECK-DAG: <<Array:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Limit:i\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<If:v\d+>> If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get0:i\d+>> ArrayGet [<<Array>>,<<Phi>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:i\d+>> ArrayGet [<<Array>>,<<IndAdd>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Add:i\d+>> Add [<<Get0>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet [<<Array>>,<<Phi>>,<<Add>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: Phi
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-START: void Main.noUnrollingNotKnownTripCount(int[], int) loop_optimization (after)
/// CHECK-DAG: Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: Phi
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static final void noUnrollingNotKnownTripCount(int[] a, int n) {
for (int i = 0; i < n; i++) {
a[i] += a[i + 1];
}
}
/// CHECK-START: void Main.peelingSimple(int[], boolean) loop_optimization (before)
/// CHECK-DAG: <<Param:z\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Param>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: If
/// CHECK-NOT: ArraySet
/// CHECK-START: void Main.peelingSimple(int[], boolean) loop_optimization (after)
/// CHECK-DAG: <<Param:z\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: <<CheckA:z\d+>> GreaterThanOrEqual [<<Const0>>,<<Limit>>] loop:none
/// CHECK-DAG: If [<<CheckA>>] loop:none
/// CHECK-DAG: If [<<Param>>] loop:none
/// CHECK-DAG: ArrayGet loop:none
/// CHECK-DAG: ArraySet loop:none
/// CHECK-DAG: <<IndAddA:i\d+>> Add [<<Const0>>,<<Const1>>] loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi [<<IndAddA>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Const0>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: If
/// CHECK-NOT: ArraySet
/// CHECK-START: void Main.peelingSimple(int[], boolean) dead_code_elimination$final (after)
/// CHECK-DAG: <<Param:z\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: If [<<Param>>] loop:none
/// CHECK-DAG: ArrayGet loop:none
/// CHECK-DAG: ArraySet loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,<<Limit>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: GreaterThanOrEqual
/// CHECK-NOT: If
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static final void peelingSimple(int[] a, boolean f) {
for (int i = 0; i < LENGTH; i++) {
if (f) {
break;
}
a[i] += 1;
}
}
// Often used idiom that, when not hoisted, prevents BCE and vectorization.
//
/// CHECK-START: void Main.peelingAddInts(int[]) loop_optimization (before)
/// CHECK-DAG: <<Param:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<ConstNull:l\d+>> NullConstant loop:none
/// CHECK-DAG: <<Eq:z\d+>> Equal [<<Param>>,<<ConstNull>>] loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If [<<Eq>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-START: void Main.peelingAddInts(int[]) dead_code_elimination$final (after)
/// CHECK-DAG: <<Param:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<ConstNull:l\d+>> NullConstant loop:none
/// CHECK-DAG: <<Eq:z\d+>> Equal [<<Param>>,<<ConstNull>>] loop:none
/// CHECK-DAG: If [<<Eq>>] loop:none
/// CHECK-DAG: ArraySet loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: If [<<Eq>>] loop:<<Loop>> outer_loop:none
private static final void peelingAddInts(int[] a) {
for (int i = 0; a != null && i < a.length; i++) {
a[i] += 1;
}
}
/// CHECK-START: void Main.peelingBreakFromNest(int[], boolean) loop_optimization (before)
/// CHECK-DAG: <<Param:z\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: <<Phi0:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop0:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi1>>,<<Limit>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: If [<<Check>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: If [<<Param>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArrayGet loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArraySet loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<IndAdd1:i\d+>> Add [<<Phi1>>,<<Const1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<IndAdd0:i\d+>> Add [<<Phi0>>,<<Const1>>] loop:<<Loop0>> outer_loop:none
//
/// CHECK-NOT: If
/// CHECK-NOT: ArraySet
/// CHECK-START: void Main.peelingBreakFromNest(int[], boolean) dead_code_elimination$final (after)
/// CHECK-DAG: <<Param:z\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 4096 loop:none
/// CHECK-DAG: <<Phi0:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop0:B\d+>> outer_loop:none
/// CHECK-DAG: If [<<Param>>] loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop0>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Const1>>,{{i\d+}}] loop:<<Loop1:B\d+>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<Check:z\d+>> GreaterThanOrEqual [<<Phi1>>,<<Limit>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: If [<<Check>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArrayGet loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: ArraySet loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<IndAdd1:i\d+>> Add [<<Phi1>>,<<Const1>>] loop:<<Loop1>> outer_loop:<<Loop0>>
/// CHECK-DAG: <<IndAdd0:i\d+>> Add [<<Phi0>>,<<Const1>>] loop:<<Loop0>> outer_loop:none
//
/// CHECK-NOT: If
/// CHECK-NOT: ArraySet
private static final void peelingBreakFromNest(int[] a, boolean f) {
outer:
for (int i = 1; i < 32; i++) {
for (int j = 0; j < LENGTH; j++) {
if (f) {
break outer;
}
a[j] += 1;
}
}
}
/// CHECK-START: int Main.peelingHoistOneControl(int) loop_optimization (before)
/// CHECK-DAG: <<Param:i\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Check:z\d+>> NotEqual [<<Param>>,<<Const0>>] loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If [<<Check>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<IndAdd:i\d+>> Add [<<Phi>>,<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: If
/// CHECK-START: int Main.peelingHoistOneControl(int) dead_code_elimination$final (after)
/// CHECK-DAG: <<Param:i\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Check:z\d+>> NotEqual [<<Param>>,<<Const0>>] loop:none
/// CHECK-DAG: If [<<Check>>] loop:none
/// CHECK-DAG: SuspendCheck loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: Goto loop:<<Loop>> outer_loop:none
//
// Check that the loop has no instruction except SuspendCheck and Goto (indefinite loop).
/// CHECK-NOT: loop:<<Loop>> outer_loop:none
/// CHECK-NOT: If
/// CHECK-NOT: Phi
/// CHECK-NOT: Add
private static final int peelingHoistOneControl(int x) {
int i = 0;
while (true) {
if (x == 0)
return 1;
i++;
}
}
/// CHECK-START: int Main.peelingHoistOneControl(int, int) loop_optimization (before)
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
//
/// CHECK-START: int Main.peelingHoistOneControl(int, int) dead_code_elimination$final (after)
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-NOT: If loop:<<Loop>> outer_loop:none
private static final int peelingHoistOneControl(int x, int y) {
while (true) {
if (x == 0)
return 1;
if (y == 0) // no longer invariant
return 2;
y--;
}
}
/// CHECK-START: int Main.peelingHoistTwoControl(int, int, int) loop_optimization (before)
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
//
/// CHECK-START: int Main.peelingHoistTwoControl(int, int, int) dead_code_elimination$final (after)
/// CHECK-DAG: <<Phi:i\d+>> Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: If loop:<<Loop>> outer_loop:none
/// CHECK-NOT: If loop:<<Loop>> outer_loop:none
private static final int peelingHoistTwoControl(int x, int y, int z) {
while (true) {
if (x == 0)
return 1;
if (y == 0)
return 2;
if (z == 0) // no longer invariant
return 3;
z--;
}
}
/// CHECK-START: void Main.unrollingFull(int[]) loop_optimization (before)
/// CHECK-DAG: <<Param:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 2 loop:none
/// CHECK-DAG: <<Phi:i\d+>> Phi [<<Const0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
/// CHECK-START: void Main.unrollingFull(int[]) loop_optimization (after)
/// CHECK-DAG: <<Param:l\d+>> ParameterValue loop:none
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Limit:i\d+>> IntConstant 2 loop:none
// Two peeled iterations
/// CHECK-DAG: ArrayGet loop:none
/// CHECK-DAG: ArrayGet loop:none
/// CHECK-DAG: ArraySet loop:none
/// CHECK-DAG: ArrayGet loop:none
/// CHECK-DAG: ArrayGet loop:none
/// CHECK-DAG: ArraySet loop:none
// Loop
/// CHECK-DAG: <<Phi:i\d+>> Phi [{{i\d+}},{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArrayGet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
/// CHECK-DAG: If [<<Const1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static final void unrollingFull(int[] a) {
for (int i = 0; i < 2; i++) {
a[i] += a[i + 1];
}
}
private static void expectEquals(int expected, int result) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
public void verifyUnrolling() throws Exception {
initIntArray(a);
initIntArray(b);
initMatrix(mA);
initMatrix(mB);
initMatrix(mC);
int expected = 174291515;
int found = 0;
double[] doubleArray = new double[LENGTH_B];
initDoubleArray(doubleArray);
unrollingInstanceOf(a, new Integer[LENGTH_B]);
unrollingDivZeroCheck(a, 15);
unrollingTypeConversion(a, doubleArray);
unrollingCheckCast(a, new SubMain());
// Call unrollingWhile(a);
Class<?> c = Class.forName("PeelUnroll");
Method m = c.getMethod("unrollingWhile", Class.forName("[I"));
Object[] arguments = { a };
m.invoke(null, arguments);
unrollingLoadStoreElimination(a);
unrollingSwitch(a);
unrollingSwapElements(a);
unrollingRInnerproduct(mC, mA, mB, RESULT_POS, RESULT_POS);
unrollingInTheNest(a, b, RESULT_POS);
unrollingTwoLoopsInTheNest(a, b, RESULT_POS);
noUnrollingOddTripCount(b);
noUnrollingNotKnownTripCount(b, 128);
for (int i = 0; i < LENGTH; i++) {
found += a[i];
found += b[i];
}
found += (int)mC[RESULT_POS][RESULT_POS];
expectEquals(expected, found);
}
public void verifyPeeling() throws Exception {
expectEquals(1, peelingHoistOneControl(0)); // anything else loops
expectEquals(1, peelingHoistOneControl(0, 0));
expectEquals(1, peelingHoistOneControl(0, 1));
expectEquals(2, peelingHoistOneControl(1, 0));
expectEquals(2, peelingHoistOneControl(1, 1));
expectEquals(1, peelingHoistTwoControl(0, 0, 0));
expectEquals(1, peelingHoistTwoControl(0, 0, 1));
expectEquals(1, peelingHoistTwoControl(0, 1, 0));
expectEquals(1, peelingHoistTwoControl(0, 1, 1));
expectEquals(2, peelingHoistTwoControl(1, 0, 0));
expectEquals(2, peelingHoistTwoControl(1, 0, 1));
expectEquals(3, peelingHoistTwoControl(1, 1, 0));
expectEquals(3, peelingHoistTwoControl(1, 1, 1));
initIntArray(a);
peelingSimple(a, false);
peelingSimple(a, true);
peelingAddInts(a);
peelingAddInts(null); // okay
peelingBreakFromNest(a, false);
peelingBreakFromNest(a, true);
unrollingSimpleLiveOuts(a);
// Call unrollingWhileLiveOuts(a);
Class<?> c = Class.forName("PeelUnroll");
Method m = c.getMethod("unrollingWhileLiveOuts", Class.forName("[I"));
Object[] arguments = { a };
m.invoke(null, arguments);
unrollingLiveOutsNested(a);
int expected = 51565978;
int found = 0;
for (int i = 0; i < a.length; i++) {
found += a[i];
}
expectEquals(expected, found);
}
public static void main(String[] args) throws Exception {
Main obj = new Main();
obj.verifyUnrolling();
obj.verifyPeeling();
System.out.println("passed");
}
}
|
/*
* 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 com.services;
import com.dao.ImplDao;
import com.entity.Cliente;
import com.entity.Detallepreventa;
import com.entity.Preventa;
import com.entity.Producto;
import com.entity.Tienda;
import com.implDao.IDetallepreventa;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
/**
*
* @author DAC-PC
*/
public class DetallepreventaServices extends ImplDao<Detallepreventa, Long> implements IDetallepreventa,Serializable{
@Override
public List<Detallepreventa> verdetalle(Preventa id) {
List<Detallepreventa> lista = new ArrayList<>();
Detallepreventa c = null;
String consulta;
try {
consulta = "FROM Detallepreventa d WHERE d.preventa = ?1";
Query query = getEmf().createEntityManager().createQuery(consulta);
query.setParameter(1, id);
lista =query.getResultList();
} catch (Exception e) {
throw e;
}finally{
getEntityManagger().close();
}
return lista;
}
@Override
public List<Producto> productoporcliente(Cliente c) {
List<Producto> listaproductos = new ArrayList<>();
String consulta;
try {
consulta = "SELECT i.producto FROM Detallepreventa i WHERE i.cliente = ?1 GROUP by i.producto ORDER BY COUNT(i.producto) DESC";
Query query = getEmf().createEntityManager().createQuery(consulta);
query.setParameter(1, c);
listaproductos =query.getResultList();
} catch (Exception e) {
throw e;
}finally{
getEntityManagger().close();
}
return listaproductos;
}
@Override
public List<Producto> vermascomprado(Tienda t) {
List<Producto> listaproductomasvendido;
String consulta;
try {
consulta = "SELECT p.producto FROM Detallepreventa p WHERE p.tienda =?1 GROUP BY p.producto ORDER BY Sum(p.cantidad) DESC ";
Query query = getEmf().createEntityManager().createQuery(consulta);
query.setParameter(1, t).setMaxResults(5);
listaproductomasvendido = query.getResultList();
} catch (Exception e) {
throw e;
}finally{
getEntityManagger().close();
}
return listaproductomasvendido;
}
@Override
public List<Integer> cantidad(Tienda ti) {
List<Integer> cantidadlistaproductomasvendido;
String consulta;
try {
consulta = "SELECT Sum(pe.cantidad) FROM Detallepreventa pe WHERE pe.tienda =?1 GROUP BY pe.producto ORDER BY Sum(pe.cantidad) DESC";
Query query = getEmf().createEntityManager().createQuery(consulta);
query.setParameter(1, ti);
cantidadlistaproductomasvendido = query.getResultList();
} catch (Exception e) {
throw e;
}finally{
getEntityManagger().close();
}
return cantidadlistaproductomasvendido;
}
}
|
package Transform;
import entity.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import javax.xml.bind.SchemaOutputResolver;
import java.util.ArrayList;
/**
* @author douglas
* @create 2021-02-19 21:15
*/
public class Flink09_TransForm_reduce_Anonymous {
public static void main(String[] args) throws Exception {
//创建流的执行环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//创建数组
ArrayList<WaterSensor> waterSensors = new ArrayList<>();
waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
//从数组中读取数据
KeyedStream<WaterSensor, String> kbStream = env.fromCollection(waterSensors)
.keyBy(WaterSensor::getId);
//匿名内部类执行reduce
kbStream.reduce(new ReduceFunction<WaterSensor>() {
@Override
public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
System.out.println("reducer function ...");
return new WaterSensor(value1.getId(),value1.getTs(),value1.getVc()+value2.getVc());
}
})
.print("reduce...");
env.execute();
}
}
|
package jvmTool;
/**
* user is lwb
**/
public class NMTTest {
public static void main(String[] args){
System.out.println("hello world!!");
}
}
|
package com.stackroute.userservice.service;
import com.stackroute.userservice.domain.User;
import java.util.Map;
/**
* Interface for JWT Token Generation
*/
public interface JWTTokenGenerator {
/**
* Abstract method for token generation
*/
Map<String, String> generateToken(String emailId);
}
|
package com.techelevator.dao;
import java.util.List;
import com.techelevator.model.DamageClaim;
import com.techelevator.model.Report;
public interface ReportDAO {
public List<Report> listReports();
public void addReport(Report report);
public void deleteReportByReportId(int report_id);
public void updateReport(Report report);
public void addDamageClaim(DamageClaim damageClaim);
public List<DamageClaim> listDamageClaims();
// single field update methods??
public void updateStatusByReportId(int report_id, int status_id);
public void updateSeverityByReportId(int report_id, int severity_id);
public void updateInspectedByReportId(int report_id, String inspected_date);
public void updateRepairedByReportId(int report_id, String repaired_date);
}
|
package jd.http;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import jd.http.requests.PostFormDataRequest;
import jd.http.requests.PostRequest;
import org.appwork.utils.net.httpconnection.HTTPProxy;
import org.appwork.utils.net.httpconnection.HTTPProxyHTTPConnectionImpl;
public class URLConnectionAdapterHTTPProxyImpl extends HTTPProxyHTTPConnectionImpl implements URLConnectionAdapter {
private Request request;
public URLConnectionAdapterHTTPProxyImpl(final URL url, final HTTPProxy proxy) {
super(url, proxy);
}
@Override
public InputStream getErrorStream() {
try {
return super.getInputStream();
} catch (final IOException e) {
return null;
}
}
@Override
public long getLongContentLength() {
return this.getContentLength();
}
@Override
public Request getRequest() {
return this.request;
}
@Override
public void setRequest(final Request request) {
this.request = request;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(this.getRequestInfo());
if (this.getRequest() != null) {
if (this.getRequest() instanceof PostRequest) {
if (((PostRequest) this.getRequest()).log() != null) {
sb.append(((PostRequest) this.getRequest()).log());
}
sb.append(new char[] { '\r', '\n' });
} else if (this.getRequest() instanceof PostFormDataRequest) {
if (((PostFormDataRequest) this.getRequest()).getPostDataString() != null) {
sb.append(((PostFormDataRequest) this.getRequest()).getPostDataString());
}
sb.append(new char[] { '\r', '\n' });
}
}
sb.append(this.getResponseInfo());
return sb.toString();
}
}
|
public class isCom implements BetterBehavior
{
public void comIs()
{
System.out.println("This is comparative.");
}
}
|
package com.mycompany.itman.corecourse.lesson2.task2;
import com.mycompany.itman.corecourse.lesson1.Event;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Comparator;
import static org.junit.jupiter.api.Assertions.*;
class VectorTest {
private Vector<Integer> createVector() {
Vector<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);
vector.add(null);
return vector;
}
private Vector<Event> createEventVector() {
Vector<Event> vector = new Vector<>();
vector.add(new Event(2020, 1, 8, "eight"));
vector.add(new Event(2020, 1, 4, "four"));
vector.add(new Event(2020, 1, 6, "six"));
return vector;
}
@Test
public void testAdd() {
Vector<Integer> vector = createVector();
Assertions.assertArrayEquals(new Integer[]{1, 2, 3, null}, vector.toArray());
}
@Test
public void testSize() {
Vector<Integer> vector = createVector();
Assertions.assertTimeout(Duration.ofSeconds(1), () -> {
Assertions.assertEquals(4, vector.size());
});
}
@Test
public void getTest() {
Vector<Integer> vector = createVector();
Assertions.assertEquals(1, vector.get(0));
}
@Test
public void setTest() {
Vector<Integer> vector = createVector();
vector.set(0, 1);
Assertions.assertEquals(1, vector.get(0));
}
@Test
public void removeTest() {
Vector<Integer> vector = createVector();
vector.remove(0);
Assertions.assertEquals(2, vector.get(0));
}
@Test
public void addIndexElementTest() {
Vector<Integer> vector = createVector();
vector.add(0, 5);
Assertions.assertEquals(5, vector.get(0));
}
@Test
public void toArrayTest() {
Vector<Integer> vector = createVector();
Object[] actual = vector.toArray();
Object[] expected = new Object[]{1, 2, 3, null};
Assertions.assertArrayEquals(expected, actual);
}
@Test
public void sortTest() {
Vector<Event> vectorActual = createEventVector();
Comparator<Event> comparatorByDate = (a, b) -> {
if (a.getDay() < b.getDay()) {
return -1;
}
if (a.getDay() > b.getDay()) {
return 1;
}
return 0;
};
vectorActual.sort(comparatorByDate);
Object[] actual = vectorActual.toArray();
Vector<Event> vectorExpected = new Vector<>();
vectorExpected.add(new Event(2020, 1, 4, "four"));
vectorExpected.add(new Event(2020, 1, 6, "six"));
vectorExpected.add(new Event(2020, 1, 8, "eight"));
Object[] expected = vectorExpected.toArray();
Assertions.assertArrayEquals(expected, actual);
}
@Test
public void clearTest() {
Vector<Integer> vector = createVector();
vector.clear();
Vector<Integer> expected = new Vector<>();
Assertions.assertArrayEquals(expected.toArray(), vector.toArray());
}
@Test
public void testToString() {
Vector<Integer> vector = createVector();
String actual = vector.toString();
String expected = "[1, 2, 3, null]";
Assertions.assertEquals(expected, actual);
}
}
|
package com.wy.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
*
* 该类放一些与服务器相关的参数
* 200,404,500;s
* 端口号port,线程池含量MAX_Thread
* 解析XML文件,并存放在中间
*/
public class CommonChar {
static public String htmlUrl;
static public int MAX_Thread;
static public int PORT;
static public String NowProtocol;
public final static int StATUS_OK = 200;
public final static int StATUS_NOT_FOUND = 404;
public final static int StATUS_SERVER_ERROR = 500;
public static Map<String, String> typesMap;
private static List<Element> typemappingsList;
static{
typesMap = new HashMap<String, String>();
init();
}
private static void init() {//读取XML(protocol)文件,并输入到map中
try {
SAXReader reader = new SAXReader();
Document doc = reader.read("config/config.xml");
Element serverRoot = doc.getRootElement();
//解析connector标签
Element connector =
serverRoot.element("service").element("connector");
NowProtocol = connector.attributeValue("protpcol");
PORT = Integer.parseInt(
connector.attributeValue("port"));
MAX_Thread = Integer.parseInt(
connector.attributeValue("MaxThread"));
htmlUrl = serverRoot.element("service").elementText("webroot");
System.out.println("NowProtocol = "+NowProtocol+";PORT = "+PORT+
";MAX_Thread = "+MAX_Thread+";htmlUrl = "+htmlUrl);
typemappingsList = serverRoot.element(
"type-mappings").elements("type-mapping");
for(Element element : typemappingsList)
{
String suffix = element.attributeValue("suffix");
String type = element.attributeValue("type");
typesMap.put(suffix, type);
System.out.println(suffix+"--"+type);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.test.base;
import com.test.SolutionA;
import com.test.SolutionB;
import junit.framework.TestCase;
public class Example extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
public void testSolutionA()
{
solution = new SolutionA();
assertSolution();
}
public void testSolutionB()
{
solution = new SolutionB();
assertSolution();
}
private void assertSolution()
{
Node nodeA1 = new Node();
Node nodeA2 = new Node();
nodeA1.val = 1;
nodeA1.next = nodeA2;
nodeA1.random = nodeA2;
nodeA2.val = 2;
nodeA2.next = null;
nodeA2.random = nodeA2;
solution.copyRandomList(nodeA1);
Node nodeB1 = new Node();
Node nodeB2 = new Node();
nodeB1.val = 11;
nodeB1.next = nodeB2;
nodeB1.random = nodeB2;
nodeB2.val = 22;
nodeB2.next = null;
nodeB2.random = nodeB1;
solution.copyRandomList(nodeB1);
}
@Override
protected void tearDown()
throws Exception
{
super.tearDown();
}
}
|
package clienteLogica;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import com.google.gson.Gson;
import interfazDelJuego.JVentanaGrafica;
import logicaJuego.Bomberman;
import logicaJuego.Entidad;
import logicaJuego.Mapa;
import clienteLogica.Sala;
public class Escuchar extends Thread {
private DataInputStream entrada;
private VentanaLobby ventana;
private JVentanaGrafica ventanaGrafica;
private Mapa mapa;
private VentanaChat ventanaChat;
boolean flag;
public Escuchar(DataInputStream entrada, VentanaLobby ventanaLobby) {
// TODO Auto-generated constructor stub
this.entrada = entrada;
this.ventana = ventanaLobby;
flag = false;
}
public void run() {
while (flag == false) {
String mensajeRecibido;
ArrayList<Bomberman> bombers;
ArrayList<ImageIcon> imagenes;
try {
mensajeRecibido = (String) entrada.readUTF();
Mensaje mensajes = new Mensaje();
Gson gson = new Gson();
mensajes = gson.fromJson(mensajeRecibido, Mensaje.class);
String keys = mensajes.getTipo();
switch (keys) {
case "crearSala":
int id = mensajes.getId();
ventana.setIdSala(id);
if (ventana.getVentanaSala() != null)
ventana.getVentanaSala().dispose();
ventana.setVentanaSala(new VentanaSala(ventana.getNombre(), ventana.getTextField().getText(),
ventana.getCliente(), id));
ventana.getVentanaSala().setVisible(true);
ventana.setBtnUnirseSala(false);
break;
case "listarSalas":
ventana.getTextSalas().setText("");
ventana.setTextSalas(mensajes.getMsj());
break;
case "unirseSala":
Sala salita = mensajes.getSala();
if (ventana.getUnirse() != null)
ventana.getUnirse().setVisible(false);
ventana.setUnirse(new VentanaUnirse(salita, ventana.getCliente()));
ventana.getUnirse().setVisible(true);
ventana.setBtnUnirseSala(false);
ventana.getUnirse().setLobby(ventana);
ventana.desactivarCamposDeTexto();
break;
case "errorUnirse":
JOptionPane.showMessageDialog(null,
"Error, la sala: " + mensajes.getMsj()+ " no existe o la contraseņa es incorrecta");
break;
case "salaLlena":
JOptionPane.showMessageDialog(null,
"Error, la sala: " + mensajes.getMsj() + " esta llena");
break;
case "iniciarPartida":
Entidad[][] matrizmapa;
Entidad[][] matrizcosas;
mapa = new Mapa();
matrizmapa = mensajes.getMapa().descargarMatrizMapa();
matrizcosas = mensajes.getMapa().descargarMatrizCosas();
bombers = mensajes.getMapa().descargarBombers();
imagenes = mensajes.getMapa().descargarImageIcons();
mapa.setMatrizMapa(matrizmapa);
mapa.setMatrizCosas(matrizcosas);
mapa.setJugadores(bombers);
for (int i = 0; i < mapa.getJugadores().size(); i++) {
ImageIcon icono = new ImageIcon(imagenes.get(i).getDescription());
mapa.getJugadores().get(i).setBomberman(icono);
}
ventanaChat = new VentanaChat();
if(!mensajes.isEspectador()) {
ventanaChat.setVisible(true);
}else ventanaChat.setVisible(false);
ventanaGrafica = new JVentanaGrafica(mapa, ventana.getCliente());
ventanaGrafica.getMov1().setDirecciones(ventana.getVentanaBotones());
ventanaGrafica.setIdSala(mensajes.getId());
ventanaGrafica.setDueņo(mensajes.getPropietarioMsj().equals(ventana.getCliente().getNombre()));
ventanaGrafica.setChat(ventanaChat);
ventanaGrafica.setVisible(true);
ventanaGrafica.setLobby(ventana);
if (ventana.getUnirse() != null)
ventana.getUnirse().setVisible(false);
break;
case "eliminarSala":
if (ventana.getUnirse() != null) {
ventana.getUnirse().setVisible(false);
ventana.setVentanaSala(null);
}
if (ventanaGrafica != null) {
ventanaGrafica.getHiloDibujado().finalizarHilo();
ventanaGrafica.setVisible(false);
ventanaGrafica.dispose();
ventanaChat.dispose();
}
ventana.getBtnUnirseSala().setVisible(true);
ventana.habilitarCamposTexto();
break;
case "actualizarSala":
if (ventana.getUnirse() != null) {
ventana.getUnirse().setTextUsuarios(mensajes.getMsj());
}
if (ventana.getVentanaSala() != null) {
ventana.getVentanaSala().setTextParticipantes(mensajes.getMsj());
}
break;
case "actualizarMapa":
mapa = new Mapa();
matrizmapa = mensajes.getMapa().descargarMatrizMapa();
matrizcosas = mensajes.getMapa().descargarMatrizCosas();
bombers = mensajes.getMapa().descargarBombers();
imagenes = mensajes.getMapa().descargarImageIcons();
mapa.setMatrizMapa(matrizmapa);
mapa.setMatrizCosas(matrizcosas);
mapa.setJugadores(bombers);
for (int i = 0; i < mapa.getJugadores().size(); i++) {
ImageIcon icono = new ImageIcon(imagenes.get(i).getDescription());
mapa.getJugadores().get(i).setBomberman(icono);
}
ventanaGrafica.setNuevo(mapa);
break;
case "mensajeChat":
String msj = new String();
msj = msj.concat(mensajes.getPropietarioMsj());
msj = msj.concat(": ");
msj = msj.concat(mensajes.getMsj());
msj = msj.concat("\n");
ventanaChat.getTextChat().append(msj);
break;
case "modoEspectador":
if(ventanaGrafica!=null) {
ventanaGrafica.setVisible(false);
}
Entidad[][] matrizMapa;
Entidad[][] matrizCosas;
mapa = new Mapa();
matrizMapa = mensajes.getMapa().descargarMatrizMapa();
matrizCosas = mensajes.getMapa().descargarMatrizCosas();
bombers = mensajes.getMapa().descargarBombers();
imagenes = mensajes.getMapa().descargarImageIcons();
mapa.setMatrizMapa(matrizMapa);
mapa.setMatrizCosas(matrizCosas);
mapa.setJugadores(bombers);
for (int i = 0; i < mapa.getJugadores().size(); i++) {
ImageIcon icono = new ImageIcon(imagenes.get(i).getDescription());
mapa.getJugadores().get(i).setBomberman(icono);
}
ventanaChat = new VentanaChat();
if (!mensajes.isEspectador()) {
ventanaChat.setVisible(true);
} else
ventanaChat.setVisible(false);
ventanaGrafica = new JVentanaGrafica(mapa, ventana.getCliente());
ventanaGrafica.getMov1().setDirecciones(ventana.getVentanaBotones());
ventanaGrafica.setIdSala(mensajes.getId());
ventanaGrafica.setDueņo(mensajes.getPropietarioMsj().equals(ventana.getCliente().getNombre()));
ventanaGrafica.setChat(ventanaChat);
ventanaGrafica.setVisible(true);
ventanaGrafica.setLobby(ventana);
if (ventana.getUnirse() != null)
ventana.getUnirse().setVisible(false);
break;
case "finalizarPartida":
class podio implements Comparable<podio> {
int puntaje;
String nombre;
public podio(int puntaje, String nombre) {
this.puntaje = puntaje;
this.nombre = nombre;
}
public String devolverPodio() {
return "Nombre: " + nombre + " Puntaje: " + puntaje + "\n";
}
@Override
public int compareTo(podio o) {
if (puntaje == o.puntaje)
return 0;
else if (puntaje > o.puntaje)
return -1;
else
return 1;
}
}
int puntajes[] = mensajes.getSala().getPuntajes();
ArrayList<String> jugadores = mensajes.getSala().getJugadores();
ArrayList<podio> podios = new ArrayList<>();
for (int i = 0; i < mensajes.getSala().getJugadores().size(); i++) {
podios.add(new podio(puntajes[i], jugadores.get(i)));
}
Collections.sort(podios);
String podioDeGanadores = new String();
for (int i = 0; i < podios.size(); i++) {
podioDeGanadores = podioDeGanadores.concat((i + 1) + "° " + podios.get(i).devolverPodio());
}
JOptionPane.showMessageDialog(null, "Podio de los ganadores:" + "\n" + podioDeGanadores);
break;
case "temporizador":
ventanaGrafica.getContentPane().setTemporizador(new String());
ventanaGrafica.getContentPane().setTemporizador(mensajes.getMsj());
break;
}
} catch (IOException e) {
flag = true;
}
}
}
}
|
package com.oracle.curd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping(value = "/adminLogin")
public String adminLogin(){
return "managerLogin";
}
@RequestMapping(value = "/adminLoginOut")
public String adminLoginOut(){
return "managerLogin";
}
}
|
package com.abstraction;
public class abstract2 extends abstract1 {
@Override
void password() {
System.out.println("1342");
// TODO Auto-generated method stub
//iyihfih
}
public static void main(String[] args) {
abstract2 e=new abstract2();
e.name();
e.password();
}
}
|
package org.usfirst.frc.team5114.MyRobot2016;
import edu.wpi.first.wpilibj.vision.USBCamera;
/**
* Manages multiple cameras regardless of actual configuration
* imaqOverlayText
*/
public class CameraSystems {
public USBCamera[] cameras;
private int maxCameras = 0;
private int currentCamera = -1;
// Constructor attempts to initialize X cameras
public CameraSystems(int maxCams)
{
this.maxCameras = maxCams;
this.cameras = new USBCamera[maxCams];
for( int i=0; i<maxCams; i++ )
{
try
{
String camName = "cam"+Integer.toString(i);
System.out.println("Initializing "+camName);
USBCamera newCamera = new USBCamera(camName);
newCamera.openCamera();
this.cameras[i] = newCamera;
System.out.println("Camera "+camName+" found on system and opened");
}
catch(Exception e)
{
System.out.println("Camera initialization caused an exception " + e);
}
}
}
public int getMaxCameras() {
return maxCameras;
}
public USBCamera getCurrentCamera()
{
USBCamera retVal = null;
if ( ( this.currentCamera >= 0 ) && (this.currentCamera < this.maxCameras) )
{
retVal = this.cameras[this.currentCamera];
}
return retVal;
}
public int getCurrentCameraIndex() {
return currentCamera;
}
public void setCurrentCameraIndex(int value) {
if ( (value >= 0) && (value < this.maxCameras) && (this.cameras[value] != null ) )
{
USBCamera currCam = getCurrentCamera();
if ( currCam != null )
currCam.stopCapture();
this.currentCamera = value;
currCam = getCurrentCamera();
currCam.startCapture();
}
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.idea.config;
import com.atlassian.theplugin.commons.configuration.PluginConfiguration;
import com.atlassian.theplugin.commons.util.MiscUtil;
import com.atlassian.theplugin.idea.GeneralConfigForm;
import com.atlassian.theplugin.idea.autoupdate.NewVersionChecker;
import com.atlassian.theplugin.util.InfoServer;
import javax.swing.*;
import java.awt.*;
/**
* General plugin config form.
*/
public final class GeneralConfigPanel extends JPanel implements ContentPanel {
private GeneralConfigForm dialog;
private PluginConfiguration localPluginConfigurationCopy;
private final PluginConfiguration globalPluginConfiguration;
public GeneralConfigPanel(PluginConfiguration globalPluginConfiguration, final NewVersionChecker newVersionChecker) {
this.globalPluginConfiguration = globalPluginConfiguration;
localPluginConfigurationCopy = this.globalPluginConfiguration;
setLayout(new CardLayout());
dialog = new GeneralConfigForm(newVersionChecker);
add(dialog.getRootPane(), "GeneralConfig");
}
public boolean isModified() {
return !localPluginConfigurationCopy.equals(globalPluginConfiguration)
|| dialog.getIsAutoUpdateEnabled()
!= globalPluginConfiguration.getGeneralConfigurationData().isAutoUpdateEnabled()
|| dialog.isHttpServerEnabled()
!= globalPluginConfiguration.getGeneralConfigurationData().isHttpServerEnabled()
|| dialog.getHttpServerPort()
!= globalPluginConfiguration.getGeneralConfigurationData().getHttpServerPort()
|| dialog.getIsCheckUnstableVersionsEnabled()
!= globalPluginConfiguration.getGeneralConfigurationData().isCheckUnstableVersionsEnabled()
|| MiscUtil.isModified(dialog.getIsAnonymousFeedbackEnabled(),
globalPluginConfiguration.getGeneralConfigurationData().getAnonymousEnhancedFeedbackEnabled())
|| dialog.getUseIdeaProxySettings()
!= globalPluginConfiguration.getGeneralConfigurationData().getUseIdeaProxySettings()
|| MiscUtil.isModified(dialog.getCheckNotButtonOption(),
globalPluginConfiguration.getGeneralConfigurationData().getCheckNowButtonOption());
}
public void setIsAnonymousFeedbackEnabled(Boolean isAnonymousFeedbackEnabled) {
dialog.setIsAnonymousFeedbackEnabled(isAnonymousFeedbackEnabled);
}
public String getTitle() {
return "General";
}
public void saveData() {
if (localPluginConfigurationCopy.getGeneralConfigurationData().getAnonymousEnhancedFeedbackEnabled()
!= dialog.getIsAnonymousFeedbackEnabled()) {
InfoServer.reportOptInOptOut(
globalPluginConfiguration.getGeneralConfigurationData().getUid(),
dialog.getIsAnonymousFeedbackEnabled());
}
localPluginConfigurationCopy.getGeneralConfigurationData().setAutoUpdateEnabled(dialog.getIsAutoUpdateEnabled());
localPluginConfigurationCopy.getGeneralConfigurationData().setHttpServerEnabled(dialog.isHttpServerEnabled());
localPluginConfigurationCopy.getGeneralConfigurationData().setHttpServerPort(dialog.getHttpServerPort());
localPluginConfigurationCopy.getGeneralConfigurationData()
.setCheckUnstableVersionsEnabled(dialog.getIsCheckUnstableVersionsEnabled());
localPluginConfigurationCopy.getGeneralConfigurationData()
.setAnonymousEnhancedFeedbackEnabled(dialog.getIsAnonymousFeedbackEnabled());
localPluginConfigurationCopy.getGeneralConfigurationData().setUseIdeaProxySettings(dialog.getUseIdeaProxySettings());
localPluginConfigurationCopy.getGeneralConfigurationData().setCheckNowButtonOption(dialog.getCheckNotButtonOption());
globalPluginConfiguration.getGeneralConfigurationData().setAutoUpdateEnabled(dialog.getIsAutoUpdateEnabled());
globalPluginConfiguration.getGeneralConfigurationData().setHttpServerEnabled(dialog.isHttpServerEnabled());
globalPluginConfiguration.getGeneralConfigurationData().setHttpServerPort(dialog.getHttpServerPort());
globalPluginConfiguration.getGeneralConfigurationData()
.setCheckUnstableVersionsEnabled(dialog.getIsCheckUnstableVersionsEnabled());
globalPluginConfiguration.getGeneralConfigurationData()
.setAnonymousEnhancedFeedbackEnabled(dialog.getIsAnonymousFeedbackEnabled());
globalPluginConfiguration.getGeneralConfigurationData().setUseIdeaProxySettings(dialog.getUseIdeaProxySettings());
globalPluginConfiguration.getGeneralConfigurationData().setCheckNowButtonOption(dialog.getCheckNotButtonOption());
}
public void setData(PluginConfiguration config) {
localPluginConfigurationCopy = config;
dialog.setAutoUpdateEnabled(localPluginConfigurationCopy.getGeneralConfigurationData()
.isAutoUpdateEnabled());
dialog.setHttpServerEnabled(localPluginConfigurationCopy.getGeneralConfigurationData()
.isHttpServerEnabled());
dialog.setHttpServerPort(localPluginConfigurationCopy.getGeneralConfigurationData()
.getHttpServerPort());
dialog.setIsCheckUnstableVersionsEnabled(localPluginConfigurationCopy.getGeneralConfigurationData()
.isCheckUnstableVersionsEnabled());
dialog.setIsAnonymousFeedbackEnabled(localPluginConfigurationCopy.getGeneralConfigurationData()
.getAnonymousEnhancedFeedbackEnabled());
dialog.setUseIdeaProxySettings(localPluginConfigurationCopy.getGeneralConfigurationData()
.getUseIdeaProxySettings());
dialog.setCheckNowButtonOption(localPluginConfigurationCopy.getGeneralConfigurationData()
.getCheckNowButtonOption());
}
}
|
package checkers.core.boards;
import checkers.core.Checker;
import checkers.core.Coordinates;
public interface Board {
int getNumOfCol();
int getNumOfRows();
Checker getFieldOccupiedBy(Coordinates location);
Checker getFieldType(Coordinates location);
void makeMove(Coordinates currLocation, Coordinates destination) throws WrongMoveException;
int getExNumOfPlayers();
Checker colorForPlayer(int num);
}
|
package exo_oiseaux;
public class Pie extends Oiseau{
public void decrire() {
super.decrire();
System.out.println("Je suis une pie");
}
}
|
package edu.neu.ccs.cs5010;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class FollowedGraphTest {
@Before
public void setUp() throws Exception {
}
@Test
public void createFollowedGraph() throws Exception {
}
@Test
public void getVexNum() throws Exception {
}
@Test
public void getEdgeNum() throws Exception {
}
@Test
public void getVexElement() throws Exception {
}
@Test
public void getVetexList() throws Exception {
}
@Test
public void getIDNumber() throws Exception {
}
@Test
public void printGraph() throws Exception {
}
@Test
public void countFollowers() throws Exception {
}
@Test
public void getfollowerList() throws Exception {
}
}
|
package com.impulse.test.config;
import java.util.HashMap;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = "com.impulse")
public class TestConfig {
@Bean
public DataSource localDataSource() {
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(false)
.addScripts("sql/department.sql", "sql/employee.sql")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean localUsersEntityManagerFactory(DataSource localDataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(localDataSource);
em.setPersistenceUnitName("springTests");
em.setPackagesToScan(new String[] { "com.impulse" });
em.setJpaPropertyMap(new HashMap<String, Object>() {
private static final long serialVersionUID = 1L;
{
put("hibernate.cache.use_second_level_cache", false);
}
});
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQLInnoDBDialect");
vendorAdapter.setShowSql(false);
vendorAdapter.setGenerateDdl(false);
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
|
package loginform;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ManejadorMD5 {
public String encriptaClave(String clave) throws NoSuchAlgorithmException {
MessageDigest instanciaMD =MessageDigest.getInstance("MD5");
instanciaMD.update(clave.getBytes());
byte[] claveBytes=instanciaMD.digest();
StringBuilder sb = new StringBuilder();
for(int y=0; y< claveBytes.length ;y++)
{
sb.append(Integer.toString((claveBytes[y] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
|
package com.buttercell.vaxn.model;
/**
* Created by amush on 23-Jan-18.
*/
public class Record {
public String testName,testResults,testComments,dateAdded;
public Record( String testName, String testResults, String testComments, String dateAdded) {
this.testName = testName;
this.testResults = testResults;
this.testComments = testComments;
this.dateAdded = dateAdded;
}
public Record() {
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestResults() {
return testResults;
}
public void setTestResults(String testResults) {
this.testResults = testResults;
}
public String getTestComments() {
return testComments;
}
public void setTestComments(String testComments) {
this.testComments = testComments;
}
public String getDateAdded() {
return dateAdded;
}
public void setDateAdded(String dateAdded) {
this.dateAdded = dateAdded;
}
}
|
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInputStream2 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:/Users/RAKESH/Desktop/Tutorial.txt");
FileOutputStream fos = new FileOutputStream("C:/Users/RAKESH/Desktop/Tutorial5.txt");
int size = fis.available();
System.out.println("Number of bytes in file: " + size);
int i = fis.read();
while(i != -1){
fos.write((byte) i);
i = fis.read();
}
System.out.println("Copy Operation Done");
fis.close();
fos.flush();
}
}
|
package lab02;
import java.util.LinkedList;
import lab01.Edge;
import lab01.GraphInterface;
import lab01.MatrixGraph;
import lab01.Vertex;
public class WarshalFloyd
{
private int vertexCount;
private int[][] distances;
private int[][] predecessors;
private LinkedList<Integer> path = new LinkedList<Integer>();
public int[][] warshalFloyd(GraphInterface graph)
{
vertexCount = graph.getVertexCount()+1;
this.distances = new int[vertexCount][vertexCount];
this.predecessors = new int[vertexCount][vertexCount];
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
this.predecessors[i][j] = -1;
Vertex iv = new Vertex().setVertexId(i);
Vertex jv = new Vertex().setVertexId(j);
Edge edge = graph.getEdge(iv, jv);
if(i == j) {
this.distances[i][j] = 0;
} else if(edge == null) {
this.distances[i][j] = 9999;
} else {
this.distances[i][j] = edge.getEdgeWeight();
this.predecessors[i][j] = j;
}
}
}
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
for (int k = 0; k < vertexCount; k++) {
if (this.distances[j][i] + this.distances[i][k] < this.distances[j][k]) {
this.distances[j][k] = this.distances[j][i] + this.distances[i][k];
this.predecessors[j][k] = this.predecessors[j][i];
}
}
}
}
return this.distances;
}
public LinkedList<Integer> getPath(int initialVertexId, int finalVertexId)
{
if (this.predecessors[initialVertexId][finalVertexId] != -1) {
path.add(initialVertexId);
while (initialVertexId != finalVertexId) {
initialVertexId = this.predecessors[initialVertexId][finalVertexId];
path.add(initialVertexId);
}
}
return path;
}
}
|
package com.example.usser.moneycatch;
public class Addrecycleitem {
private String name;
public Addrecycleitem(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package kxg.searchaf.url.hollisterco;
import java.util.*;
import kxg.searchaf.mail.Mail;
import kxg.searchaf.mail.SystemMail;
import kxg.searchaf.url.Constant;
import kxg.searchaf.util.ProxyUtli;
public class SearchHollisterco {
public HashMap<Integer, HollistercoProduct> allmenoldprolist = new HashMap<Integer, HollistercoProduct>();
public HashMap<Integer, HollistercoProduct> allmennewprolist = new HashMap<Integer, HollistercoProduct>();
public ArrayList<HollistercoProduct> menmatchprolist = new ArrayList<HollistercoProduct>();
public HashMap<Integer, HollistercoProduct> allwomenoldprolist = new HashMap<Integer, HollistercoProduct>();
public HashMap<Integer, HollistercoProduct> allwomennewprolist = new HashMap<Integer, HollistercoProduct>();
public ArrayList<HollistercoProduct> womenmatchprolist = new ArrayList<HollistercoProduct>();
public HollistercoCode hollistercocode;
public static void main(String[] args) throws Exception {
ProxyUtli.setProxy(true);
SearchHollisterco hollisterco = new SearchHollisterco();
try {
// hollisterco.gethollistercocode();
// Thread.sleep(1000);
// hollisterco.gethollistercocode();
hollisterco.getnewproduct(1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getnewproduct(int i) {
// if (i % (6 * 24) == 0) {
// this.allmenoldprolist.clear();
// this.allwomenoldprolist.clear();
// }
if (i % (1) == 0) {
HollistercoMailList.sync();
}
gethollistercocode();
getnewMenproduct();
getnewWomenproduct();
}
public void gethollistercocode() {
System.out.println("Checking Hollister Code");
ParserHollistercoCode parserHollistercoCode = new ParserHollistercoCode();
try {
HollistercoCode newhollistercocode = parserHollistercoCode
.checkcode();
if (newhollistercocode != null) {
if (hollistercocode != null
&& !newhollistercocode.equals(hollistercocode)) {
if (!newhollistercocode.name.startsWith("Last Day"))
sendmail(newhollistercocode);
hollistercocode = newhollistercocode;
}
}
} catch (Exception e) {
SystemMail.sendSystemMail("error when get Hollister code,err:"
+ e.toString());
}
}
public void getnewMenproduct() {
System.out.println("Checking Hollister Mens");
this.allmennewprolist.clear();
this.menmatchprolist.clear();
checkMennewproduct();
sendmail(menmatchprolist, true);
}
public void getnewWomenproduct() {
System.out.println("Checking Hollister Womens");
this.allwomennewprolist.clear();
this.womenmatchprolist.clear();
checkWoMennewproduct();
sendmail(womenmatchprolist, false);
}
private void sendmail(HollistercoCode hollistercoCode) {
Date currentDate = new Date();
List<HollistercoMailList> hollistercomailist = HollistercoMailList
.getinstance();
for (int i = 0; i < hollistercomailist.size(); i++) {
HollistercoMailList amail = hollistercomailist.get(i);
if (amail.valideTime.after(currentDate) && amail.warningCode) {
send2one(amail, hollistercoCode);
}
}
}
private void send2one(HollistercoMailList amail,
HollistercoCode hollistercoCode) {
Mail m = new Mail();
m.mail_subject = HollistercoMailList.mail_subject + " 新折扣码";
m.mail_to = amail.mailaddress;
m.tagcontext.append(hollistercoCode.tagcontext);
m.sendMail(amail.getSendingMailRetryTimes());
}
private void sendmail(ArrayList<HollistercoProduct> matchprolist,
boolean isMen) {
if (matchprolist.size() == 0)
return;
Collections.sort(matchprolist);
Date currentDate = new Date();
List<HollistercoMailList> hollistercomailist = HollistercoMailList
.getinstance();
for (int i = 0; i < hollistercomailist.size(); i++) {
HollistercoMailList amail = hollistercomailist.get(i);
if (amail.valideTime.after(currentDate)) {
if (isMen && amail.warningMen) {
HollistercoUtil HollistercoUtil = new HollistercoUtil();
ArrayList<HollistercoProduct> usermatch = HollistercoUtil
.checkuser(matchprolist, amail, isMen);
send2one(usermatch, amail, isMen);
}
if (!isMen && amail.warningWomen) {
HollistercoUtil HollistercoUtil = new HollistercoUtil();
ArrayList<HollistercoProduct> usermatch = HollistercoUtil
.checkuser(matchprolist, amail, isMen);
send2one(usermatch, amail, isMen);
}
}
}
}
private void send2one(ArrayList<HollistercoProduct> matchprolist,
HollistercoMailList amail, boolean isMen) {
if (matchprolist.size() == 0)
return;
Mail m = new Mail();
if (isMen) {
m.mail_subject = HollistercoMailList.mail_subject + " 男士";
} else {
m.mail_subject = HollistercoMailList.mail_subject + " 女士";
}
m.mail_to = amail.mailaddress;
m.tagcontext
.append("<html><head><link rel=\"stylesheet\" href=\"http://www.hollisterco.com/hol/56603/css/global/site.css\"/></head><body>");
for (int i = 0; i < matchprolist.size(); i++) {
HollistercoProduct matchpro = matchprolist.get(i);
// attach html file
m.tagcontext
.append(matchpro
+ "<br/>"
+ matchpro.tagcontext
+ "<br/>************************************************<br/>");
}
m.tagcontext.append("</body></html>");
m.sendMail(amail.getSendingMailRetryTimes());
}
private void checkMennewproduct() {
boolean parsewithErr = false;
List<HollistercoPage> urllist = HollistercoPage
.getMenclearanceBySinglePageInstance(); // getClearanceInstance();getclearanceBySinglePageInstance
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allmennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
System.out.println("Error when get Hollisterco Men page."
+ e.getMessage());
}
}
urllist = HollistercoPage.getMenSaleBySinglePageInstance(); // getSaleInstance();getSaleBySinglePageInstance
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allmennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollister Men Sale page."
+ e.toString());
}
}
urllist = HollistercoPage.getMenSecretInstance();
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allmennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollister Men Secret page."
+ e.toString());
}
}
urllist = HollistercoPage.getMenAllInstance();
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allmennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollisterco Men All page."
+ e.toString());
}
}
System.out.println("found products:" + allmennewprolist.size());
if (allmennewprolist.size() == 0) {
// didn't get new product
return;
}
if (allmenoldprolist.size() == 0) {
// first time
if (!parsewithErr)
this.allmenoldprolist.putAll(allmennewprolist);
return;
}
// check new product
Iterator<Integer> entryKeyIterator = allmennewprolist.keySet()
.iterator();
while (entryKeyIterator.hasNext()) {
Integer key = entryKeyIterator.next();
HollistercoProduct product = allmennewprolist.get(key);
HollistercoProduct oldproduct = allmenoldprolist.get(key);
if (oldproduct != null) {
// have found this
if (oldproduct.price > product.price) {
// if (product.realdiscount <=
// HollistercoConstant.newproductcheck_discount) {
// price dis
product.addReason = "产品降价,旧价格:" + oldproduct.price;
if (checkInventory(product))
menmatchprolist.add(product);
// }
}
} else {
// if (product.realdiscount <=
// HollistercoConstant.newproductcheck_discount) {
// new one
product.addReason = "新产品";
if (checkInventory(product))
menmatchprolist.add(product);
// }
}
}
// put new to old list
if (!parsewithErr)
this.allmenoldprolist.clear();
this.allmenoldprolist.putAll(allmennewprolist);
}
private void checkWoMennewproduct() {
boolean parsewithErr = false;
List<HollistercoPage> urllist = HollistercoPage
.getWomenclearanceBySinglePageInstance(); // getClearanceInstance();getclearanceBySinglePageInstance
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allwomennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollister WoMen C page."
+ e.toString());
}
}
urllist = HollistercoPage.getWomenSaleBySinglePageInstance(); // getSaleInstance();getSaleBySinglePageInstance
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allwomennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollister Women S page."
+ e.toString());
}
}
urllist = HollistercoPage.getWomenSecretInstance();
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allwomennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollister woMen Secret page."
+ e.toString());
}
}
urllist = HollistercoPage.getWomenAllInstance();
for (int i = 0; i < urllist.size(); i++) {
HollistercoPage hollistercopage = urllist.get(i);
ParserHollistercoPage parserHollistercopage = new ParserHollistercoPage(
hollistercopage, allmennewprolist);
try {
parserHollistercopage.checkprice();
} catch (Exception e) {
// TODO Auto-generated catch block
parsewithErr = true;
SystemMail
.sendSystemMail("Error when get Hollister woMen Secret page."
+ e.toString());
}
}
System.out.println("found products:" + allwomennewprolist.size());
if (allwomennewprolist.size() == 0) {
// didn't get new product
return;
}
if (allwomenoldprolist.size() == 0) {
// first time
if (!parsewithErr)
this.allwomenoldprolist.putAll(allwomennewprolist);
return;
}
// check new product
Iterator<Integer> entryKeyIterator = allwomennewprolist.keySet()
.iterator();
while (entryKeyIterator.hasNext()) {
Integer key = entryKeyIterator.next();
HollistercoProduct product = allwomennewprolist.get(key);
HollistercoProduct oldproduct = allwomenoldprolist.get(key);
if (oldproduct != null) {
// have found this
if (oldproduct.price > product.price) {
// if (product.realdiscount <=
// HollistercoConstant.newproductcheck_discount) {
// price dis
product.addReason = "产品降价,旧价格:" + oldproduct.price;
if (checkInventory(product))
womenmatchprolist.add(product);
// }
}
} else {
// if (product.realdiscount <=
// HollistercoConstant.newproductcheck_discount) {
// new one
product.addReason = "新产品";
if (checkInventory(product))
womenmatchprolist.add(product);
// }
}
}
if (!parsewithErr)
this.allwomenoldprolist.clear();
this.allwomenoldprolist.putAll(allwomennewprolist);
}
public boolean checkInventory(HollistercoProduct product) {
ParserHollistercoProduct ParserHollistercoProduct = new ParserHollistercoProduct(
product);
ParserHollistercoProduct.checkColorItemInventory(true);
// return product.inventoryList == null ? false : true;
return true;
}
}
|
package com.qst.dms.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @author 陌意随影
TODO :基础数据类
*2019年11月7日 下午7:25:55
*/
public class DataBase implements Serializable{
private static final long serialVersionUID = 1L;
/**ID标识*/
private int id;
/**时间*/
private Date time;
/**地点*/
private String address;
/**状态*/
private int type;
/**"采集"*/
public static final int GATHER=1;
/**"匹配"*/
public static final int MATHCH=2;
/**"记录"*/
public static final int RECORD=3;
/**发送*/
public static final int SEND=4;
/**"接收"*/
public static final int RECIVE=5;
/**"归档"*/
public static final int WRITE=6;
/**"保存"*/
public static final int SAVE=7;
/**
* @return 获取id
*/
public int getId() {
return id;
}
/**
* @param id 设置id
*/
public void setId(int id) {
this.id = id;
}
/**
* @return 获取时间
*/
public Date getTime() {
return time;
}
/**
* @param time 设置时间
*/
public void setTime(Date time) {
this.time = time;
}
/**
* @return 获取地址
*/
public String getAddress() {
return address;
}
/**
* @param address 设置地址
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return 获取
*/
public int getType() {
return type;
}
/**
* @param type 设置状态
*/
public void setType(int type) {
this.type = type;
}
@SuppressWarnings("javadoc")
public DataBase() {
}
@SuppressWarnings("javadoc")
public DataBase(int id, Date time, String address, int type) {
this.id = id;
this.time = time;
this.address = address;
this.type = type;
}
@SuppressWarnings("javadoc")
public DataBase(Date time, String address, int type) {
this.time = time;
this.address = address;
this.type = type;
}
public String toString() {
return id + "," + time + "," + address + "," + type;
}
}
|
package net.cpollet.es.stores.fakes;
import net.cpollet.es.Event;
import net.cpollet.es.EventNotStoredException;
import net.cpollet.es.EventStore;
import java.util.Map;
public class SucceedingEventStore implements EventStore {
private final Event event;
public SucceedingEventStore(Event event) {
this.event = event;
}
@Override
public Event store(String aggregateId, Object payload) throws EventNotStoredException {
return event;
}
@Override
public Event store(String aggregateId, Object payload, Map<String, String> metadata) throws EventNotStoredException {
return event;
}
}
|
package reseau.couches;
import reseau.Message;
import reseau.adresses.Adresse;
import reseau.adresses.AdresseMac;
/**
* @author martine
*/
public class Ethernet extends Liaison12 {
public Ethernet(AdresseMac am ) {
super(am);
}
@Override
public void sendMessage(AdresseMac dest, Message message) {
Message entete = getEntete(dest, message);
entete.ajouter(message);
message = entete;
// Afficher une trace de l'envoi
System.out.println("Je suis " + getNom() + " et j'envoie " + message.size() + " octets : " + message);
// Transmettre à la couche
r.sendTrame(message);
}
/**
* Je reçois un message de la couche moinsUn
* @param message
*/
@Override
public void receiveMessage(Message message) {
AdresseMac adr=message.extraireAdresseMac();
if(adrMac.toString().equals(adr.toString())){
// Afficher une trace de la reception
System.out.println("Le message est pour ma gueule");
message.supprimer(12);
System.out.println("Je suis "+getNom()+" et je passse "+message.size()+" octets reçus : " +message);
((Reseau3) plusUn).receiveMessage(message);
} else {
System.out.println("Pas pour moi");
}
}
@Override
protected Message getEntete(AdresseMac dest, Message message) {
// Adresse Mac destination 48 bits), adresse Mac source (48 bits)
Message entete= new Message(dest);
entete.ajouter(adrMac);
return entete;
}
}
|
import java.util.Scanner;
public class Cinema {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String type = scan.nextLine().toLowerCase(); // Premiere, Normal, Discount
int rows = Integer.parseInt(scan.nextLine());
int cols = Integer.parseInt(scan.nextLine());
double hallCapacity = rows * cols;
double price = 0.0;
if (type.equals("premiere")) {
price = hallCapacity * 12.00;
} else if (type.equals("normal")) {
price = hallCapacity * 7.50;
} else {
price = hallCapacity * 5.00;
}
System.out.printf("%.2f leva", price);
}
}
|
package com.example.andrew.colorpicker.EyeChallenge;
import java.util.List;
import java.lang.InterruptedException;
import java.util.concurrent.TimeUnit;
import com.example.andrew.colorpicker.framework.Game;
import com.example.andrew.colorpicker.framework.Graphics;
import com.example.andrew.colorpicker.framework.Input.TouchEvent;
import com.example.andrew.colorpicker.framework.Screen;
public class MainMenuScreen extends Screen {
boolean pressed = false;
public MainMenuScreen(Game game)
{
super(game);
}
public void update(float deltaTime)
{
Graphics g = game.getGraphics();
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++)
{
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_DOWN)
{
if(inBounds(event, 150, 300, 67, 67))
{
pressed = true;
}
}
if(event.type == TouchEvent.TOUCH_UP)
{
if(inBounds(event, 150, 300, 67, 67)) {
pressed = false;
game.setScreen(new GameScreen(game));
return;
}
}
}
}
private boolean inBounds(TouchEvent event, int x, int y, int width, int height)
{
if(event.x > x && event.x < x + width - 1 &&
event.y > y && event.y < y + height - 1)
{
return true;
}
else
return false;
}
public void present(float deltaTime)
{
Graphics g = game.getGraphics();
g.drawPixmap(Assets.bg, 0, 0);
g.drawPixmap(Assets.title, -250, -250);
if(!pressed) {
g.drawPixmap(Assets.buttons, 150, 300, 0, 0, 64, 64);
}
else {
g.drawPixmap(Assets.buttons, 150, 300, 64, 0, 64, 64);
}
}
public void pause()
{
}
public void resume()
{
}
public void dispose()
{
}
}
|
package com.fujitsu.frontech.palmsecure_smpl.segovia;
import java.io.File;
import java.io.FilenameFilter;
public class SegoviaCSVFilter implements FilenameFilter {
private static final String EXTENSION = ".csv";
private static String campaign;
public SegoviaCSVFilter(String campaign) {
SegoviaCSVFilter.campaign = campaign;
}
public boolean accept(File dir, String name) {
boolean result = false;
String checkFormat = campaign;
File file = new File(dir, name);
if (file.isFile()) {
String fileName = file.getName();
if (fileName.endsWith(EXTENSION)) {
if (fileName.startsWith(checkFormat)) {
if (fileName.length() <=
(checkFormat.length() + EXTENSION.length())) {
result = true;
}
}
}
}
return result;
}
public static String GetCampaign(File file) {
String id = file.getName(); // CCCCCCCC.csv
id = id.substring(0, id.indexOf(EXTENSION)); // CCCCCCCC
return id;
}
public static String GetFileName(File dir, String campaign) {
StringBuffer buff = new StringBuffer(dir.getAbsolutePath());
buff = buff.append(File.separator);
buff = buff.append(campaign);
buff = buff.append(EXTENSION);
return buff.toString();
}
}
|
package com.framgia.fsalon.screen.customerinfo.user;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.framgia.fsalon.R;
import com.framgia.fsalon.data.model.User;
import com.framgia.fsalon.databinding.FragmentUserBinding;
import com.framgia.fsalon.utils.Constant;
import static com.framgia.fsalon.utils.Constant.RequestPermission.REQUEST_CALL_PERMISSION;
/**
* User Screen.
*/
public class UserFragment extends Fragment {
private UserContract.ViewModel mViewModel;
public static UserFragment newInstance(User user) {
UserFragment fragment = new UserFragment();
Bundle args = new Bundle();
args.putParcelable(Constant.BUNDLE_USER, user);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
User user = getArguments().getParcelable(Constant.BUNDLE_USER);
mViewModel = new UserViewModel(this, user);
UserContract.Presenter presenter =
new UserPresenter(mViewModel);
mViewModel.setPresenter(presenter);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
FragmentUserBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user,
container, false);
binding.setViewModel((UserViewModel) mViewModel);
return binding.getRoot();
}
@Override
public void onStart() {
super.onStart();
mViewModel.onStart();
}
@Override
public void onStop() {
mViewModel.onStop();
super.onStop();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CALL_PERMISSION:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
mViewModel.onPermissionDenied();
} else {
mViewModel.onPermissionGranted();
}
break;
default:
break;
}
}
}
|
package com.andikaahmad.aplikasikeuangan;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.andikaahmad.aplikasikeuangan.Config.Database;
public class MainActivity extends AppCompatActivity {
Database db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
db = new Database(this) ;
createTable();
setText() ;
askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,0x3);
}
private void askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
}
}
public void setText(){
String sql = "SELECT * FROM tblidentitas" ;
TextView title1 = (TextView) findViewById(R.id.title1);
TextView title2 = (TextView) findViewById(R.id.title2);
if (db.countRows(sql) > 0){
Cursor c = db.select(sql) ;
c.moveToNext();
title1.setText(c.getString(c.getColumnIndex("nama")));
title2.setText(c.getString(c.getColumnIndex("alamat")));
}
}
public void reset(View v){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this) ;
alertBuilder.setMessage("Apakah anda yakin akan mereset database ?") ;
alertBuilder.setPositiveButton("Iya", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
reset2();
}
}) ;
alertBuilder.setNegativeButton("Tidak",null) ;
AlertDialog alertDialog = alertBuilder.create() ;
alertDialog.show();
}
public void reset2(){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this) ;
alertBuilder.setMessage("Apakah anda Setuju akan mereset database ?") ;
alertBuilder.setPositiveButton("Tidak", null) ;
alertBuilder.setNegativeButton("Setuju",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
resetAkhir() ;
}
}) ;
AlertDialog alertDialog = alertBuilder.create() ;
alertDialog.show();
}
public void resetAkhir(){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this) ;
alertBuilder.setMessage("Apakah anda yakin akan mereset database ?") ;
alertBuilder.setPositiveButton("Iya", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String sql = "delete from tbltransaksi" ;
if (db.execution(sql)){
Toast.makeText(MainActivity.this, "Berhasil reset database. Silahkan restart aplikasi", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Gagal reset database", Toast.LENGTH_SHORT).show();
}
}
}) ;
alertBuilder.setNegativeButton("Tidak",null) ;
AlertDialog alertDialog = alertBuilder.create() ;
alertDialog.show();
}
public void createTable(){
if (!db.createTable()){
Toast.makeText(this, "Tabel dan Database gagal dibuat!", Toast.LENGTH_SHORT).show();
}
}
public void master(View view) {
// Intent intent = new Intent(this,ActivityMaster.class) ;
// startActivity(intent);
}
public void transaksi(View v){
// Intent intent = new Intent(this,ActivityTransaksi.class) ;
// startActivity(intent);
}
public void backup(View v){
// Intent intent = new Intent(this,ActivityBackup.class) ;
// startActivity(intent);
}
public void restore(View v){
// Intent intent = new Intent(this,ActivityRestore.class) ;
// startActivity(intent);
}
public void laporan(View v){
// Intent intent = new Intent(this, ActivityLaporan.class) ;
// startActivity(intent);
// Intent i = new Intent(this, ActivityCetak.class) ;
// i.putExtra("faktur","000000001") ;
// startActivity(i);
}
public void petunjuk(View v){
// Intent i = new Intent(this, ActivityPetunjuk.class) ;
// startActivity(i);
}
//
public void guide(View v){
// Intent i = new Intent(this, ActivityPenggunaan.class) ;
// startActivity(i);
}
public void tentang(View v){
// Intent i = new Intent(this, ActivityTentang.class) ;
// startActivity(i);
}
}
|
import java.util.*;
class HashMapExample{
public static void main(String []z){
Map<Integer,String> hm1=new HashMap<Integer,String>();
hm1.put(1,"krishan");
hm1.put(2,"gulati");
hm1.put(3,"krishan");
hm1.put(4,"sarth");
hm1.put(5,"gulati");
hm1.put(6,"gulati");
hm1.put(7,"krishan");
hm1.put(8,"sarth");
HashMap<String,Integer> hm2=new HashMap<String,Integer>();
for(int i=1;i<(hm1.size()+1);i++){
hm2.put(hm1.get(i), 1);
}
int i=0;
for(Map.Entry me:hm2.entrySet()){
for(Map.Entry me1:hm1.entrySet()){
if(me.getKey().equals(me1.getValue())){
me.setValue(++i);
}
}
i=0;
}
for(Map.Entry me2:hm2.entrySet()){
System.out.println(""+me2.getKey()+" "+me2.getValue());
}
}
}
|
package application.client.ui.admin;
public class admin {
}
|
/*
* 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 server.control.tasks;
/**
*
* @author luisburgos
*/
public class ReservedSeatTask extends SeatTask {
private final static String TAG = "RESERVED SEAT";
private final static long SLEEP_TIME = 60000;
public ReservedSeatTask(int eventID, int seatNumber) {
super(TAG, SLEEP_TIME, eventID, seatNumber);
}
public ReservedSeatTask(int eventID, int seatNumber, OnWaitingTimeFinished listener) {
this(eventID, seatNumber);
setWaitingFinishListener(listener);
}
}
|
package collections.demo;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class AscEvenSet {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int var=0;
System.out.println("Enter the number of elements in set: ");
Set<Integer> hashset= new HashSet<Integer>();
int n= s.nextInt();
for(int i=0;i<n;i++) {
var= s.nextInt();
hashset.add(var);
}
System.out.println("Elements in the hashset are: ");
System.out.println(hashset);
Set<Integer> treeset= new TreeSet<Integer>(hashset);
System.out.println("Sorted Treeset elements are: ");
System.out.println(treeset);
Set<Integer> remove= new TreeSet<Integer>(treeset);
System.out.println("Odd numbers removed from treeset are:");
for (Integer odd : remove) {
if(odd%2!=0) {
treeset.remove(odd); // remove odd numbers
}
}
System.out.println(treeset); // print the even numbers
}
}
|
package HelloWorld;
public class HelloWorld {
public static void main(String[] args)
{
System.out.println("Hello World");
System.out.println("Look Mom Im prgraming, by the way MR. Brosius is not a very good speller.");
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("*");
System.out.println("******************");
System.out.println("******************");
System.out.println("******************");
System.out.println("* *");
System.out.println("* *");
System.out.println("* *");
System.out.println("* *");
System.out.println("* *");
System.out.println("* *");
System.out.println("* *");
System.out.println("* *");
}
}
|
package mobi.app.redis;
/**
* User: thor
* Date: 12-12-27
* Time: 下午1:50
*/
public class ZEntity<T> {
public final T member;
public final double score;
public ZEntity(T member, double score) {
this.member = member;
this.score = score;
}
}
|
package com.capgemini.batatatinhadellivery.enums;
public enum TipoProduto {
BATATA,BEBIDA,ADICONAIS
}
|
package com.nanyin.enumEntity;
public enum DeletedStatusEnum {
IS_NOT_DELETED(false),
IS_DELETED(true);
private DeletedStatusEnum(boolean judge) {
this.judge = judge;
}
private boolean judge;
public boolean isJudge() {
return judge;
}
}
|
package com.library.Library.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.*;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Entity
public class Reader {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "LASTNAME")
private String lastname;
@Column(name = "ADRESS")
private String adress;
@Column(name = "PHONE_NUMBER")
private Integer phoneNumber;
@OneToMany(
targetEntity = Reservation.class,
mappedBy = "reader")
private List<Reservation> reservations = new ArrayList<>();
}
|
package com.cyhz_common_component_activity;
import android.test.ActivityInstrumentationTestCase2;
/**
* Created by liuxiaolong on 15/8/14.
*/
public class PicTest extends ActivityInstrumentationTestCase2<CCA_TestActivity> {
public PicTest(Class<CCA_TestActivity> activityClass) {
super(activityClass);
}
public void testShow(){
BaseEntity<LoginEntity> entity = new BaseEntity<>();
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind;
import org.springframework.http.ProblemDetail;
import org.springframework.lang.Nullable;
/**
* Base class for {@link ServletRequestBindingException} exceptions that could
* not bind because the request value is required but is either missing or
* otherwise resolves to {@code null} after conversion.
*
* @author Rossen Stoyanchev
* @since 5.3.6
*/
@SuppressWarnings("serial")
public class MissingRequestValueException extends ServletRequestBindingException {
private final boolean missingAfterConversion;
/**
* Constructor with a message only.
*/
public MissingRequestValueException(String msg) {
this(msg, false);
}
/**
* Constructor with a message and a flag that indicates whether a value
* was present but became {@code null} after conversion.
*/
public MissingRequestValueException(String msg, boolean missingAfterConversion) {
super(msg);
this.missingAfterConversion = missingAfterConversion;
}
/**
* Constructor with a given {@link ProblemDetail}, and a
* {@link org.springframework.context.MessageSource} code and arguments to
* resolve the detail message with.
* @since 6.0
*/
protected MissingRequestValueException(String msg, boolean missingAfterConversion,
@Nullable String messageDetailCode, @Nullable Object[] messageDetailArguments) {
super(msg, messageDetailCode, messageDetailArguments);
this.missingAfterConversion = missingAfterConversion;
}
/**
* Whether the request value was present but converted to {@code null}, e.g. via
* {@code org.springframework.core.convert.support.IdToEntityConverter}.
*/
public boolean isMissingAfterConversion() {
return this.missingAfterConversion;
}
}
|
package com.gtambit.gt.app.MemberCard;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.Api.CommonParameters;
import com.ambit.city_guide.R;
import com.gtambit.gt.app.api.GtRequestApi;
import com.gtambit.gt.app.api.gson.MemberCardListObj;
import com.gtambit.gt.app.mission.obj.ProfileType;
import com.tms.lazytip.DrawerActivity;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import ur.ga.URGAManager;
import ur.ui_component.drawer.URMenuType;
import ur.ur_flow.coupon.URCouponActivity;
public class MemberCardHeadPageActivity extends DrawerActivity implements android.location.LocationListener {
private Button mMemberCardBtn;
private MemberCardListObj mMemberCardListObj;
private LinearLayout mNoJoinCardLayout;
private ListView mMemberCardList;
private String KEY_SHOP_NAME = "poiname";
private String KEY_SHOP_TEL = "poitel";
private String KEY_SHOP_PHOTO = "poiphoto";
private String KEY_SHOP_CAT = "poicat";
private int intResouce = R.layout.membercard_love_list;
private String[] shopfrom = {
KEY_SHOP_NAME,
KEY_SHOP_TEL,
KEY_SHOP_CAT,
KEY_SHOP_PHOTO,
};
private int[] shopto = {
R.id.TextViewPoiName,
R.id.TextViewPoiTel,
R.id.TextViewstorecat,
R.id.ImageViewStortePicture,
};
private LocationManager locationMgr;
private String mGooglelat, mGooglelon;
private boolean isCencel = false;
private ProgressDialog progressDialog;
@Override
public URMenuType onCurrentMenuType() {
return URMenuType.MEMBERCARD;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_card_head_page);
this.locationMgr = (LocationManager) this.getSystemService(LOCATION_SERVICE);
URGAManager.sendScreenName(MemberCardHeadPageActivity.this, getResources().getString(R.string.ga_membercard));
}
@Override
protected void onResume() {
super.onResume();
initLayout();
getList();
// 取得位置提供者,不下條件,讓系統決定最適用者,true 表示生效的 provider
String provider = this.locationMgr.getBestProvider(new Criteria(), true);
if (provider == null) {
return;
}
this.locationMgr.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 30000, 1500, this);
Location location = this.locationMgr.getLastKnownLocation(provider);
if (location == null) {
location = this.locationMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
this.onLocationChanged(location);
return;
}
this.onLocationChanged(location);
}
private void initLayout() {
setTitleName(getResources().getString(R.string.ur_menu_member_card));
setMenuBtn(true, null);
mMemberCardBtn = (Button) findViewById(R.id.btn_coupon_store);
mNoJoinCardLayout = (LinearLayout) findViewById(R.id.nojoincard);
mMemberCardList = (ListView) findViewById(R.id.membercardlist);
mMemberCardBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(MemberCardHeadPageActivity.this, URCouponActivity.class);
startActivity(i);
}
});
}
public void getList() {
new Thread() {
@Override
public void run() {
String userID = ProfileType.getUserId(MemberCardHeadPageActivity.this);
if(userID==null) {
mNoJoinCardLayout.setVisibility(View.VISIBLE);
return;
}
mMemberCardListObj = GtRequestApi.getMeMberCardList(MemberCardHeadPageActivity.this, userID);
if (mMemberCardListObj == null) {
mNoJoinCardLayout.setVisibility(View.VISIBLE);
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
mNoJoinCardLayout.setVisibility(View.GONE);
mMemberCardList.setVisibility(View.VISIBLE);
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
mMemberCardList.setDividerHeight(0);
mMemberCardList.setDivider(null);
if (mMemberCardListObj.data == null) {
mNoJoinCardLayout.setVisibility(View.VISIBLE);
mMemberCardList.setVisibility(View.GONE);
return;
}
mNoJoinCardLayout.setVisibility(View.GONE);
mMemberCardList.setVisibility(View.VISIBLE);
for (MemberCardListObj.Data mdata : mMemberCardListObj.data) {
Double listlat = mdata.lat;
Double listlong = mdata.lon;
float listdistance = 0;
if (mGooglelat != null && mGooglelon != null) {
Location crntLocation = new Location("");
crntLocation.setLatitude(Double.parseDouble(mGooglelat));
crntLocation.setLongitude(Double.parseDouble(mGooglelon));
Location newLocation = new Location("");
newLocation.setLatitude(listlat);
newLocation.setLongitude(listlong);
listdistance = crntLocation.distanceTo(newLocation); // in m
listdistance = listdistance / 1000;//km
mdata.shopKm = (int) listdistance;
} else {
mdata.shopKm = 0;
}
}
Arrays.sort(mMemberCardListObj.data);
for (MemberCardListObj.Data mdata : mMemberCardListObj.data) {
HashMap<String, Object> hm = addStoreData(mdata);
data.add(hm);
}
com.hyxen.app.ZeroCard.Api.MySimpleAdapter mSimpleAdapter;
mSimpleAdapter = new com.hyxen.app.ZeroCard.Api.MySimpleAdapter(MemberCardHeadPageActivity.this, data, intResouce, shopfrom, shopto);
mMemberCardList.setAdapter(mSimpleAdapter);
mMemberCardList.setOnItemClickListener(onPoiListItemClickListener);
}
});
}
}.start();
}
private HashMap<String, Object> addStoreData(final MemberCardListObj.Data mdata) {
HashMap<String, Object> shopname = new HashMap<String, Object>();
String km = null;
Double listlat = mdata.lat;
Double listlong = mdata.lon;
float listdistance = 0;
if (mGooglelat != null && mGooglelon != null) {
Location crntLocation = new Location("");
crntLocation.setLatitude(Double.parseDouble(mGooglelat));
crntLocation.setLongitude(Double.parseDouble(mGooglelon));
Location newLocation = new Location("");
newLocation.setLatitude(listlat);
newLocation.setLongitude(listlong);
listdistance = crntLocation.distanceTo(newLocation); // in m
listdistance = listdistance / 1000;//km
km= new DecimalFormat("0.0").format(listdistance);
} else {
mdata.shopKm = 0;
}
shopname.put(KEY_SHOP_NAME, mdata.shop_name);
shopname.put(KEY_SHOP_TEL, mdata.shop_en_name);
shopname.put(KEY_SHOP_CAT,km+ "km");
shopname.put(KEY_SHOP_PHOTO, mdata.cardpic_link);
return shopname;
}
@Override
public void onLocationChanged(Location location) {
if (location == null) {
mGooglelat = String.valueOf(CommonParameters.getLastLatlng().latitude);
mGooglelon = String.valueOf(CommonParameters.getLastLatlng().longitude);
} else {
mGooglelat = String.valueOf(location.getLatitude());
mGooglelon = String.valueOf(location.getLongitude());
this.locationMgr.removeUpdates(this);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
private AdapterView.OnItemClickListener onPoiListItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String mShopid = mMemberCardListObj.data[position].shop_id;
final String mShopName = mMemberCardListObj.data[position].shop_name;
Intent i = new Intent();
i.setClass(MemberCardHeadPageActivity.this,MemberCardDetatilActivity.class);
Bundle bundle = new Bundle();
bundle.putString("mShopid",mShopid);
bundle.putString("mShopName",mShopName);
i.putExtras(bundle);
startActivity(i);
MemberCardHeadPageActivity.this.finish();
}
};
}
|
package com.github.tobby48.java.scene3;
/**
* <pre>
* com.github.tobby48.java.scene3
* Robot.java
*
* 설명 :클래스 기본 정리 예제
* </pre>
*
* @since : 2017. 11. 15.
* @author : Administrator
* @version : v1.0
*/
public class Robot extends Toy{
String gender;
Robot(int price, String name){
super(price, name);
}
void play(){
super.play();
System.out.println(name+"를 움직입니다.");
}
void play(String personName){
System.out.println(personName + "이" + getToy().price + "짜리"+
name+"를 움직입니다.");
}
public static void main(String[] args){
Toy toy = new Toy(5, "레고");
toy.play();
Dol dol = new Dol(5, "레고");
dol.play();
Robot robot = new Robot(10, "로봇");
robot.play();
robot.play("돌쌤");
System.out.println(Toy.MaxSize);
}
}
|
package kr.ac.kopo.day02.homework;
import java.util.Scanner;
public class HomeworkMain03b {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("물건값 입력: ");
int price = sc.nextInt();
System.out.print("지불액수 입력: ");
int payment = sc.nextInt();
sc.close();
int change = payment - price;
// change = (a * 1000) + (b * 500) + (c * 100) + (d * 50) + (e * 10)
int a = change / 1000;
int b = (change - (a * 1000)) / 500;
int c = (change - (a * 1000) - (b * 500)) / 100;
int d = (change - (a * 1000) - (b * 500) - (c * 100)) / 50;
int e = (change - (a * 1000) - (b * 500) - (c * 100) - (d * 50)) / 10;
if (price > payment) {
System.out.println((price - payment) + "원이 부족합니다.");
} else if (price == payment) {
System.out.println("거스름돈이 없습니다.");
} else {
System.out.println("거스름돈: " + change);
System.out.println("1000원: " + a);
System.out.println("500원: " + b);
System.out.println("100원: " + c);
System.out.println("50원: " + d);
System.out.println("10원: " + e);
}
}
}
|
package com.db.aspects;
import com.db.persistence.events.audit.ObjectModificationEvent;
import com.db.persistence.objectStore.VirtualizedEntityManager;
import com.db.persistence.scheme.BaseObject;
import com.db.persistence.workSession.WorkSessionManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
@Aspect
public class ObjectsModificationAspect {
private final static Logger LOGGER = Logger.getLogger(ObjectsModificationAspect.class);
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private WorkSessionManager workSessionManager;
@PostConstruct
public void init() {
System.out.println("TalAspect " + publisher);
}
@Around("execution(* com.db.persistence.objectStore.VirtualizedEntityManager.movePrivateToPublic(..))")
@Transactional
public void aroundMovePrivateToPublic(ProceedingJoinPoint pjp) throws Throwable {
try {
LOGGER.debug("Using Aspect -> " + pjp + " -- " + publisher);
Object[] args = pjp.getArgs();
BaseObject privateItem = (BaseObject) args[0];
BaseObject publicItem = (BaseObject) args[1];
Integer nextRevision = (Integer) args[3];
System.out.println("From: " + privateItem);
System.out.println("To: " + publicItem);
String userName = workSessionManager.getUserNameByCtx(privateItem.getKeyId().getEntityManagerCtx());
System.out.println("Around before is running! - By User:" + userName);
pjp.proceed();
this.publisher.publishEvent(new ObjectModificationEvent(publicItem, privateItem, nextRevision, userName));
System.out.println("Around after is running!");
}
catch (Throwable t) {LOGGER.error("Error occur during event publishing:" + t.getMessage(), t);}
}
@Around("execution(* com.db.persistence.objectStore.VirtualizedEntityManager.movePrivateToPublicForFirstTime(..))")
@Transactional
public void aroundMovePrivateToPublicForFirstTime(ProceedingJoinPoint pjp) throws Throwable {
try {
LOGGER.debug("Using Aspect1 -> " + pjp);
Object[] args = pjp.getArgs();
BaseObject privateItem = (BaseObject) args[0];
Integer nextRevision = (Integer) args[2];
System.out.println("New: " + privateItem);
String userName = workSessionManager.getUserNameByCtx(privateItem.getKeyId().getEntityManagerCtx());
System.out.println("Around before is running! - By User:" + userName);
pjp.proceed();
this.publisher.publishEvent(new ObjectModificationEvent(null, privateItem, nextRevision, userName));
System.out.println("Around after is running!");
}
catch (Throwable t) {LOGGER.error("Error occur during event publishing:" + t.getMessage(), t);}
}
}
|
// https://leetcode.com/problems/consecutive-characters/solution/
class Solution {
public int maxPower(String s) {
if (s.length() == 1) return 1;
int count = 0, maxCount = 0;
char previous = ' ';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == previous) {
count++;
} else {
count = 1;
previous = c;
}
maxCount = Math.max(maxCount, count);
}
return maxCount;
}
}
|
package org.jaxws.stub2html.model;
import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* Imagine a Java Language Variable = a Field in a Java Class, or a Parameter in
* a Java Method
*
* @author chenjianjx
*
*/
public class JavaLanguageVariable {
/**
* as "order" in @XmlType(name = "order"). If the name is not specified in
*
* @XmlType, use the field name
*/
private String variableName;
/**
* the java type of a variable, such as "Order.class"
*/
private Class<?> type;
private boolean required;
private boolean multiOccurs;
/**
* is it transmitted via soap header?
*/
private boolean header;
public boolean isHeader() {
return header;
}
public void setHeader(boolean header) {
this.header = header;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String name) {
this.variableName = name;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
@Override
public String toString() {
return new ToStringBuilder(this, SHORT_PREFIX_STYLE).append(type).append(variableName).toString();
}
public boolean isMultiOccurs() {
return multiOccurs;
}
public void setMultiOccurs(boolean multiOccurs) {
this.multiOccurs = multiOccurs;
}
}
|
package writer;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class SpaceSeparatedNumberWriter extends AbstractNumberWriter implements NumberWriter {
private static final int NUMBER_OF_ELEMENTS_IN_LINE = 10;
private StringBuilder currentLine;
private int numbersInCurrentLine;
private boolean wroteLine;
private BufferedWriter writer;
@Override
public void writeNumbers(List<Double> input, String filePath) throws IOException {
Path path = openFile(filePath);
initializeHelpers();
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
this.writer = writer;
for (Double x : input)
writeSingleNumber(x);
}
}
private void initializeHelpers() {
this.currentLine = new StringBuilder();
this.numbersInCurrentLine = 0;
this.wroteLine = false;
}
private void writeSingleNumber(Double number) throws IOException {
addNumberToCurrentLine(number);
this.numbersInCurrentLine++;
if (this.numbersInCurrentLine == NUMBER_OF_ELEMENTS_IN_LINE) {
this.numbersInCurrentLine = 0;
this.writeCurrentLine();
}
}
private void writeCurrentLine() throws IOException {
if (this.wroteLine) {
this.writer.write("\n");
}
this.wroteLine = true;
this.writer.write(this.currentLine.toString());
this.currentLine.setLength(0);
}
private void addNumberToCurrentLine(Double x) {
if (this.numbersInCurrentLine > 0) {
currentLine.append(" ");
}
currentLine.append(x);
}
}
|
package com.airelogic.artistinfo.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
public class LLyrics {
@JsonProperty("lyrics")
String lyrics;
public LLyrics() {
}
public LLyrics(String lyrics) {
this.lyrics = lyrics;
}
public String getLyrics() {
return lyrics;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LLyrics lLyrics = (LLyrics) o;
return Objects.equals(lyrics, lLyrics.lyrics);
}
@Override
public int hashCode() {
return Objects.hash(lyrics);
}
@Override
public String toString() {
return "LLyrics{" +
"lyrics='" + lyrics + '\'' +
'}';
}
}
|
package no.nav.vedtak.log.util;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.function.Predicate.not;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
public final class LoggerUtils {
private static final int DEFAULT_LENGTH = 50;
private LoggerUtils() {
}
public static String removeLineBreaks(String string) {
return Optional.ofNullable(string).map(s -> s.replaceAll("\\R", "")).orElse(null);
}
public static String toStringWithoutLineBreaks(Object object) {
return Optional.ofNullable(object).map(Object::toString).map(LoggerUtils::removeLineBreaks).orElse(null);
}
public static String taint(String value) {
if (!value.matches("[a-zA-Z0-9]++")) {
throw new IllegalArgumentException(value);
}
return value;
}
public static String endelse(List<?> liste) {
return liste.size() == 1 ? "" : "er";
}
public static String limit(String tekst) {
return limit(tekst, DEFAULT_LENGTH);
}
public static String limit(String tekst, int max) {
return Optional.ofNullable(tekst).filter(t -> t.length() >= max).map(s -> s.substring(0, max - 1) + "...").orElse(tekst);
}
public static String limit(byte[] bytes, int max) {
return limit(Arrays.toString(bytes), max);
}
public static String partialMask(String value) {
return partialMask(value, 11);
}
public static String partialMask(String value, int length) {
return (value != null) && (value.length() == length) ? padEnd(value.substring(0, length / 2 + length % 2), length, '*') : value;
}
public static String mask(String value) {
return Optional.ofNullable(value).map(String::stripLeading).filter(not(String::isBlank)).map(v -> "*".repeat(v.length())).orElse("<null>");
}
public static String encode(String string) {
return encode(string, UTF_8);
}
public static String encode(String string, Charset charset) {
return Base64.getEncoder().encodeToString(string.getBytes(charset));
}
public static String padEnd(String string, int minLength, char padChar) {
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
sb.append(string);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
return sb.toString();
}
}
|
package com.sinodynamic.hkgta.dao.mms;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.dto.mms.MmsOrderItemDto;
import com.sinodynamic.hkgta.dto.mms.SpaCancelledNotificationInfoDto;
import com.sinodynamic.hkgta.entity.crm.Member;
import com.sinodynamic.hkgta.entity.mms.SpaAppointmentRec;
@Repository
public class SpaAppointmentRecDaoImpl extends GenericDao<SpaAppointmentRec>
implements SpaAppointmentRecDao {
public Serializable saveSpaAppointmenRec(SpaAppointmentRec sapAppointmenRec){
return save(sapAppointmenRec);
}
public SpaAppointmentRec getBySysId(Long sysId){
return null;
}
@Override
public List<SpaAppointmentRec> getSpaAppointmentRecByExtinvoiceNo(String extInvoiceNo) {
String hql = "from SpaAppointmentRec where extInvoiceNo = ? order by sysId";
List<Serializable> params = new ArrayList<Serializable>();
params.add(extInvoiceNo);
return getByHql(hql, params);
}
@Override
public int deleteByExtInvoiceNo(String extInvoiceNo) {
String hql = "delete from spa_appointment_rec where ext_invoice_no = ?";
List<Serializable> params = new ArrayList<Serializable>();
params.add(extInvoiceNo);
return deleteByHql(hql, params);
}
@Override
public void updateSpaAppointmentRec(SpaAppointmentRec spaAppointmentRec) {
update(spaAppointmentRec);
}
@Override
public List<MmsOrderItemDto> getAppointmentItemsByExtinvoiceNo(String extInvoiceNo) {
String sql = "select sar.ext_appointment_id as appointmentId, sar.ext_employee_code as therapistCode,"
+ "sar.ext_service_code as itemId, "
+ "sar.service_name as service, "
+ "concat(sar.ext_employee_first_name, ' ', sar.ext_employee_last_name) as therapist, "
+ "cod.item_total_amout as rate, "
+ "sar.status as status, "
+ "sar.start_datetime as startTime, "
+ "sar.end_datetime as endTime "
+ "from "
+ "spa_appointment_rec sar "
+ "left join customer_order_det cod on sar.order_det_id = cod.order_det_id "
+ "where sar.ext_invoice_no = ? ";
List<Serializable> params = new ArrayList<Serializable>();
params.add(extInvoiceNo);
return getDtoBySql(sql, params, MmsOrderItemDto.class);
}
@Override
public Date getLastestSpaSyncTime() {
String sql = "select max(ext_sync_timestamp) from spa_appointment_rec where create_by = 'spa_sync'";
Date date = (Date) getUniqueBySQL(sql, null);
return date;
}
@Override
public List<SpaAppointmentRec> getAppointmentRecsByAppointmentId(String appointmentId) {
String hql = "from SpaAppointmentRec where extAppointmentId = ?";
List<Serializable> params = new ArrayList<Serializable>();
params.add(appointmentId);
return getByHql(hql, params);
}
@Override
public List<SpaAppointmentRec> getAppointmentRecsByInvoiceNo(String extInvoiceNo) {
String hql = "from SpaAppointmentRec where extInvoiceNo = ?";
List<Serializable> params = new ArrayList<Serializable>();
params.add(extInvoiceNo);
return getByHql(hql, params);
}
@Override
public List<SpaCancelledNotificationInfoDto> getUserForSpaAppointmentBeginNotification() {
String sql = "select "
+ "mb.user_id as userId, "
+ "sar.start_datetime as startDatetime, "
+ "sar.end_datetime as endDatetime, "
+ "sar.service_name as serviceName, "
+ "sar.ext_employee_first_name as employFN, "
+ "sar.ext_employee_last_name as employLN "
+ "from spa_appointment_rec sar left join member mb on sar.customer_id = mb.customer_id "
+ "where sar.status = 'RSV' and timestampdiff(minute, sar.start_datetime, date_add(current_timestamp(), interval 1 hour)) = 0";
return getDtoBySql(sql, null, SpaCancelledNotificationInfoDto.class);
}
@Override
public List<SpaCancelledNotificationInfoDto> getUserForSpaAppointmentEndNotification() {
String sql = "select "
+ "mb.user_id as userId, "
+ "sar.start_datetime as startDatetime, "
+ "sar.end_datetime as endDatetime, "
+ "sar.service_name as serviceName, "
+ "sar.ext_employee_first_name as employFN, "
+ "sar.ext_employee_last_name as employLN "
+ "from spa_appointment_rec sar left join member mb on sar.customer_id = mb.customer_id "
+ "where sar.status = 'RSV' and timestampdiff(minute, sar.end_datetime, date_add(current_timestamp(), interval 10 minute)) = 0";
return getDtoBySql(sql, null, SpaCancelledNotificationInfoDto.class);
}
}
|
../../../jvmti-common/Breakpoint.java
|
package cn.edu.njnu.around_part;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import cn.edu.njnu.main_part.MainActivity;
import cn.edu.njnu.nnu_creative_cloud.*;
public class AroundActivity extends FunctionActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.around_entry);
}
@Override
public void return_back(View view) {
if (super.setting)
super.return_back(view);
else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
@Override
protected void get_ID() {
super.setting_container_id = R.id.around_entry;
}
}
|
package mainGame.components.interfaces;
/**
* This interface contains all the essential methods that'll make the column lane class work
*
* @author Justin Yau
*
*/
public interface ColumnLaneInterface {
/**
* This method converts the current x position and determines which column lane this is
* @return Returns the number of this column lane
* @author Justin Yau
*/
public int getLane();
}
|
package com.version.SpringOne.Repository;
import com.version.SpringOne.Model.UserData;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.Optional;
public interface UserRepo extends MongoRepository<UserData,String> {
@Query("{ id : ?0}")
Optional<UserData> findUser(String id);
@Query("{ 'name' : ?0}")
Optional<UserData> findUserByName(String name);
}
|
package com.example.elearning.rest;
import com.example.elearning.entities.Formateur;
import com.example.elearning.entities.Formation;
import com.example.elearning.entities.Module;
import com.example.elearning.repositories.ModuleRepository;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("module")
@CrossOrigin
public class moduleRestController {
//Actions
private ModuleRepository moduleRepository;
public moduleRestController(ModuleRepository moduleRepository) {
this.moduleRepository = moduleRepository;
}
@GetMapping()
public List<Module> allModules() {
return moduleRepository.findAll();
}
@GetMapping(path = "/{id}")
public ResponseEntity<Module> findById(@PathVariable("id") int idModule)
throws ResourceNotFoundException {
Module module = moduleRepository.findById(idModule)
.orElseThrow(() -> new ResourceNotFoundException("Aucun module trouvé avec : " + idModule));
return ResponseEntity.ok().body(module);
}
@PostMapping
public ResponseEntity<Module> addModule(@Valid @RequestBody Module module) {
try {
moduleRepository.save(module);
return new ResponseEntity<Module>(module, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<Module>(HttpStatus.NOT_ACCEPTABLE);
}
}
@PutMapping("/{id}")
public ResponseEntity<Module> updateModule(@PathVariable("id") int idModule, @RequestBody Module moduleDetails)
throws ResourceNotFoundException {
Module module = moduleRepository.findById(idModule)
.orElseThrow(() -> new ResourceNotFoundException("Aucun module trouvé avec : " + idModule));
module.setDescription(moduleDetails.getDescription());
module.setDuree(moduleDetails.getDuree());
module.setNom(moduleDetails.getNom());
module.setNbrchapitre(moduleDetails.getNbrchapitre());
module.setTyperessource(moduleDetails.getTyperessource());
//***************
module.setChapitres(moduleDetails.getChapitres());
module.setFormateur(moduleDetails.getFormateur());
module.setFormation(moduleDetails.getFormation());
module.setRessources(moduleDetails.getRessources());
module.setApprenants(moduleDetails.getApprenants());
//***************
final Module updatedModule = moduleRepository.save(module);
return ResponseEntity.ok(updatedModule);
}
@DeleteMapping("/{id}")
public Map<String, Boolean> deleteModule(@PathVariable("id") int idModule) throws Exception {
Module module = moduleRepository.findById(idModule)
.orElseThrow(() -> new ResourceNotFoundException("Aucun module trouvé avec : " + idModule));
moduleRepository.delete(module);
Map<String, Boolean> response = new HashMap<>();
response.put("Module supprimé", Boolean.TRUE);
return response;
}
}
|
package com.lxl.web.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lxl.beans.vo.DfGroup;
import com.lxl.beans.vo.DfItem;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xiaolu on 15/5/12.
*/
public class DfGroupVo {
private Integer id;
private String name;
private String type;
private String description;
List<DfItem> data;
public DfGroupVo(DfGroup group) {
this.id = group.getId();
this.name = group.getName();
this.description = group.getDescription();
this.type = "group";
this.data = new ArrayList<>();
}
public List<DfItem> getData() {
return data;
}
public void setData(List<DfItem> data) {
this.data = data;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
try {
return new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(this);
}catch (Exception e) {
return "";
}
}
}
|
package ltd.getman.testjobproject.utils;
/**
* Created by Artem Getman on 17.05.17.
* a.e.getman@gmail.com
*/
public class UIHelper {
}
|
public class Parent {
public void hello(){
System.out.println("hello parent");
bye();
}
public void bye(){
System.out.println("bye parent");
}
}
class Child extends Parent{
public void hello(){
super.hello();
}
public void bye(){
System.out.println("bye child");
}
public static void main(String[] args) {
Child child=new Child();
child.hello();
}
}
|
/**
* project name:saas
* file name:MsgIdentifyCodeController
* package name:com.cdkj.msg.controller
* date:2018/3/20 上午9:01
* author:bovine
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.manager.msg.controller;
import com.cdkj.common.base.controller.BaseController;
import com.cdkj.common.exception.CustException;
import com.cdkj.util.JsonUtils;
import com.cdkj.util.StringUtil;
import com.cdkj.constant.ErrorCode;
import com.cdkj.manager.msg.service.api.MsgIdentifyCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* description: 验证码短信控制器 <br>
* date: 2018/3/20 上午9:01
*
* @author bovine
* @version 1.0
* @since JDK 1.8
*/
@Api(value = "/msg/identify", description = "验证码短信控制器")
@RestController
@RequestMapping("/msg/identify")
public class MsgIdentifyCodeController extends BaseController {
@Resource
private MsgIdentifyCodeService msgIdentifyCodeService;
@ApiOperation(value = "发送短信", notes = "发送短信")
@ApiImplicitParams({
@ApiImplicitParam(name = "sysAccount", value = "帐套号", required = true, dataType = "String", paramType = "path"),
@ApiImplicitParam(name = "mobile", value = "手机号码", required = true, dataType = "String", paramType = "path")
})
@GetMapping("/open/send/{sysAccount}/{mobile}")
public String send(@PathVariable("sysAccount") String sysAccount, @PathVariable("mobile") String mobile) {
try {
if (!StringUtil.areNotEmpty(sysAccount, mobile)) {
throw new CustException(224, ErrorCode.ERROR_20001, "01", "参数异常");
}
return JsonUtils.toJson(msgIdentifyCodeService.send(sysAccount, mobile));
} catch (CustException ce) {
logger.error("MsgIdentifyCodeController.send()方法异常!error={}", ce);
return JsonUtils.resFailed(ce.getMsg());
} catch (Exception e) {
logger.error("MsgIdentifyCodeController.send()方法系统异常!error={}", e);
return JsonUtils.resFailed(224, ErrorCode.ERROR_20002, "01", "系统异常");
}
}
@ApiOperation(value = "发送短信", notes = "发送短信")
@ApiImplicitParams({
@ApiImplicitParam(name = "sysAccount", value = "帐套号", required = true, dataType = "String", paramType = "path"),
@ApiImplicitParam(name = "mobile", value = "手机号码", required = true, dataType = "String", paramType = "path")
})
@GetMapping("/open/send/{mobile}")
public String sendByMobile(@PathVariable("mobile") String mobile) {
try {
if (!StringUtil.areNotEmpty(mobile)) {
throw new CustException(224, ErrorCode.ERROR_20001, "01", "参数异常");
}
return JsonUtils.toJson(msgIdentifyCodeService.send(null, mobile));
} catch (CustException ce) {
logger.error("MsgIdentifyCodeController.sendByMobile()方法异常!error={}", ce);
return JsonUtils.resFailed(ce.getMsg());
} catch (Exception e) {
logger.error("MsgIdentifyCodeController.sendByMobile()方法系统异常!error={}", e);
return JsonUtils.resFailed(224, ErrorCode.ERROR_20002, "01", "系统异常");
}
}
}
|
package controller;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import dao.Dictionnaire;
import model.Main;
import vue.Vue;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
public class LoginController {
@FXML private TextField Text_NumeroCompte;
@FXML private PasswordField Text_Password;
@FXML private Button Btn_Connexion;
@FXML public void Btn_Connexion_Click()
{
String user = Text_NumeroCompte.getText();
String password = Text_Password.getText();
//On vérifie que les champs ne sont pas vides
if(user.isEmpty() || password.isEmpty())
{
Main.message_erreur("Veuillez renseigner un numéro d'utilisateur ainsi qu'un mot de passe");
}
else
{
try
{
ResultSet Resultat = Main.Req.connexion(user, password);
if (Resultat.isBeforeFirst())
{
while(Resultat.next())
{
int numClient = Resultat.getInt("numClient");
if(numClient != 0)
{
Main.IDClient = numClient;
new Vue("Compte",null,null);
}
}
}
else
Main.message_erreur("Numéro d'utilisateur ou mot de passe incorrect.");
} catch (Exception e)
{
Main.message_erreur("Erreur lors de la connexion : " + e.toString());
}
}
}
@FXML
public void btn_quitter()
{
Main.parentWindow.close();
}
}
|
package com.example.anand38.encryptit.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.anand38.encryptit.Helper.EncryptUtils;
import com.example.anand38.encryptit.Helper.FileJob;
import com.example.anand38.encryptit.R;
public class Login extends AppCompatActivity {
EditText email,password;
Button login;
TextView go_to_register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
findViewsById();
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String info= FileJob.read_from_file(getBaseContext());
if (info.length()==0){
Toast.makeText(Login.this, "You have not registered yet", Toast.LENGTH_SHORT).show();
}else{
String s[]=info.split(",");
String temp_email=s[0];
String temp_password=s[1];
System.out.println("Email:"+temp_email);
System.out.println("Password:"+temp_password);
EncryptUtils encryptUtils=new EncryptUtils();
if (!(email.getText().toString().trim().equals(temp_email) && password.getText().toString().trim().equals(encryptUtils.decrypt(temp_password)))){
Toast.makeText(Login.this, "Incorrect Username/Password", Toast.LENGTH_SHORT).show();
}else{
Intent i=new Intent(Login.this,MainActivity.class);
startActivity(i);
finish();
}
}
}
});
go_to_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//check if user has already registerd
String s=FileJob.read_from_file(getBaseContext());
if (s.length()>0){
Toast.makeText(Login.this, "You have already registered!! Please login to continue", Toast.LENGTH_SHORT).show();
}else {
Intent i = new Intent(Login.this, Register.class);
startActivity(i);
}
}
});
}
private void findViewsById() {
email= (EditText) findViewById(R.id.email);
password= (EditText) findViewById(R.id.password);
login= (Button) findViewById(R.id.login);
go_to_register= (TextView) findViewById(R.id.go_to_register);
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.db;
import java.util.List;
/**
* DatabaseManager is responsible of every database transaction.<br />
* It provides method to register, delete, synchronize objects in database.
* Each method will work on the object and its inheritance.
* An implementation of empty DB that keep everything in memory is also provided.
*
* @author The ProActive Team
* @since ProActive Scheduling 1.0
*/
public interface DatabaseManager {
/**
* Set user define property for the database session.<br />
* Properties that are set after building process won't be used. Set property before building the session factory.<br />
* This method override the default properties.
*
* @param propertyName the name of the property to set.
* @param value the value of the property.
*/
public void setProperty(String propertyName, String value);
/**
* Build the database.<br/>
* Call this method when you want to build the database. If not called,
* it will be automatically build when needed.<br />
* For performance reason, It is recommended to call this method during your application building process.<br /><br/>
* It is also possible to set some properties before building the session.
*/
public void build();
/**
* Close the databasae
*/
public void close();
/**
* Force a transaction to be started. This method has to be used only when multiple calls
* to methods of this class have to be performed.<br />
* For simple atomic call, transaction is implicit.<br /><br />
*
* To use the manual transaction, call this startTransaction() method,<br/>
* then, (when multiple modifications are done) a call to {@link #commitTransaction()} OR {@link #rollbackTransaction()}
* will terminate the transaction.
*/
public void startTransaction();
/**
* Force a manually opened transaction to be committed.
* See {@link #startTransaction()} for details.
*/
public void commitTransaction();
/**
* Force a manually opened transaction to be rolledback.
* See {@link #startTransaction()} for details.
*/
public void rollbackTransaction();
/**
* Register an object.
* This method will persist the given object and store it in the database.
*
* @param o the new object to store.
*/
public void register(Object o);
/**
* Delete an object.
* This method will delete the given object and also every dependences.
*
* @param o the new object to delete.
*/
public void delete(Object o);
/**
* Update the given entity and every dependences.
*
* @param o the entity to update.
*/
public void update(Object o);
/**
* Return a list of every <T> type stored in the database.
*
* @param <T> The type to be returned by the recovering call.
* @param egClass The class that represents the real type to be recover.
* @return a list of every <T> type stored in the database.
*/
public <T> List<T> recover(Class<T> egClass);
/**
* Return a list of every <T> type stored matching the given conditions.
*
* @param <T> The type to be returned by the recovering call.
* @param egClass The class that represents the real type to be recover.
* @param conditions a list of condition that represents the conditions of the request.
* @return a list of every <T> type stored matching the given conditions.
*/
public <T> List<T> recover(Class<T> egClass, Condition... conditions);
/**
* Synchronize the given object in the database.<br />
* The object must have @alterable field(s).
* In fact this method will only update the database for @alterable field for this object.
*
* @param o the object entity to synchronize.
*/
public void synchronize(Object o);
/**
* Load the @unloadable field in the given object.<br />
* This method will set, from the values in the database, every NULL fields that have the @unloadable annotation.
*
* @param o the object entity to load.
*/
public void load(Object o);
/**
* Cause every @unloadable fields in the given object to be set to NULL.<br />
* Primitive field type won't be unloaded.
*
* @param o the object to unload.
*/
public void unload(Object o);
/**
* Execute a native "SELECT" SQL query and return the result as a list. (see hibernate SQLQurey.list() for more details)
*
* @param nativeQuery the query to be executed, "must be a SELECT query"
* @return
*/
@SuppressWarnings("rawtypes")
public List sqlQuery(String nativeQuery);
/**
* Set the callback value to the given callback value<br/>
* call back system can be used to be notified when the database has encountered a disconnection
*
* @param callback the callback to set
*/
public void setCallback(FilteredExceptionCallback callback);
/**
* FilteredExceptionCallback is used to notify the implementation
* that a filtered exception has been raised.
*
* @author The ProActive Team
* @since ProActive Scheduling 3.1
*/
public interface FilteredExceptionCallback {
/**
* Notify the listener when a filtered exception is detected.<br/>
* In such a case, this method is called on the listener. Argument is the exception that
* caused this call wrapped in a DatabaseManagerException.<br/>
* <br/>
* Note : To get the real exception, just get the cause of the given exception.
*
* @param dme the DatabaseManagerException containing the cause.
*/
public void notify(DatabaseManagerException dme);
}
}
|
package com.algorithm.tree;
import java.util.ArrayList;
import java.util.List;
public class PathSum {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> innerList = new ArrayList();
int result = 0;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(root, innerList, sum);
return list;
}
private void dfs(TreeNode root, List<Integer> innerList, int sum) {
if (root == null) {
return;
}
innerList.add(root.val);
if (root.left == null && root.right == null) {
for (int i = 0; i < innerList.size(); i++) {
result += innerList.get(i);
}
if (result == sum) {
list.add(innerList);
}
result = 0;
}
List temp = new ArrayList(innerList);
dfs(root.left, innerList, sum);
dfs(root.right, temp, sum);
}
}
|
package webuters.com.geet_uttarakhand20aprilpro.activity;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import webuters.com.geet_uttarakhand20aprilpro.R;
//import com.google.analytics.tracking.android.EasyTracker;
//import com.google.analytics.tracking.android.MapBuilder;
//import com.google.analytics.tracking.android.StandardExceptionParser;
/**
* Created by Tushar on 3/1/2016.
*/
public class ContactUs extends Activity {
//TextView txt_EventName;
ListView listview;
public static TextView text_songname;
private File file;
public static ArrayList<String> myList = new ArrayList<>();
public static ArrayList<String> filepathlst = new ArrayList<>();
public static ArrayList<String> song_image_list = new ArrayList<>();
public static MediaPlayer mediaPlayer;
public static int pos;
public static boolean music_flag = true;
public static ImageView imgplay, imgpause;
SeekBar seekBar;
TextView remaingTxt, Totaltxt;
ImageView next;
public static boolean reset_player = false;
private ConnectionDetector cd;
public static String song_path="";
public static Handler myHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_us_layout);
listview = (ListView) findViewById(R.id.mymusic_songlist);
text_songname = (TextView) findViewById(R.id.text_songname);
imgplay = (ImageView) findViewById(R.id.img_playmusic);
imgpause = (ImageView) findViewById(R.id.img_pausemusic);
seekBar = (SeekBar) findViewById(R.id.seekBar);
remaingTxt = (TextView) findViewById(R.id.remaining_songtime_left_text1);
Totaltxt = (TextView) findViewById(R.id.total_song_time_text1);
seekBar.setClickable(false);
next = (ImageView) findViewById(R.id.btnNext);
cd = new ConnectionDetector(getApplicationContext());
seekBar.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// seekChange(v);
return false;
}
});
try {
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
//file = new File(root_sd + "/Download");
file = new File(root_sd + File.separator + "Android" + File.separator + "data" + File.separator + "webuters.com.geet_uttarakhand20aprilpro" + File.separator + "files");
file.mkdirs();
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
filepathlst.add(list[i].toString());
Log.d("sun", filepathlst.toString());
}
File file1 = new File(root_sd + File.separator + "Android" + File.separator + "data" + File.separator + "webuters.com.geet_uttarakhand20aprilpro" + File.separator + "images");
file1.mkdirs();
File list1[] = file1.listFiles();
for(int i=0;i<list1.length;i++){
song_image_list.add(list1[i].toString());
}
Log.d("sunil", song_image_list.toString());
}
catch (Exception e){
Log.d("sunil",e.toString());
}
ArrayAdapter<String> adapter = (new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList));
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AppConstant.setsavedmusicplaying(getApplicationContext(),false);
AppConstant.setmainmusicplaying(getApplicationContext(),false);
AppConstant.setfavmusicplaying(getApplicationContext(),false);
pos=i;
// song_path=filepathlst.get(i);
Intent intent=new Intent(ContactUs.this,SavedSongsMusicPlayer.class);
intent.putExtra("back",true);
startActivity(intent);
// startActivityForResult(intent,1);
}
});
}
//
// @Override
// protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// if (requestCode == 1) {
// if(resultCode == Activity.RESULT_OK){
// String result=data.getStringExtra("result");
// }
// if (resultCode == Activity.RESULT_CANCELED) {
// //Write your code if there's no result
// }
// }
// }
}
|
package chessknights.resultsJAXB;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import java.time.Duration;
import java.time.ZonedDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
public class Record implements Comparable<Record>{
/**
* The name of the player.
*/
private String player;
/**
* Number of total wins.
*/
private int totalWins;
/**
* For comparing objects of type Record.
* @param o passing instance of Record object to compare.
* @return positive value if totalWins field of first object, more than of the second.
* @return 0 value if totalWins field of first and second object are same.
* @return positive value if totalWins field of second object, more than of the first.
*/
@Override
public int compareTo(Record o) {
return Integer.compare(o.totalWins, totalWins);
}
}
|
package com.lucianoscilletta.battleship.ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import com.lucianoscilletta.battleship.graphics.*;
import com.lucianoscilletta.battleship.*;
import com.lucianoscilletta.battleship.ui.*;
public class CreditsPanel extends MessagePanel{
public CreditsPanel(){
super();
this.addComponent(new CreditsUI());
}
public void continueAction(){
GraphicsEngine.loadScreen(new MainMenuPanel());
}
}
|
package com.example.qiyue.mvp_dragger.entity;
/**
* Created by Administrator on 2016/11/17 0017.
*/
public class WeatherParam {
public String format;
public String cityname;
public String key;
}
|
package com.utils;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
public class ExtFreemarkerView extends FreeMarkerView {
@Override
protected void exposeHelpers(Map<String, Object> model,
HttpServletRequest request) throws Exception {
super.exposeHelpers(model, request);
model.put("base", request.getContextPath());
}
}
|
package algorithm.annealing.factory;
import java.util.ArrayList;
import java.util.List;
import algorithm.annealing.SAParameters;
import algorithm.annealing.SimulatedAnnealing;
import algorithm.annealing.neighbor.ConsecutiveSwap;
import algorithm.annealing.neighbor.NeighborGenerator;
import algorithm.annealing.neighbor.RandomSwap;
import algorithm.annealing.temperature.ExponentialSchedule;
import algorithm.annealing.temperature.LinearSchedule;
import algorithm.annealing.temperature.SigmoidSchedule;
import algorithm.annealing.temperature.TemperatureSchedule;
public class SAFactory {
public static SimulatedAnnealing getDefault() {
return new SimulatedAnnealing(new SAParameters());
}
public static SimulatedAnnealing getOptimal() {
SAParameters params = new SAParameters();
params.setNeighborGenerator(new RandomSwap());
params.setTemperatureSchedule(new LinearSchedule());
return new SimulatedAnnealing(params);
}
public static List<SimulatedAnnealing> getNeighborGenerators() {
List<Class<? extends NeighborGenerator>> classes = new ArrayList<Class<? extends NeighborGenerator>>();
classes.add(ConsecutiveSwap.class);
classes.add(RandomSwap.class);
List<SimulatedAnnealing> result = new ArrayList<SimulatedAnnealing>();
for (Class<? extends NeighborGenerator> clazz : classes) {
SAParameters params = new SAParameters();
try {
params.setNeighborGenerator(clazz.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
result.add(new SimulatedAnnealing(params));
}
return result;
}
public static List<SimulatedAnnealing> getTemperatureSchedules() {
List<Class<? extends TemperatureSchedule>> classes = new ArrayList<Class<? extends TemperatureSchedule>>();
classes.add(LinearSchedule.class);
classes.add(ExponentialSchedule.class);
classes.add(SigmoidSchedule.class);
List<SimulatedAnnealing> result = new ArrayList<SimulatedAnnealing>();
for (Class<? extends TemperatureSchedule> clazz : classes) {
SAParameters params = new SAParameters();
try {
params.setTemperatureSchedule(clazz.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
result.add(new SimulatedAnnealing(params));
}
return result;
}
}
|
package com.miaoke.hook.utils;
public class StackUtils {
public static String getMethodStack() {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StringBuilder stringBuilder = new StringBuilder();
for (StackTraceElement temp : stackTraceElements) {
stringBuilder.append(temp.toString()).append("\n");
}
return stringBuilder.toString();
}
}
|
package com.javaArray;
import java.util.ArrayList;
public class Bank {
private ArrayList<Branches> myBranches;
public boolean addBankTransactions(String BankName, String customerName, double amount) {
if (findBank(BankName) != null) {
findBank(BankName).addNewCustomer(customerName, amount);
return true;
}
return false;
}
public boolean addBranch(String name) {
if (findBank(name) != null) {
this.myBranches.add(new Branches(name));
return true;
}
return false;
}
public boolean addNewCustomer(String bankName, String customerName, double amount) {
if (findBank(bankName) != null) {
findBank(bankName).addNewCustomer(customerName, amount);
return true;
}
return false;
}
public Branches findBank(String bankName) {
for (int i = 0; i < this.myBranches.size(); i++) {
Branches branches = this.myBranches.get(i);
if (branches.getBankName().equalsIgnoreCase(bankName)) {
return branches;
}
}
return null;
}
public boolean listCustomers(String bankName, boolean showTransactions) {
Branches branches = findBank(bankName);
if (branches != null) {
System.out.println("Customer details for branch: " + branches.getBankName());
ArrayList<Customer> branchCustomers = branches.getMyCustomer();
for (int i = 0; i < branchCustomers.size(); i++) {
System.out.println("Customer: " + branchCustomers.get(i).getName() + " { " + (i + 1) + " } ");
if (showTransactions) {
System.out.println("Transactions: ");
ArrayList<Double> transactions = branchCustomers.get(i).getTransactions();
for (int j = 0; j < transactions.size(); j++) {
System.out.println("{ " + (j + 1) + " Amount " + transactions.get(j));
}
}
}
return true;
}
return false;
}
}
|
package com.capstone.videoeffect.Adapters;
import android.app.Activity;
import android.app.Dialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.capstone.videoeffect.R;
import com.capstone.videoeffect.utils.Glob;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class CreationAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
private Activity dactivity;
private int imageSize;
ArrayList<String> imagegallary = new ArrayList();
SparseBooleanArray mSparseBooleanArray;
MediaMetadataRetriever metaRetriever;
View vi;
static class ViewHolder {
public FrameLayout frm;
ImageView imgIcon;
ViewHolder() {
}
}
public CreationAdapter(Activity dAct, ArrayList<String> dUrl) {
this.dactivity = dAct;
this.imagegallary = dUrl;
inflater = (LayoutInflater) this.dactivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mSparseBooleanArray = new SparseBooleanArray(this.imagegallary.size());
}
public int getCount() {
return this.imagegallary.size();
}
public Object getItem(int position) {
return Integer.valueOf(position);
}
public long getItemId(int position) {
return (long) position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View row = convertView;
int width = this.dactivity.getResources().getDisplayMetrics().widthPixels;
if (row == null) {
row = LayoutInflater.from(this.dactivity).inflate(R.layout.list_gallary, parent, false);
holder = new ViewHolder();
holder.frm = (FrameLayout) row.findViewById(R.id.frm);
holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
holder.imgIcon.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
final Dialog dialog = new Dialog(CreationAdapter.this.dactivity);
DisplayMetrics metrics = new DisplayMetrics();
CreationAdapter.this.dactivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = (int) (((double) metrics.heightPixels) * 1.0d);
int width = (int) (((double) metrics.widthPixels) * 1.0d);
dialog.requestWindowFeature(1);
dialog.getWindow().setFlags(1024, 1024);
dialog.setContentView(R.layout.layout_fullscreen_image);
dialog.getWindow().setLayout(width, height);
dialog.setCanceledOnTouchOutside(true);
ImageView imgDelete = (ImageView) dialog.findViewById(R.id.imgDelete);
ImageView imgShare = (ImageView) dialog.findViewById(R.id.imgShare);
ImageView imgSetAs = (ImageView) dialog.findViewById(R.id.imgSetAs);
((ImageView) dialog.findViewById(R.id.imgDisplay)).setImageURI(Uri.parse((String) Glob.IMAGEALLARY.get(position)));
imgShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// dialog.dismiss();
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType("image/*");
sharingIntent.putExtra("android.intent.extra.TEXT", Glob.app_name + " Create By : " + Glob.app_link+dactivity.getPackageName());
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(new File((String) CreationAdapter.this.imagegallary.get(position))));
dactivity.startActivity(Intent.createChooser(sharingIntent, "Share Image using"));
}
});
imgSetAs.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CreationAdapter.this.setWallpaper("Diversity", (String) CreationAdapter.this.imagegallary.get(position));
dialog.dismiss();
}
});
imgDelete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Dialog dial = new Dialog(CreationAdapter.this.dactivity);
dial.requestWindowFeature(1);
dial.setContentView(R.layout.delete_confirmation);
dial.getWindow().setBackgroundDrawable(new ColorDrawable(0));
dial.setCanceledOnTouchOutside(true);
((TextView) dial.findViewById(R.id.delete_yes)).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
File fD = new File((String)CreationAdapter.this.imagegallary.get(position));
if (fD.exists()) {
fD.delete();
}
CreationAdapter.this.imagegallary.remove(position);
CreationAdapter.this.dactivity.sendBroadcast(new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", Uri.fromFile(new File(String.valueOf(fD)))));
CreationAdapter.this.notifyDataSetChanged();
if (CreationAdapter.this.imagegallary.size() == 0) {
Toast.makeText(CreationAdapter.this.dactivity, "No Image Found..", Toast.LENGTH_SHORT).show();
}
dial.dismiss();
dialog.dismiss();
}
});
((TextView) dial.findViewById(R.id.delete_no)).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
dial.dismiss();
}
});
dial.show();
}
});
dialog.show();
}
});
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Glide.with(this.dactivity).load((String) this.imagegallary.get(position)).into(holder.imgIcon);
System.gc();
return row;
}
private void setWallpaper(String diversity, String s) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this.dactivity);
DisplayMetrics metrics = new DisplayMetrics();
this.dactivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
try {
Options options = new Options();
options.inPreferredConfig = Config.ARGB_8888;
wallpaperManager.setBitmap(BitmapFactory.decodeFile(s, options));
wallpaperManager.suggestDesiredDimensions(width / 2, height / 2);
Toast.makeText(this.dactivity, "Wallpaper Set", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.chinasoft.education_manage.service.impl;
import com.chinasoft.education_manage.dao.ClassDao;
import com.chinasoft.education_manage.dao.StudentDao;
import com.chinasoft.education_manage.dao.impl.ClassDaoImpl;
import com.chinasoft.education_manage.dao.impl.StudentDaoImpl;
import com.chinasoft.education_manage.domain.Class;
import com.chinasoft.education_manage.domain.Student;
import com.chinasoft.education_manage.domain.StudentPage;
import com.chinasoft.education_manage.service.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
StudentDao studentDao = new StudentDaoImpl();
@Override
public void addStudent(Student student) {
studentDao.addStudent(student);
}
@Override
public StudentPage findStudentMessage(String pageNum, String rowsNum, String search) {
int rows = Integer.parseInt(rowsNum);
int pageNums = Integer.parseInt(pageNum);
if (pageNums < 1){
pageNums = 1;
}
int totalCount = studentDao.findAllStudentTotal(search);
int totalPage = (totalCount%rows) == 0 ? (totalCount/rows):(totalCount/rows)+1;
int start = (pageNums - 1)*rows;
List<Student> list = studentDao.findAllStudent(start,rows,search);
StudentPage<Student> studentPage = new StudentPage<>(totalCount, totalPage, list, pageNums, rows);
return studentPage;
}
@Override
public Student echoStudnet(int sno) {
return studentDao.echoStudent(sno);
}
@Override
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}
@Override
public void deleteStudent(int sno) {
studentDao.deleteStudent(sno);
}
@Override
public List<Class> echoClass() {
List<Class> list = studentDao.stuFindClass();
return list;
}
}
|
package br.ufs.dcomp.chatrabbitmq;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.GregorianCalendar;
import javax.activation.MimeType;
import org.json.JSONObject;
import com.google.protobuf.ByteString;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import br.ufs.dcomp.chatrabbitmq.MensagemProto.Mensagem;
import br.ufs.dcomp.chatrabbitmq.MensagemProto.Mensagem.Conteudo;
import br.ufs.dcomp.utils.FileUtils;
import br.ufs.dcomp.utils.VariaveisGlobais;
public class Emissor implements IRabbitObject{
private static GregorianCalendar calendario = new GregorianCalendar();
private static String getDate() {
String date = Integer.toString(calendario.get(GregorianCalendar.DAY_OF_MONTH)) + "/" +
Integer.toString(calendario.get(GregorianCalendar.MONTH)) + "/" +
Integer.toString(calendario.get(GregorianCalendar.YEAR));
return date;
}
private static String getTime() {
String time = Integer.toString(calendario.get(GregorianCalendar.HOUR_OF_DAY)) + ":" +
Integer.toString(calendario.get(GregorianCalendar.MINUTE));
return time;
}
private static Mensagem formatMsg(String message, String user, String group) {
MensagemProto.Mensagem mensagem = MensagemProto.Mensagem.newBuilder()
.setSender(user)
.setDate(getDate())
.setTime(getTime())
.setGroup(group)
.setContent(
Conteudo.newBuilder()
.setType(FileUtils.TYPE_NONE)
.setBody(ByteString.copyFrom(message, StandardCharsets.UTF_8))
.build())
.build();
return mensagem;
}
private static Mensagem formatMsgFile(String path, String user, String group) throws IOException{
MensagemProto.Mensagem mensagem = MensagemProto.Mensagem.newBuilder()
.setSender(user)
.setDate(getDate())
.setTime(getTime())
.setGroup(group)
.setContent(
Conteudo.newBuilder()
.setType(FileUtils.TYPE_TEXT)
.setName(path)
.setBody(ByteString.copyFrom(FileUtils.read(path)))
.build())
.build();
return mensagem;
}
public static void sendToUser(Channel channel, String sender, String destination, String message) throws UnsupportedEncodingException, IOException {
Mensagem msg = formatMsg(message, sender, "");
channel.basicPublish("", destination, null, msg.toByteArray());
}
public static void sendToGroup(Channel channel, String sender, String group, String message) throws UnsupportedEncodingException, IOException {
Mensagem msg = formatMsg(message, sender, group + "/");
channel.basicPublish(group, "", null, msg.toByteArray());
}
public static void sendFileToUser(final Channel channel, final String sender, final String destination, final String path) throws UnsupportedEncodingException, IOException {
Thread t1 = new Thread(new Runnable() {
public void run()
{
try {
Mensagem msg = formatMsgFile(path, sender, "");
channel.basicPublish("", destination, null, msg.toByteArray());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Ocorreu um erro no envio do arquivo " + path + " para " + destination);
}
}});
t1.start();
}
public static void sendFileToGroup(final Channel channel, final String sender, final String group, final String path) throws UnsupportedEncodingException, IOException {
Thread t1 = new Thread(new Runnable() {
public void run()
{
try {
Mensagem msg = formatMsgFile(path, sender, group + "/");
if (msg != null) {
channel.basicPublish(group + VariaveisGlobais.fileQueuSufix, "", null, msg.toByteArray());
System.out.println("File " + path + " is now available to " + sender + "!\n");
}
else
System.err.println("Não foi possivel carregar o arquivo");
} catch (IOException e) {
System.err.println("Ocorreu um erro no envio do arquivo " + path + " para " + group);
}
}});
t1.start();
}
}
|
package Controllers;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.json.simple.JSONArray;
import server.Main;
import javax.annotation.PostConstruct;
import javax.print.attribute.standard.Media;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@Path("/song/")
public class Songs {
@POST
@Path("UserID={UserID}/SongID={SongID}/save") //API path /song/UserID= /SongID= /save
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String saveSong(@PathParam("UserID") Integer UserID, @FormDataParam("SongName") String SongName, @FormDataParam("SongContents") String SongContents, @PathParam("SongID") Integer SongID) { //Fields required for SQL statements
try {
if (SongID == 0 || UserID == 0 || SongName == null || SongContents == null) { //Checks if any of the fields are missing/null
throw new Exception("One or more form data parameters are missing in the HTTP request"); //if it is returns this error message
}
PreparedStatement ps = Main.db.prepareStatement("UPDATE Songs SET UserID = ?, SongName = ?, SongContents = ? WHERE SongID = ?"); //SQL statement
ps.setInt(1, UserID);
ps.setString(2, SongName);
ps.setString(3, SongContents);
ps.setInt(4, SongID);
ps.executeUpdate();
return "{\"Status\": \"OK\"}";
} catch (Exception exception) {
System.out.println("Database error: " + exception.getMessage());
return "{\"Error\": \"Unable to Update song\"}";
}
}
@POST
@Path("UserID={UserID}/newSong")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String newSong(@PathParam("UserID") Integer UserID, @FormDataParam("SongName") String SongName, @FormDataParam("SongContents") String SongContents) { //Fields required for SQL statements
try {
if (UserID == 0 || SongName == null || SongContents == null) {
throw new Exception("One or more form data parameters are missing in the HTTP request");
}
PreparedStatement ps = Main.db.prepareStatement("INSERT INTO Songs (UserID, SongName, SongContents) VALUES ( ?, ?, ?)");
ps.setInt(1, UserID);
ps.setString(2, SongName);
ps.setString(3, SongContents);
ps.execute();
return "{\"Status\": \"OK\"}";
} catch (Exception exception) {
System.out.println("Database error:" + exception.getMessage());
return "{\"Error\": \"Unable to Save song\"}";
}
}
public static void saveSong(Integer SongID, Integer UserID, String SongName, String SongContents) {
try {
PreparedStatement ps = Main.db.prepareStatement("UPDATE Songs SET UserID = ?, SongName = ?, SongContents = ? WHERE SongID = ?");
ps.setInt(1, UserID);
ps.setString(2, SongName);
ps.setString(3, SongContents);
ps.setInt(4, SongID);
ps.executeUpdate();
System.out.println("Update successful");
} catch (Exception exception){
System.out.println("Database error:"+ exception.getMessage());
}
}
public static void deleteSong(Integer SongID) {
try {
PreparedStatement ps = Main.db.prepareStatement("DELETE FROM Songs WHERE SongID = ?");
ps.setInt(1, SongID);
ps.execute();
System.out.println("Deletion successful");
} catch (Exception exception) {
System.out.println("Database error:" + exception.getMessage());
}
}
public static void createSong() {
try {
PreparedStatement ps = Main.db.prepareStatement("INSERT INTO Songs (UserID, SongName, SongContents) VALUES ( ?, ?, ?)");
ps.setInt(1, 2);
ps.setString(2, "Wood Tables");
ps.setString(3, "35840483058");
ps.executeUpdate();
} catch (Exception exception) {
System.out.println("Database error:" + exception.getMessage());
}
}
public static void renameSong() {
try {
PreparedStatement ps = Main.db.prepareStatement("UPDATE Songs SET SongName = ? WHERE (SongID = 3)");
ps.setString(1, "Spinning");
ps.executeUpdate();
System.out.println("Song successfully renamed");
} catch (Exception exception) {
System.out.println("Database error:" + exception.getMessage());
}
}
public static void listSongs() {
try {
PreparedStatement ps = Main.db.prepareStatement("SELECT SongID, UserID, SongName, SongContents FROM Songs");
ResultSet results = ps.executeQuery();
while (results.next()) {
int SongID = results.getInt(1);
int UserID = results.getInt(2);
String SongName = results.getString(3);
String SongContents = results.getString(4);
System.out.println(SongID + " " + UserID + " " + SongName + " " + SongContents);
}
} catch (Exception exception) {
System.out.println("Database error:" + exception.getMessage());
}
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.datetime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.springframework.format.Formatter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* A formatter for {@link java.util.Date} types.
* <p>Supports the configuration of an explicit date time pattern, timezone,
* locale, and fallback date time patterns for lenient parsing.
*
* @author Keith Donald
* @author Juergen Hoeller
* @author Phillip Webb
* @author Sam Brannen
* @since 3.0
* @see SimpleDateFormat
*/
public class DateFormatter implements Formatter<Date> {
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
// We use an EnumMap instead of Map.of(...) since the former provides better performance.
private static final Map<ISO, String> ISO_PATTERNS;
static {
Map<ISO, String> formats = new EnumMap<>(ISO.class);
formats.put(ISO.DATE, "yyyy-MM-dd");
formats.put(ISO.TIME, "HH:mm:ss.SSSXXX");
formats.put(ISO.DATE_TIME, "yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
ISO_PATTERNS = Collections.unmodifiableMap(formats);
}
@Nullable
private Object source;
@Nullable
private String pattern;
@Nullable
private String[] fallbackPatterns;
private int style = DateFormat.DEFAULT;
@Nullable
private String stylePattern;
@Nullable
private ISO iso;
@Nullable
private TimeZone timeZone;
private boolean lenient = false;
/**
* Create a new default {@code DateFormatter}.
*/
public DateFormatter() {
}
/**
* Create a new {@code DateFormatter} for the given date time pattern.
*/
public DateFormatter(String pattern) {
this.pattern = pattern;
}
/**
* Set the source of the configuration for this {@code DateFormatter} —
* for example, an instance of the {@link DateTimeFormat @DateTimeFormat}
* annotation if such an annotation was used to configure this {@code DateFormatter}.
* <p>The supplied source object will only be used for descriptive purposes
* by invoking its {@code toString()} method — for example, when
* generating an exception message to provide further context.
* @param source the source of the configuration
* @since 5.3.5
*/
public void setSource(Object source) {
this.source = source;
}
/**
* Set the pattern to use to format date values.
* <p>If not specified, DateFormat's default style will be used.
*/
public void setPattern(String pattern) {
this.pattern = pattern;
}
/**
* Set additional patterns to use as a fallback in case parsing fails for the
* configured {@linkplain #setPattern pattern}, {@linkplain #setIso ISO format},
* {@linkplain #setStyle style}, or {@linkplain #setStylePattern style pattern}.
* @param fallbackPatterns the fallback parsing patterns
* @since 5.3.5
* @see DateTimeFormat#fallbackPatterns()
*/
public void setFallbackPatterns(String... fallbackPatterns) {
this.fallbackPatterns = fallbackPatterns;
}
/**
* Set the ISO format to use to format date values.
* @param iso the {@link ISO} format
* @since 3.2
*/
public void setIso(ISO iso) {
this.iso = iso;
}
/**
* Set the {@link DateFormat} style to use to format date values.
* <p>If not specified, DateFormat's default style will be used.
* @see DateFormat#DEFAULT
* @see DateFormat#SHORT
* @see DateFormat#MEDIUM
* @see DateFormat#LONG
* @see DateFormat#FULL
*/
public void setStyle(int style) {
this.style = style;
}
/**
* Set the two characters to use to format date values.
* <p>The first character is used for the date style; the second is used for
* the time style.
* <p>Supported characters:
* <ul>
* <li>'S' = Small</li>
* <li>'M' = Medium</li>
* <li>'L' = Long</li>
* <li>'F' = Full</li>
* <li>'-' = Omitted</li>
* </ul>
* This method mimics the styles supported by Joda-Time.
* @param stylePattern two characters from the set {"S", "M", "L", "F", "-"}
* @since 3.2
*/
public void setStylePattern(String stylePattern) {
this.stylePattern = stylePattern;
}
/**
* Set the {@link TimeZone} to normalize the date values into, if any.
*/
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
/**
* Specify whether parsing is to be lenient. Default is {@code false}.
* <p>With lenient parsing, the parser may allow inputs that do not precisely match the format.
* With strict parsing, inputs must match the format exactly.
*/
public void setLenient(boolean lenient) {
this.lenient = lenient;
}
@Override
public String print(Date date, Locale locale) {
return getDateFormat(locale).format(date);
}
@Override
public Date parse(String text, Locale locale) throws ParseException {
try {
return getDateFormat(locale).parse(text);
}
catch (ParseException ex) {
if (!ObjectUtils.isEmpty(this.fallbackPatterns)) {
for (String pattern : this.fallbackPatterns) {
try {
DateFormat dateFormat = configureDateFormat(new SimpleDateFormat(pattern, locale));
// Align timezone for parsing format with printing format if ISO is set.
if (this.iso != null && this.iso != ISO.NONE) {
dateFormat.setTimeZone(UTC);
}
return dateFormat.parse(text);
}
catch (ParseException ignoredException) {
// Ignore fallback parsing exceptions since the exception thrown below
// will include information from the "source" if available -- for example,
// the toString() of a @DateTimeFormat annotation.
}
}
}
if (this.source != null) {
ParseException parseException = new ParseException(
String.format("Unable to parse date time value \"%s\" using configuration from %s", text, this.source),
ex.getErrorOffset());
parseException.initCause(ex);
throw parseException;
}
// else rethrow original exception
throw ex;
}
}
protected DateFormat getDateFormat(Locale locale) {
return configureDateFormat(createDateFormat(locale));
}
private DateFormat configureDateFormat(DateFormat dateFormat) {
if (this.timeZone != null) {
dateFormat.setTimeZone(this.timeZone);
}
dateFormat.setLenient(this.lenient);
return dateFormat;
}
private DateFormat createDateFormat(Locale locale) {
if (StringUtils.hasLength(this.pattern)) {
return new SimpleDateFormat(this.pattern, locale);
}
if (this.iso != null && this.iso != ISO.NONE) {
String pattern = ISO_PATTERNS.get(this.iso);
if (pattern == null) {
throw new IllegalStateException("Unsupported ISO format " + this.iso);
}
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setTimeZone(UTC);
return format;
}
if (StringUtils.hasLength(this.stylePattern)) {
int dateStyle = getStylePatternForChar(0);
int timeStyle = getStylePatternForChar(1);
if (dateStyle != -1 && timeStyle != -1) {
return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
}
if (dateStyle != -1) {
return DateFormat.getDateInstance(dateStyle, locale);
}
if (timeStyle != -1) {
return DateFormat.getTimeInstance(timeStyle, locale);
}
throw new IllegalStateException("Unsupported style pattern '" + this.stylePattern + "'");
}
return DateFormat.getDateInstance(this.style, locale);
}
private int getStylePatternForChar(int index) {
if (this.stylePattern != null && this.stylePattern.length() > index) {
switch (this.stylePattern.charAt(index)) {
case 'S': return DateFormat.SHORT;
case 'M': return DateFormat.MEDIUM;
case 'L': return DateFormat.LONG;
case 'F': return DateFormat.FULL;
case '-': return -1;
}
}
throw new IllegalStateException("Unsupported style pattern '" + this.stylePattern + "'");
}
}
|
package Question1_25;
import Test.ListNode;
public class _19_RemoveNthNode {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = head;
ListNode second = head;
ListNode last = head;
if( n <= 0) {
return null;
}
while( n > 1) {
n--;
last = last.next;
}
while(last.next != null) {
last = last.next;
first = second;
second = second.next;
}
if(second == head) {
head = head.next;
}else {
first.next = second.next;
}
return head;
}
}
|
package com.fm.scheduling.domain;
import java.time.LocalDateTime;
public class BaseRecord<E> {
private LocalDateTime createDate;
private String createdBy;
private LocalDateTime lastUpdate;
private String lastUpdateBy;
public LocalDateTime getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDateTime createDate) {
this.createDate = createDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getLastUpdateBy() {
return lastUpdateBy;
}
public void setLastUpdateBy(String lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy;
}
public static <E> E createInstance(Class clazz) {
E e = null;
try {
e = (E) clazz.newInstance();
} catch(Exception ex) {
ex.printStackTrace();
}
return e;
}
}
|
package example.com.db.nimbuzz_banbot_android_by_db;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class HomeFragment extends Fragment {
private TextView botjid;
private Button LogoutBtn;
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
botjid = (TextView) view.findViewById(R.id.textView6);
botjid.setText(XMPPLogic.connection.getUser());
LogoutBtn = (Button) view.findViewById(R.id.logoutbtn);
LogoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
XMPPLogic.connection.disconnect();
if (!XMPPLogic.connection.isConnected()) {
//finish();
// Return Back To MainActivity
Intent dbint2 = new Intent(getActivity(), MainActivity.class);
dbint2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(dbint2);
}
}
});
return view;
}
}
|
package cn.jbit.epet.entity;
import java.util.Date;
/**
* 宠物实体类。
*/
public class Pet {
private int id;// 宠物id
private int masterId;// 主人id
private String name;// 昵称
private int typeId;// 类型id
private int health;// 健康值
private int love;// 亲密度
private Date adoptTime;// 领养时间
private String status;// 状态
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMasterId() {
return masterId;
}
public void setMasterId(int masterId) {
this.masterId = masterId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getLove() {
return love;
}
public void setLove(int love) {
this.love = love;
}
public Date getAdoptTime() {
return adoptTime;
}
public void setAdoptTime(Date adoptTime) {
this.adoptTime = adoptTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package com.company;
import com.company.services.impl.UserTypeSelectingService;
import com.company.services.impl.FilmInventoryService;
import com.company.services.impl.FilmRentalService;
import com.company.storage.FilmStore;
public class Main {
public static void main(String[] args) {
UserTypeSelectingService userTypeSelectingService = new UserTypeSelectingService();
FilmInventoryService filmInventoryService = new FilmInventoryService();
FilmRentalService filmRentalService = new FilmRentalService();
FilmStore filmStore = new FilmStore();
filmStore.initFilms();
int userType = 0;
while (true){
userType = userTypeSelectingService.selectUser();
if(userType == 1){
filmInventoryService.selectAction();
break;
} else if(userType == 2) {
filmRentalService.selectAction();
break;
} else {
continue;
}
}
}
}
|
package se.mah.m11p0121.iotproject;
class Constants {
static final String MQTT_BROKER_URL = "tcp://m23.cloudmqtt.com:10999";
static final String PUBLISH_TOPIC = "LED";
static final String CLIENT_ID = "IOTP";
}
|
package org.squonk.core;
/** Interface that defined an executable service. From an instance of this class you can obtain a @{link ServiceConfig} instance
* that defines the properties that are needed by a client of this service.
* Implementations of this interface define the details of how the service is to be executed.
*
*
* Created by timbo on 04/01/17.
*/
public interface ServiceDescriptor {
String getId();
/** The descriptor that defines the client side properties of the service
*
* @return
*/
ServiceConfig getServiceConfig();
}
|
package duke.command;
import duke.ImageType;
import duke.TaskList;
import duke.Ui;
import duke.exception.NonExistentTaskException;
/**
* Represents a PriorityLevelCommand.
*/
public class PriorityLevelCommand extends Command {
/**
* Number on the list of the task to be updated.
*/
protected int taskNum;
/**
* Creates a PriorityLevelCommand object.
* @param taskNum Number on the list of the task.
*/
public PriorityLevelCommand(int taskNum) {
super(CommandType.PRIORITYLEVEL, ImageType.PENDING);
this.taskNum = taskNum;
}
/**
* Executes a priority level command.
* @param ui Ui associated with the command.
* @param taskList Task list associated with the command.
* @return Prommpt for user to enter the priority level.
* @throws NonExistentTaskException For when the task number does not correspond to a task on the list.
*/
@Override
public String execute(Ui ui, TaskList taskList) throws NonExistentTaskException {
if (taskNum == 0 || taskNum > taskList.getTaskListSize()) {
throw new NonExistentTaskException();
}
return ui.printPrompt("What Level do you want to set it as?\n"
+ " - High\n"
+ " - Medium\n"
+ " - Low\n");
}
public int getTaskNum() {
return taskNum;
}
}
|
package com.daydvr.store.util;
import android.os.Handler;
import android.os.Message;
/**
* @author LoSyc
* @version Created on 2017/12/28. 11:05
*/
public class LoaderHandler extends Handler {
private LoaderHandlerListener mListener;
public Message createMessage(int what, int arg1, int arg2, Object obj) {
Message msg = Message.obtain();
msg.what = what;
if (obj != null) {
msg.obj = obj;
}
msg.arg1 = arg1;
msg.arg2 = arg2;
return msg;
}
@Override
public void handleMessage(Message msg) {
if (mListener != null) {
mListener.handleMessage(msg);
}
}
public interface LoaderHandlerListener {
void handleMessage(Message msg);
}
public void setListener(LoaderHandlerListener listener) {
mListener = listener;
}
}
|
package com.designpattern.dp1simplefactory.v2;
/**
* 优点:由课程工厂创建课程,把具体对象的创建细节隐藏起来
* 缺点:如果继续扩展,要增加前端课程,那么工厂CourseFactory中的create()方法就要
* 每次都根据产品的增加修改代码逻辑,不符合开闭原则。
*/
public class Test {
public static void main(String[] args) {
CourseFactory.createCourse("java").record();
CourseFactory.createCourse("python").record();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.