text
stringlengths
10
2.72M
/** * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.controller.model.manager; import java.io.Serializable; /** * @ClassName: DutyInfo * @Description: 管理中心 职务 * @author 高振 * @date 2016年3月27日 下午4:52:52 * */ public class DutyInfo implements Serializable { private static final long serialVersionUID = 2615488053231958057L; /** * 编码 */ private Long dutyId; /** * 名称 */ private String dutyName; /** * 级别 */ private String rankNo; /** * 是否删除 */ private Byte beDeleted; public Long getDutyId() { return dutyId; } public void setDutyId(Long dutyId) { this.dutyId = dutyId; } public String getDutyName() { return dutyName; } public void setDutyName(String dutyName) { this.dutyName = dutyName; } public String getRankNo() { return rankNo; } public void setRankNo(String rankNo) { this.rankNo = rankNo; } public Byte getBeDeleted() { return beDeleted; } public void setBeDeleted(Byte beDeleted) { this.beDeleted = beDeleted; } @Override public String toString() { return "DutyInfo [dutyId=" + dutyId + ", dutyName=" + dutyName + ", rankNo=" + rankNo + ", beDeleted=" + beDeleted + "]"; } }
package com.cz.android.sample; import com.cz.android.datastructure.sparse.SparseIntArray; import org.junit.Test; public class BinarySearchTest { @Test public void tableColumnIndexerTest(){ DynamicTableIndexer tableIndexer=new DynamicTableIndexer(); for(int i=0;i<7;i++){ tableIndexer.addTableColumnFromEnd(i,300); } System.out.println(tableIndexer.findTableCellColumn(5)); System.out.println(tableIndexer.findTableCellColumn(833)); //Fetch table column from location; System.out.println(tableIndexer.getTableCellOffsetX(0)); System.out.println(tableIndexer.getTableCellOffsetX(1)); System.out.println(tableIndexer.findTableCellColumn(1805)); // //Test the table column // System.out.println("start:"+tableIndexer.getStartTableColumn()+" end:"+tableIndexer.getEndTableColumn()); // tableIndexer.removeTableColumn(0,1); // System.out.println("start:"+tableIndexer.getStartTableColumn()+" end:"+tableIndexer.getEndTableColumn()); // // int endTableColumn = tableIndexer.getEndTableColumn(); // tableIndexer.addTableColumnFromEnd(endTableColumn+1,400); // System.out.println(tableIndexer.tableColumnExist(1)); // System.out.println(tableIndexer.tableColumnExist(2)); } @Test public void tableRowIndexerTest(){ DynamicTableIndexer tableIndexer=new DynamicTableIndexer(); for(int i=0;i<20;i++){ tableIndexer.addTableRow(i,300); } System.out.println(tableIndexer.findTableCellColumn(5)); System.out.println(tableIndexer.findTableCellColumn(833)); //Fetch table column from location; System.out.println(tableIndexer.getTableCellOffsetX(0)); System.out.println(tableIndexer.getTableCellOffsetX(1)); System.out.println(tableIndexer.findTableCellColumn(1805)); } @Test public void binarySearchTest(){ SparseIntArray tableArray=new SparseIntArray(); int[] array=new int[]{300,1600,900,1200}; for(int i=0;i<array.length;i++){ tableArray.append(i,array[i]); } int i = binarySearchStartIndex(tableArray, 306)+1; int key = tableArray.keyAt(i); System.out.println("i:"+key+" v:"+tableArray.get(key)); System.out.println(binarySearchStartIndex(tableArray, 5)); System.out.println(binarySearchStartIndex(tableArray, 1205)); } private int binarySearchStartIndex(SparseIntArray array, float value){ int start = 0; int result = -1; int end = array.size() - 1; while (start <= end) { int middle = (start + end) / 2; int key = array.keyAt(middle); int middleValue = array.get(key); if (value == middleValue) { result = middle; break; } else if (value < middleValue) { end = middle - 1; } else { start = middle + 1; } } if (-1 == result) { result = start-1; } return result; } }
package net.minecraft.item; import net.minecraft.entity.EntityLivingBase; import net.minecraft.world.World; public interface IItemPropertyGetter { float apply(ItemStack paramItemStack, World paramWorld, EntityLivingBase paramEntityLivingBase); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\IItemPropertyGetter.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package emmet.warehousing.operation.repository; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RestResource; import emmet.core.data.entity.StorageSpace; @RestResource(exported = true) public interface StorageSpaceRepository extends PagingAndSortingRepository<StorageSpace, String> { @Query("select max(s.id) from StorageSpace s where s.warehouse.id = :warehouseId ") String findLastId(@Param("warehouseId") String warehouseId); List<StorageSpace> findByNameAndWarehouseId(String name,String id); }
package com.sanjaychawla.android.sensorapplication.helper; import android.location.Location; import android.util.Log; import com.sanjaychawla.android.sensorapplication.data.Record; import com.sanjaychawla.android.sensorapplication.writer.CSVRecorder; import com.sanjaychawla.android.sensorapplication.writer.FirebaseDBRecorder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class InternetSpeedHelper { public static final String TAG = InternetSpeedHelper.class.getSimpleName(); // bandwidth in kbps static private int POOR_BANDWIDTH = 150; private int AVERAGE_BANDWIDTH = 550; private int GOOD_BANDWIDTH = 2000; static OkHttpClient client = new OkHttpClient(); static Request request = new Request.Builder() .url("https://b.zmtcdn.com/data/user_profile_pictures/3be/8d1eff0f14f4c5e2d4de16f08151e3be.jpg?fit=around%7C400%3A400&crop=400%3A400%3B%2A%2C%2A") .build(); public static double calculateSpeed(Record record, String filepath){ Log.d(TAG, "inside speed calculator"); CustomImageCallback cb = new CustomImageCallback(record, filepath); client.newCall(request).enqueue(cb); return cb.speed; } private static class CustomImageCallback implements Callback { long endTime; long fileSize; double speed; long startTime; String filepath; Record record; public CustomImageCallback(Record record, String filepath) { startTime = System.currentTimeMillis(); this.record = record; this.filepath = filepath; } @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Error in HTTP call: " + e.getMessage()); record.setNetworkSpeed(speed); record.setTimestamp(getCurrentTime()); CSVRecorder.write(filepath, record); FirebaseDBRecorder.write(record); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); InputStream input = response.body().byteStream(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (input.read(buffer) != -1) { bos.write(buffer); } byte[] docBuffer = bos.toByteArray(); fileSize = bos.size(); } finally { input.close(); } endTime = System.currentTimeMillis(); double timeTakenMills = Math.floor(endTime - startTime); // time taken in milliseconds speed = fileSize / timeTakenMills; record.setNetworkSpeed(speed); record.setTimestamp(getCurrentTime()); CSVRecorder.write(filepath, record); FirebaseDBRecorder.write(record); } private static String getCurrentTime() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); } } }
package tfg.example.org.materialdesign; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteTransactionListener; import java.util.ArrayList; import java.util.List; /** * Created by Iván on 25/04/2018. */ public class DBHandler extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "favmoviestable"; // Contacts table name private static final String TABLE_MOVIES = "movies"; // Shops Table Columns names private static final String KEY_ID = "id"; private static final String KEY_MOVIE_ID = "movie_id"; private static final String KEY_NAME = "movie_name"; public DBHandler(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE = "CREATE TABLE " + TABLE_MOVIES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_MOVIE_ID + " TEXT, " + KEY_NAME + " TEXT"+")"; db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES); // Creating tables again onCreate(db); } // Adding new shop public void addMovie(FavMoviesDB movie) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, movie.getMovie_name()); values.put(KEY_MOVIE_ID, movie.getMovie_id()); // Inserting Row db.insert(TABLE_MOVIES, null, values); db.close(); // Closing database connection } // Getting one movie public FavMoviesDB getMovie(int id) { FavMoviesDB movie; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_MOVIES, new String[] { KEY_ID, KEY_MOVIE_ID, KEY_NAME}, KEY_MOVIE_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } try { movie = new FavMoviesDB(Integer.parseInt(cursor.getString(0)), Integer.parseInt(cursor.getString(1)), cursor.getString(2)); } catch(Exception e) { return null; } return movie; } // Getting All Shops public List<FavMoviesDB> getAllFavMovies() { List<FavMoviesDB> shopList = new ArrayList<FavMoviesDB>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_MOVIES; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { FavMoviesDB shop = new FavMoviesDB(0, 0, null); shop.setId(Integer.parseInt(cursor.getString(0))); shop.setMovie_id(Integer.parseInt(cursor.getString(1))); shop.setMovie_name(cursor.getString(2)); // Adding contact to list shopList.add(shop); } while ( cursor.moveToNext()); } // return contact list return shopList; } // Getting shops Count public int getMoviesCount() { String countQuery = "SELECT * FROM " + TABLE_MOVIES; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); cursor.close(); // return count return cursor.getCount(); } // Updating a shop public int updateMovie(FavMoviesDB movie) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_MOVIE_ID, movie.getMovie_id()); values.put(KEY_NAME, movie.getMovie_name()); // updating row return db.update(TABLE_MOVIES, values, KEY_ID + " = ?", new String[]{String.valueOf(movie.getId())}); } // Deleting a shop public void deleteMovies(FavMoviesDB movie) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_MOVIES, KEY_ID + " = ?", new String[] { String.valueOf(movie.getId()) }); db.close(); } }
package it.unive.interfaces; /** * Metodi che Permanent DEVE offrire * */ public interface Permanent { /** * ritorna il Player che possiede il permanent * @return */ public Player getOwner(); /** * setta il possessore del permanent * @param owner */ public void setOwner(Player owner); /** * ritorna il nome del permanent * @return */ public String getName(); /** * avvisa l'observer della distruzione del permanente */ public void destroy(); /*distrugge il permanent avvisando l'observer */ /** * ritorna la Stringa contenente le info del permanente * @return */ @Override public String toString(); }
package ir.ssatari.springcommons.model.response; import ir.ssatari.springcommons.util.enums.MessageType; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.List; /** * The message object that could be sent to the caller of a REST API * * @author Saeed */ @NoArgsConstructor @Getter @Setter public class ResponseMessage { /** * Actual message that would be sent to in response */ private String text; /** * Unique code of the message representing the exact scenario that happened. It could to find the exact point in * service provider's codebase which generated this message or causes the error condition to happen. */ private String code; /** * An optional arguments that may be used to send complementary information to the caller. This could be used for * implementing user interface messages in web (which messages are generated in client side base on user's language * and the message sent from server is ignored) */ private List arguments; /** * The type of the message. Messages could be informative, warning or error */ private MessageType type; /** * Creates a new instance using given text. The type of the message would be initialized to the default value of * {@link MessageType#INFO} * * @param text Text of the message */ public ResponseMessage(String text) { this.text = text; this.type = MessageType.INFO; } /** * Creates a new instance using all given parameter. * * @param text Text of the message * @param code Code of the message * @param arguments List of arguments for the message * @param type Type of the message that included {info,warning,error} */ public ResponseMessage(String text, String code, List arguments, MessageType type) { this.text = text; this.code = code; this.arguments = arguments; this.type = type; } }
package com.xiao.hadoop; /** * Created by xiaoliang * 2016/7/27 16:22 * * @Version 1.0 */ public class App { }
package com.duanxr.yith.midium; /** * @author 段然 2021/11/15 */ public class MapSumPairs { /** * Design a map that allows you to do the following: * * Maps a string key to a given value. * Returns the sum of the values that have a key with a prefix equal to a given string. * Implement the MapSum class: * * MapSum() Initializes the MapSum object. * void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one. * int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix. *   * * Example 1: * * Input * ["MapSum", "insert", "sum", "insert", "sum"] * [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] * Output * [null, null, 3, null, 5] * * Explanation * MapSum mapSum = new MapSum(); * mapSum.insert("apple", 3); * mapSum.sum("ap"); // return 3 (apple = 3) * mapSum.insert("app", 2); * mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5) *   * * Constraints: * * 1 <= key.length, prefix.length <= 50 * key and prefix consist of only lowercase English letters. * 1 <= val <= 1000 * At most 50 calls will be made to insert and sum. * * 实现一个 MapSum 类,支持两个方法,insert 和 sum: * * MapSum() 初始化 MapSum 对象 * void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。 * int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。 *   * * 示例: * * 输入: * ["MapSum", "insert", "sum", "insert", "sum"] * [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] * 输出: * [null, null, 3, null, 5] * * 解释: * MapSum mapSum = new MapSum(); * mapSum.insert("apple", 3); * mapSum.sum("ap"); // return 3 (apple = 3) * mapSum.insert("app", 2); * mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5) *   * * 提示: * * 1 <= key.length, prefix.length <= 50 * key 和 prefix 仅由小写英文字母组成 * 1 <= val <= 1000 * 最多调用 50 次 insert 和 sum * */ class MapSum { Node root; public MapSum() { root = new Node(); } public void insert(String key, int val) { insert(root, 0, key, val); } private int insert(Node root, int i, String key, int val) { int ni = key.charAt(i) - 'a'; if (root.nodes[ni] == null) { root.nodes[ni] = new Node(); } if (i == key.length() - 1) { int sub = val - root.nodes[ni].val; root.nodes[ni].val = val; root.nodes[ni].sum += sub; return sub; } else { int insert = insert(root.nodes[ni], i + 1, key, val); root.nodes[ni].sum += insert; return insert; } } public int sum(String prefix) { Node node = root; for (int i = 0; i < prefix.length(); i++) { node = node.nodes[prefix.charAt(i) - 'a']; if (node == null) { return 0; } if (i == prefix.length() - 1) { return node.sum; } } return 0; } class Node { Node[] nodes = new Node[26]; int sum = 0; int val = 0; } } }
package Selinium; public class Q43oddposition { public static void main(String[] args) { int a[]={1,2,3,4,5,6}; int ans = 0 ; for(int i=1;i<a.length;i=i+2) { ans = ans + (a[i] * i); }System.out.println(ans); } }
package com.conglomerate.dev.models; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "users") @Data @Builder @NoArgsConstructor @AllArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id; String email; String passwordHash; String calendarLink; String userName; @JsonIgnore String profilePic; String authTokenHash; String googleIdToken; String googleRefreshToken; @OneToMany(mappedBy = "user") private List<Device> devices; // @ManyToMany(fetch = FetchType.LAZY) // @JoinTable(name = "user_group_mappings", // joinColumns=@JoinColumn(name="user_id"), // inverseJoinColumns=@JoinColumn(name="group_id")) // private Set<Grouping> groupingSet; }
package com.david.crossfit.model.dto.video_info; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Item { @SerializedName("id") @Expose public Id id; @SerializedName("snippet") @Expose public Snippet snippet; /** * No args constructor for use in serialization * */ public Item() { } /** * * @param id * @param snippet */ public Item(Id id, Snippet snippet) { super(); this.id = id; this.snippet = snippet; } }
package com.huatec.edu.http; import android.util.Log; import com.huatec.edu.common.Constants; import com.huatec.edu.http.entity.GoodsDetailEntity; import com.huatec.edu.http.entity.HttpResult; import com.huatec.edu.http.entity.MemberEntity; import com.huatec.edu.http.presenter.MemberPresenter; import com.huatec.edu.http.service.CategoryService; import com.huatec.edu.http.service.GoodsService; import com.huatec.edu.http.service.MemberService; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; public class HttpMethods { private static final String TAG = "HttpMethods"; private static final String BASE_URL = Constants.BASE_URL; private static final long DEFAULT_TIMBOUT = 5; private static HttpMethods sInstance; protected static GoodsService goodsService; protected static MemberService memberService; protected static CategoryService categoryService; private Retrofit retrofit; public HttpMethods(){ if (sInstance == null){ OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(DEFAULT_TIMBOUT, TimeUnit.SECONDS) .readTimeout(DEFAULT_TIMBOUT, TimeUnit.SECONDS) .writeTimeout(DEFAULT_TIMBOUT, TimeUnit.SECONDS) .build(); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(okHttpClient) .build(); goodsService = retrofit.create(GoodsService.class); memberService = retrofit.create(MemberService.class); categoryService = retrofit.create(CategoryService.class); } } public static HttpMethods getInstance(){ if (sInstance == null){ synchronized (HttpMethods.class){ if (sInstance == null){ sInstance = new HttpMethods(); } } } return sInstance; } public static class HttpResultFunc<T> implements Func1<HttpResult<T>,T>{ @Override public T call(HttpResult<T> httpResult){ Log.i(TAG,"status:"+httpResult.getStatus()); Log.i(TAG,"msg:"+httpResult.getMsg()); Log.i(TAG,"data:"+httpResult.getData()); return httpResult.getData(); } } protected static <T> void toSubscribe(Observable<T> observable, Subscriber<T> subscriber){ observable.subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); } private void httpRequest(final String username, final String password){ MemberPresenter.login2(new Subscriber<MemberEntity>(){ @Override public void onCompleted(){ } @Override public void onError(Throwable e){ Log.e("error","e:"+e.getMessage().toString()); } @Override public void onNext(MemberEntity memberEntity){ } },username,password); } }
package cn.yhd.service; import cn.yhd.base.IBaseService; import cn.yhd.entity.TbUser; import cn.yhd.entity.TbUserExample; public interface ITbUserService extends IBaseService<TbUser, TbUserExample> { }
package geeksforgeeks.mustdo.String; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by joetomjob on 5/23/19. */ public class ExtractMaximum { public static long extractMax(String s) { String s1 = "0"; long m = 0; for (int i = 0; i < s.length(); i++) { if(Character.isDigit(s.charAt(i))) { s1 += s.charAt(i); } else { if(Long.parseLong(s1) > m) { m = Long.parseLong(s1); } s1 = "0"; } } if(Long.parseLong(s1) > m) { m = Long.parseLong(s1); } return m; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int k = Integer.parseInt(br.readLine()); for (int i = 0; i < k; i++) { String s = br.readLine(); System.out.println(extractMax(s)); } } }
package io.github.surfer8137.spanishmod.block.blocks.flag.flags; import io.github.surfer8137.spanishmod.block.blocks.flag.BlockFlag; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.util.EnumFacing; /** * Created by Angel on 06/01/2018. */ public class BlockBaseFlag extends BlockFlag { private static final PropertyEnum<EnumFacing> FACING = PropertyEnum.<EnumFacing>create("facing", EnumFacing.class); public static final String FLAG_NAME = "baseflag"; public BlockBaseFlag() { super(FLAG_NAME); } }
package jang.hyun.mapper; import org.apache.ibatis.annotations.Param; import dto.jang.hs.MemberVO; public interface MemberMapper { public MemberVO read(String userid); public int findOnlyId(String userid); public void insert(MemberVO vo); public void insertAuth(@Param("userid") String userid,@Param("auth")String auth); }
package com.tt.miniapp.util; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Point; import android.os.BatteryManager; import android.os.Build; import android.os.LocaleList; import android.text.TextUtils; import android.view.Display; import android.view.Window; import android.view.WindowManager; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.util.UIUtils; import java.io.IOException; import java.lang.reflect.Method; import java.util.Locale; public class DevicesUtil { private static boolean sIsMiui; private static boolean sIsMiuiInited; private static String sMiuiVersion; private static int sStatusBarHeight; public static String version; public static String getBrand() { return Build.BRAND; } public static int getCurrentBattery(Context paramContext) { return ((BatteryManager)paramContext.getSystemService("batterymanager")).getIntProperty(4); } private static Display getDisplay(Context paramContext) { WindowManager windowManager; if (paramContext instanceof Activity) { windowManager = ((Activity)paramContext).getWindowManager(); } else { windowManager = (WindowManager)windowManager.getSystemService("window"); } return (windowManager != null) ? windowManager.getDefaultDisplay() : null; } public static float getFontSize(Context paramContext) { Configuration configuration = paramContext.getResources().getConfiguration(); float f = UIUtils.sp2px(paramContext, 12.0F); return configuration.fontScale * f; } public static String getLanguage() { Locale locale; if (Build.VERSION.SDK_INT >= 24) { locale = LocaleList.getDefault().get(0); } else { locale = Locale.getDefault(); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(locale.getLanguage()); stringBuilder.append("-"); stringBuilder.append(locale.getCountry()); return stringBuilder.toString(); } public static String getModel() { return Build.MODEL; } public static int[] getNotchSize(Context paramContext) { int[] arrayOfInt = new int[2]; arrayOfInt[0] = 0; arrayOfInt[1] = 0; try { return arrayOfInt; } catch (Exception exception) { return arrayOfInt; } finally { paramContext = null; } } public static float getPixelRadio(Context paramContext) { return (paramContext.getResources().getDisplayMetrics()).density; } public static String getPlatform() { return "Android"; } public static int getScreenHight(Context paramContext) { Display display = getDisplay(paramContext); if (display == null) return 0; try { Point point = new Point(); display.getSize(point); return point.y; } catch (Exception exception) { AppBrandLogger.e("DevicesUtil", new Object[0]); return 0; } } public static int getScreenRotation(Context paramContext) { return ((WindowManager)paramContext.getSystemService("window")).getDefaultDisplay().getRotation(); } public static int getScreenWidth(Context paramContext) { Display display = getDisplay(paramContext); if (display == null) return 0; try { Point point = new Point(); display.getSize(point); return point.x; } catch (Exception exception) { AppBrandLogger.e("DevicesUtil", new Object[0]); return 0; } } public static int getStatusBarHeight(Context paramContext) { int i = sStatusBarHeight; if (i > 0) return i; if (ConcaveScreenUtils.isOVConcaveScreen(paramContext)) { i = (int)UIUtils.dip2Px(paramContext, 27.0F); sStatusBarHeight = i; return i; } if (ConcaveScreenUtils.isHWConcaveScreen(paramContext)) { i = ConcaveScreenUtils.getHWConcaveScreenHeight(paramContext); sStatusBarHeight = i; return i; } i = 0; int j = paramContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (j > 0) i = paramContext.getResources().getDimensionPixelOffset(j); j = i; if (i == 0) j = (int)UIUtils.dip2Px(paramContext, 25.0F); sStatusBarHeight = j; return j; } public static String getSystem() { return Build.VERSION.RELEASE; } public static String getVersion(Context paramContext) { if (TextUtils.isEmpty(version)) { PackageManager packageManager = paramContext.getPackageManager(); try { version = (packageManager.getPackageInfo(paramContext.getPackageName(), 0)).versionName; } catch (Exception exception) { AppBrandLogger.stacktrace(6, "DevicesUtil", exception.getStackTrace()); } } return version; } public static int getWifiSignal(Context paramContext) { return 0; } public static boolean hasNotchInScreen(Context paramContext) { boolean bool; try { if (isHuawei()) { Class<?> clazz = paramContext.getClassLoader().loadClass("com.huawei.android.util.HwNotchSizeUtil"); bool = ((Boolean)clazz.getMethod("hasNotchInScreen", new Class[0]).invoke(clazz, new Object[0])).booleanValue(); try { AppBrandLogger.d("DevicesUtil", new Object[] { "hasNotchInScreen:", Boolean.valueOf(bool) }); return bool; } catch (Exception null) {} } else { return false; } } catch (Exception exception) { bool = false; } AppBrandLogger.e("DevicesUtil", new Object[] { "hasNotchInScreen error:", exception }); return bool; } private static void initMiuiVersion() { if (sMiuiVersion == null) { try { sMiuiVersion = BuildProperties.getInstance().getProperty("ro.miui.ui.version.name"); } catch (IOException iOException) { AppBrandLogger.stacktrace(6, "DevicesUtil", iOException.getStackTrace()); } String str2 = sMiuiVersion; String str1 = str2; if (str2 == null) str1 = ""; sMiuiVersion = str1; } } public static boolean isFlyme() { return Build.DISPLAY.startsWith("Flyme"); } public static boolean isHuawei() { return (Build.MANUFACTURER != null && Build.MANUFACTURER.contains("HUAWEI")); } public static boolean isMiui() { if (!sIsMiuiInited) { try { Class.forName("miui.os.Build"); sIsMiui = true; } catch (Exception exception) { AppBrandLogger.w("DevicesUtil", new Object[] { exception }); } sIsMiuiInited = true; } return sIsMiui; } public static boolean isMiuiV7() { initMiuiVersion(); return "V7".equals(sMiuiVersion); } public static boolean isMiuiV8() { initMiuiVersion(); return "V8".equals(sMiuiVersion); } public static boolean isMiuiV9() { initMiuiVersion(); return "V9".equals(sMiuiVersion); } public static boolean isScreenPortrait(Context paramContext) { int i = getScreenRotation(paramContext); return (i == 0 || i == 2); } public static void setFullScreenWindowLayoutInDisplayCutout(Window paramWindow) { if (paramWindow == null) return; WindowManager.LayoutParams layoutParams = paramWindow.getAttributes(); try { if (isHuawei()) { Class<?> clazz = Class.forName("com.huawei.android.view.LayoutParamsEx"); layoutParams = clazz.getConstructor(new Class[] { WindowManager.LayoutParams.class }).newInstance(new Object[] { layoutParams }); clazz.getMethod("addHwFlags", new Class[] { int.class }).invoke(layoutParams, new Object[] { Integer.valueOf(65536) }); } return; } catch (Exception exception) { AppBrandLogger.e("DevicesUtil", new Object[] { "setFullScreenWindowLayoutInDisplayCutout error:", exception }); return; } } public static void setMiuiStatusBarDarkMode(boolean paramBoolean, Window paramWindow) { try { boolean bool; Class<?> clazz1 = paramWindow.getClass(); Class<?> clazz2 = Class.forName("android.view.MiuiWindowManager$LayoutParams"); int i = clazz2.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE").getInt(clazz2); Method method = clazz1.getMethod("setExtraFlags", new Class[] { int.class, int.class }); if (paramBoolean) { bool = i; } else { bool = false; } return; } finally { paramWindow = null; } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniap\\util\DevicesUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.gtfs.bean; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "LIC_HIGH_SA_DISC_MST") public class LicHighSaDiscMst implements Serializable{ private Long id; private LicProductMst licProductMst; private Long term; private String consTermFlag; private Double hsdSaFrom; private Double hsdSaTo; private String hsdType; private Double hsdValue; private Long createdBy; private Long modifiedBy; private Long deletedBy; private Date createdDate; private Date modifiedDate; private Date deletedDate; private String deleteFlag; @Id @Column(name = "ID",nullable = false, precision = 22, scale = 0) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "LIC_PROD_MST_ID") public LicProductMst getLicProductMst() { return licProductMst; } public void setLicProductMst(LicProductMst licProductMst) { this.licProductMst = licProductMst; } @Column(name = "TERM", precision = 22, scale = 0) public Long getTerm() { return term; } public void setTerm(Long term) { this.term = term; } @Column(name = "CONS_TERM_FLAG", length=1) public String getConsTermFlag() { return consTermFlag; } public void setConsTermFlag(String consTermFlag) { this.consTermFlag = consTermFlag; } @Column(name = "HSD_SA_FROM", precision = 22, scale = 0) public Double getHsdSaFrom() { return hsdSaFrom; } public void setHsdSaFrom(Double hsdSaFrom) { this.hsdSaFrom = hsdSaFrom; } @Column(name = "HSD_SA_TO", precision = 22, scale = 0) public Double getHsdSaTo() { return hsdSaTo; } public void setHsdSaTo(Double hsdSaTo) { this.hsdSaTo = hsdSaTo; } @Column(name = "HSD_TYPE", length=5) public String getHsdType() { return hsdType; } public void setHsdType(String hsdType) { this.hsdType = hsdType; } @Column(name = "HSD_VALUE", precision = 22, scale = 0) public Double getHsdValue() { return hsdValue; } public void setHsdValue(Double hsdValue) { this.hsdValue = hsdValue; } @Column(name = "CREATED_BY", precision = 22, scale = 0) public Long getCreatedBy() { return createdBy; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } @Column(name = "MODIFIED_BY", precision = 22, scale = 0) public Long getModifiedBy() { return modifiedBy; } public void setModifiedBy(Long modifiedBy) { this.modifiedBy = modifiedBy; } @Column(name = "DELETED_BY", precision = 22, scale = 0) public Long getDeletedBy() { return deletedBy; } public void setDeletedBy(Long deletedBy) { this.deletedBy = deletedBy; } @Temporal(TemporalType.DATE) @Column(name = "CREATED_DATE", length = 7) public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Temporal(TemporalType.DATE) @Column(name = "MODIFIED_DATE", length = 7) public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } @Temporal(TemporalType.DATE) @Column(name = "DELETED_DATE", length = 7) public Date getDeletedDate() { return deletedDate; } public void setDeletedDate(Date deletedDate) { this.deletedDate = deletedDate; } @Column(name = "DELETE_FLAG", length = 1) public String getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } }
package com.tbt.testapi.command; import java.io.File; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.tbt.testapi.BaseCommand; import com.tbt.testapi.TestApiException; import com.tbt.testapi.main.Config; public class TaskCommand extends BaseCommand { @Override public void run(String id) throws TestApiException, DocumentException { String filePath = Config.getInstance().caseDataPath + "task/" + id + ".xml"; if (!new File(filePath).exists()) throw new TestApiException("task file not find."); SAXReader reader = new SAXReader(); Document doc; doc = reader.read(filePath); List list = doc.selectNodes("//task/group"); for (Iterator<Element> it = list.iterator(); it.hasNext();) { Element el = it.next(); String groupId = el.attributeValue("id"); BaseCommand command = new GroupCommand(); command.run(groupId); } } }
package Strings; import java.util.HashSet; import java.util.Set; public class CommonCharInTwoStrings { public static void main(String[] args) { String s1 = "abc"; String s2 = "aui"; for (int i = 0; i < s1.length(); i++) { char c = s1.charAt(i); String s3 = Character.toString(c); if (!s2.contains(s3)) { System.out.println(s3); } } } }
package br.com.allan.activity; /** * Created by freit on 04/02/2017. */ import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.concurrent.TimeUnit; import br.com.allan.R; import br.com.allan.common.CodeUtil; import br.com.allan.config.AppConfig; import br.com.allan.model.GenericResponse; import br.com.allan.model.Usuario; import br.com.allan.session.SessionManager; import br.com.allan.sqlite.SQLiteHandler; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; public class CadastroActivity extends AppCompatActivity { private EditText nameRegistro, emailRegistro, senhaRegistro; private Button butaoRegistrar, butaoLinkToLogin; private ProgressDialog pDialog; private SessionManager session; private SQLiteHandler db; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro); // Progress dialog pDialog = new ProgressDialog(this); pDialog.setCancelable(false); db = new SQLiteHandler(getApplicationContext()); // Session manager session = new SessionManager(getApplicationContext()); // Checa se o usuários já está logado ou não. if (session.isLoggedIn()) { // Caso o usuário esteja logado então encaminhá-lo para tela de bate-papo. Intent intent = new Intent(CadastroActivity.this, MainActivity.class); startActivity(intent); finish(); } //Bind dos butões... nameRegistro = (EditText) findViewById(R.id.nameRegister); emailRegistro = (EditText) findViewById(R.id.emailRegister); senhaRegistro = (EditText) findViewById(R.id.passwordRegister); //Bind dos botões. butaoRegistrar = (Button) findViewById(R.id.btnRegister); butaoLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); //Listener para o botao. butaoLinkToLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Encaminho para atividade... Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); } }); butaoRegistrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = nameRegistro.getText().toString().trim(); String email = emailRegistro.getText().toString().trim(); String password = senhaRegistro.getText().toString().trim(); if(!validate()){ onLoginFailed("Email ou senha não podem estar vazios.."); return; } Usuario u = new Usuario(); u.setPassword(password); u.setDeleted(false); u.setEmail(email); u.setName(name); makeRegistro(u); } }); } private void makeRegistro(Usuario usuario){ String parametroCoded = CodeUtil.getStringCoded(new Gson().toJson(usuario)); pDialog.setMessage(this.getString(R.string.login)); showDialog(); OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS); OkHttpClient okHttpClient = okHttpClientBuilder.build(); Uri.Builder builder = new Uri.Builder(); builder.scheme("http").encodedAuthority(AppConfig.URL_BASE) .appendPath("usuario") .appendPath("add") .appendQueryParameter("parametro", parametroCoded); String url = builder.build().toString(); Request request = new Request.Builder() .url(url) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { hideDialog(); final String error = e.getMessage(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show(); } }); } @Override public void onResponse(Call call, okhttp3.Response response) throws IOException { try { String responseBody = CodeUtil.getStringDecoded(response.body().string()); if (responseBody.contains("Falha no login")){ JSONObject jsonObject = new JSONObject(responseBody); Gson gson = new Gson(); final GenericResponse genericResponse = gson.fromJson(jsonObject.toString(), GenericResponse.class); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), genericResponse.getMessage(), Toast.LENGTH_LONG).show(); } }); hideDialog(); } if (!responseBody.contains("Falha no login")){ JSONObject jsonObject = new JSONObject(responseBody); Gson gson = new Gson(); final Usuario user = gson.fromJson(jsonObject.toString(), Usuario.class); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Registro realizado com sucesso, " + user.getName(), Toast.LENGTH_LONG).show(); } }); //Encaminha para tela de login após o cadastro efetuado com sucesso. Intent intent = new Intent(CadastroActivity.this, LoginActivity.class); startActivity(intent); } }catch (JSONException e){ hideDialog(); e.printStackTrace(); } } }); } private void onLoginSuccess(String message) { Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show(); } private boolean validate() { boolean valid = true; String email = emailRegistro.getText().toString(); String password = this.senhaRegistro.getText().toString(); String name = this.nameRegistro.getText().toString(); if (email.isEmpty()) { valid = false; } if (password.isEmpty()) { valid = false; } if (name.isEmpty()) { valid = false; } return valid; } public void onLoginFailed(String errorMsg) { Toast.makeText(getBaseContext(), errorMsg, Toast.LENGTH_LONG).show(); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } @Override protected void onStop() { super.onStop(); } }
package per.goweii.basic.core.base; import android.content.Context; import butterknife.ButterKnife; import butterknife.Unbinder; import per.goweii.basic.core.mvp.MvpLayer; /** * 描述: * * @author Cuizhen * @date 2019/3/29 */ public abstract class BaseLayer<P extends BasePresenter> extends MvpLayer<P> { private Unbinder mUnbinder = null; public BaseLayer(Context context) { super(context); } @Override protected void initialize() { if (mAnyLayer != null && mAnyLayer.getContentView() != null) { mUnbinder = ButterKnife.bind(mAnyLayer.getContentView()); } super.initialize(); } @Override protected boolean onDestroy() { boolean destroy = super.onDestroy(); if (destroy && mUnbinder != null) { mUnbinder.unbind(); } return destroy; } }
package br.com.volvo.api.data; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -5183069099661541090L; private Long id; private String name; private String description; private Department department; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
package com.javastudio.tutorial.spring.api; import com.javastudio.tutorial.spring.model.Product; import java.util.List; public interface ProductService { List<Product> findAll(); Product findById(long id); }
package exercise.testexercise.controller; import exercise.testexercise.dto.PointDTO; import exercise.testexercise.service.PointService; import org.springframework.http.ResponseEntity; 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 java.util.List; import java.util.Set; @RestController @RequestMapping(path = "/lines") public class LineController { private final PointService pointService; public LineController(PointService pointService) { this.pointService = pointService; } @GetMapping(path = "/{n}") public ResponseEntity<List<Set<PointDTO>>> getLines(@PathVariable Integer n) { return ResponseEntity.ok(pointService.getLines(n)); } }
package arduinosketch; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; /** * Created by troy on 07.10.2016. */ public class ArduinoNetGag { private long timeOut = 1000; public ArduinoNetGag() throws InterruptedException { String massage = null; String answer; UnitTest unitTest1 = new UnitTest("temp2"); unitTest1.setValue("1"); UnitTest unitTest2 = new UnitTest("hum2"); unitTest2.setValue("2"); massage ="info " + unitTest1.readData() + unitTest2.readData(); massage.trim(); // massage = massage + "\n"; answer = sendMassage(massage); unitTest1.checkTheSettings(answer); unitTest2.checkTheSettings(answer); System.out.println("Massage is: " + massage); System.out.println("Answer is: " + answer); while (true){ massage = ""; // long inTime = System.currentTimeMillis(); if (unitTest1.checkTime(System.currentTimeMillis())){ massage = massage + unitTest1.readData(); } if (unitTest2.checkTime(System.currentTimeMillis())){ massage = massage + unitTest2.readData(); } if (!massage.isEmpty()){ answer = sendMassage(massage.trim() + "\n"); unitTest1.checkTheSettings(answer); unitTest2.checkTheSettings(answer); System.out.println("Massage is: " + massage); System.out.println("Answer is: " + answer); } // long outTime = System.currentTimeMillis(); // System.out.println("Used time: " + (outTime-inTime) + " ms"); Thread.sleep(timeOut); answer = ""; } } private String sendMassage(String massage){ String answer = "blank"; try (Socket socket = new Socket("localhost", 7778); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)){ writer.println(massage); answer = reader.readLine(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return answer; } class UnitTest{ private long timeOut; private long lastTime; private String name; private String value = "blank"; public UnitTest(String name) { this.name = name; } public boolean checkTime(long currentTime){ boolean answer = false; if ((currentTime - this.lastTime)>= timeOut) answer = true; return answer; } public void setTimeOut(long timeOut) { this.timeOut = timeOut; } public void setValue(String value) { this.value = value; } public long getTimeOut() { return this.timeOut; } public String readData(){ this.lastTime = System.currentTimeMillis(); return name + "=" + value + " "; } public boolean checkTheSettings(String settings){ boolean answer = false; String[] setArr = settings.split(" "); for (String pair : setArr ){ if (pair.contains(name)){ answer = true; if (pair.contains(":")){ String[] arr = pair.split(":"); this.timeOut = Long.parseLong(arr[1]); } else if (pair.contains("=")){ String[] arr = pair.split("="); this.value = arr[1]; } else answer = false; } } return answer; } } }
package com.tencent.mm.plugin.game.ui; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.game.a.c; class GameDownloadGuidanceUI$3 implements Runnable { final /* synthetic */ GameDownloadGuidanceUI jXC; GameDownloadGuidanceUI$3(GameDownloadGuidanceUI gameDownloadGuidanceUI) { this.jXC = gameDownloadGuidanceUI; } public final void run() { ((c) g.l(c.class)).aSk().a("pb_over_sea", GameDownloadGuidanceUI.b(this.jXC)); } }
package com.javarush.task.task31.task3110; import com.javarush.task.task31.task3110.exception.WrongZipFileException; import java.io.IOException; public class Archiver { public static void main(String[] args) throws IOException { Operation operation = null; do { try { operation = askOperation(); CommandExecutor.execute(operation); } catch (WrongZipFileException e) { ConsoleHelper.writeMessage("You haven't selected an archive file or you have selected the wrong file."); } catch (Exception e) { ConsoleHelper.writeMessage("An error has occurred. Check the entered data."); } } while (operation != Operation.EXIT); } public static Operation askOperation() throws IOException { ConsoleHelper.writeMessage(""); ConsoleHelper.writeMessage("Select operation:"); ConsoleHelper.writeMessage(String.format("\t %d - zip the file", Operation.CREATE.ordinal())); ConsoleHelper.writeMessage(String.format("\t %d - add the file in archive", Operation.ADD.ordinal())); ConsoleHelper.writeMessage(String.format("\t %d - delete file from archive", Operation.REMOVE.ordinal())); ConsoleHelper.writeMessage(String.format("\t %d - unpack zip", Operation.EXTRACT.ordinal())); ConsoleHelper.writeMessage(String.format("\t %d - check archives content", Operation.CONTENT.ordinal())); ConsoleHelper.writeMessage(String.format("\t %d - exit", Operation.EXIT.ordinal())); return Operation.values()[ConsoleHelper.readInt()]; } }
package com.kh.efp.alarm.model.dao; import java.util.ArrayList; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.kh.efp.alarm.model.vo.Alarm; @Repository public class AlarmDaoImpl implements AlarmDao{ @Override public ArrayList<Alarm> selectListAlarm(SqlSessionTemplate sqlSession, int mid) { return (ArrayList)sqlSession.selectList("Alarm.selectListAlarm", mid); } @Override public void updateNews(SqlSessionTemplate sqlSession) { sqlSession.selectOne("updateNews"); } //모든 알림 제거 @Override public int deleteAllAlarm(SqlSessionTemplate sqlSession, int mid) { return sqlSession.delete("Alarm.deleteAllAlarm",mid); } @Override public int deleteOneAlarm(SqlSessionTemplate sqlSession, int nid) { return sqlSession.delete("Alarm.deleteOneAlarm",nid); } }
package com.igwines.dao; import com.igwines.model.User; import org.springframework.data.repository.CrudRepository; import java.util.Optional; public interface UserRepository extends CrudRepository<User, Long> { Optional<User> findUserByName(String name); }
import java.util.*; import java.io.*; class tuzikdog{ public static void main(String[] args) { int n,k,x; x=0; Scanner sc= new Scanner(System.in); System.out.println("Enter no of coins,n"); n=sc.nextInt(); System.out.println("Enter no of people,k"); k=sc.nextInt(); for(int i=n;i>0;i--){ if(i%k==0){ x=i; //System.out.println("val of x"+x); break; } else{ continue; } } int z=n-x; System.out.println("No of coins Tuzik would get are "+z); } }
package com.workorder.ticket.service; import java.util.List; import com.workorder.ticket.service.bo.user.UserEditBo; import com.workorder.ticket.service.bo.user.UserInfoBo; import com.workorder.ticket.service.bo.user.UserQueryBo; /** * 用户服务 * * @author wzdong * @Date 2019年3月4日 * @version 1.0 */ public interface UserService { int create(UserEditBo userEditBo); int updateUser(UserEditBo userEditBo); List<UserInfoBo> queryList(UserQueryBo userQueryBo); int queryUserCount(UserQueryBo userQueryBo); UserInfoBo getUserInfoById(Long userId); int disableUser(Long userId); int resetUserPwd(Long userId); int updateUserPwd(Long userId, String oldPwd, String newPwd); UserInfoBo getUserByUserNameAndPwd(String username, String password); UserInfoBo getUserByUserName(String username); }
package com.itechart.smg3; import com.itechart.pages.LoginPage; import com.itechart.pages.PersonalPage; import com.itechart.driver.DriverFactory; import com.itechart.driver.DriverType; import org.openqa.selenium.WebDriver; import java.io.*; import java.util.concurrent.TimeUnit; public class Vacation { public static void main(String[] args) throws IOException { File file = new File("src/main/resources/files/input.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter("src/main/resources/files/output.txt"); PrintWriter printWriter = new PrintWriter(fileWriter); String line; //value for each line in input.txt while((line=bufferedReader.readLine())!=null) { WebDriver driver; //System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/geckodriver.exe"); driver = DriverFactory.getManager(DriverType.FIREFOX).getDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://192.168.15.26/"); LoginPage loginPage = new LoginPage(driver); loginPage.logIn(line); PersonalPage personalPage = new PersonalPage(driver); printWriter.printf("Login %s: Vacation - %s; Illness - %s", line, personalPage.getTextOnVacation(), personalPage.getTextOnIllness()); printWriter.println(); driver.quit(); } printWriter.close(); } }
package ncs.r4a118.shop; import java.util.List; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Service; import ncs.r4a118.db.DBDao; @Service public class ProductDBManage extends JdbcDaoSupport implements DBDao<Product> { //sql private final String selectSql = "select pro_code, pro_name, pro_price, pro_unit, pro_desc, pro_img from products"; private final String seacrhSql = "select pro_code, pro_name, pro_price, pro_unit, pro_desc, pro_img from products where pro_code=?"; private final String insertSql = "insert into products(pro_name, pro_price, pro_unit, pro_desc, pro_img) values(?,?,?,?,?)"; private final String deleteSql = "delete from products where pro_code=?"; private final String updateSql = "update products set pro_name=?, pro_price=?, pro_unit=?, pro_desc=?, pro_img=? where pro_code=?"; @Autowired private DataSource dataSource; public ProductDBManage() {} @PostConstruct private void initialize() { setDataSource(dataSource); } @Override public List<Product> select() throws DataAccessException { RowMapper<Product> map = (rs,rowNum) -> { Product item = new Product(); item.setCode(rs.getInt("pro_code")); item.setName(rs.getString("pro_name")); item.setPrice(rs.getInt("pro_price")); item.setUnit(rs.getString("pro_unit")); item.setDesc(rs.getString("pro_desc")); item.setImg(rs.getString("pro_img")); return item; }; return getJdbcTemplate().query(selectSql, map); } @Override public List<Product> select(String seachData) throws DataAccessException { // TODO 自動生成されたメソッド・スタブ return null; } @Override public int insert(Product product) throws DataAccessException { Object[] param = { product.getName(), product.getPrice(), product.getUnit(), product.getDesc(), product.getImg()}; return getJdbcTemplate().update(insertSql, param); } @Override public Product search(Product product) throws DataAccessException { RowMapper<Product> map = (rs,rowNum) -> { Product item = new Product(); item.setCode(rs.getInt("pro_code")); item.setName(rs.getString("pro_name")); item.setPrice(rs.getInt("pro_price")); item.setUnit(rs.getString("pro_unit")); item.setDesc(rs.getString("pro_desc")); item.setImg(rs.getString("pro_img")); return item; }; return getJdbcTemplate().query(seacrhSql, new Object[] {product.getCode()}, map).get(0); } @Override public int delete(Product product) throws DataAccessException { Object[] param = {product.getCode()}; return getJdbcTemplate().update(deleteSql, param); } @Override public int update(Product product) throws DataAccessException { Object[] param = { product.getName(), product.getPrice(), product.getUnit(), product.getDesc(), product.getImg(), product.getCode()}; return getJdbcTemplate().update(updateSql, param); } }
package com.jiuzhe.app.hotel.service; import java.util.Map; public interface RoomReservationService { public Map getReservation(String skuId, String beginDate, String endDate); public Map getReservation(String skuId, String beginDate); public Map setReservation(String skuId, String beginDate, String endDate); public Map setReservation(String skuId, String beginDate); public Map unsetReservation(String skuId, String beginDate, String endDate); public Map unsetReservation(String skuId, String beginDate); }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.widget.searchresult; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.bean.GWTDocument; import com.openkm.frontend.client.bean.GWTFolder; import com.openkm.frontend.client.bean.GWTMail; import com.openkm.frontend.client.bean.GWTPermission; import com.openkm.frontend.client.bean.GWTPropertyGroup; import com.openkm.frontend.client.bean.GWTQueryResult; import com.openkm.frontend.client.bean.form.GWTFormElement; import com.openkm.frontend.client.service.OKMPropertyGroupService; import com.openkm.frontend.client.service.OKMPropertyGroupServiceAsync; import com.openkm.frontend.client.util.CommonUI; import com.openkm.frontend.client.util.OKMBundleResources; import com.openkm.frontend.client.util.Util; import com.openkm.frontend.client.widget.WidgetUtil; import com.openkm.frontend.client.widget.dashboard.keymap.TagCloud; import com.openkm.frontend.client.widget.form.FormManager; import com.openkm.frontend.client.widget.searchin.SearchControl; /** * SearchFullResult * * @author jllort * */ public class SearchFullResult extends Composite { private final OKMPropertyGroupServiceAsync propertyGroupService = (OKMPropertyGroupServiceAsync) GWT.create(OKMPropertyGroupService.class); private ScrollPanel scrollPanel; private FlexTable table; /** * SearchFullResult */ public SearchFullResult() { table = new FlexTable(); scrollPanel = new ScrollPanel(table); scrollPanel.setStyleName("okm-Input"); initWidget(scrollPanel); } /* (non-Javadoc) * @see com.google.gwt.user.client.ui.UIObject#setPixelSize(int, int) */ public void setPixelSize(int width, int height) { table.setWidth("100%"); scrollPanel.setPixelSize(width, height); } /** * Adds a document to the panel * * @param doc The doc to add */ public void addRow(GWTQueryResult gwtQueryResult) { if (gwtQueryResult.getDocument()!=null || gwtQueryResult.getAttachment()!=null) { addDocumentRow(gwtQueryResult, new Score(gwtQueryResult.getScore())); } else if (gwtQueryResult.getFolder()!=null) { addFolderRow(gwtQueryResult, new Score(gwtQueryResult.getScore())); } else if (gwtQueryResult.getMail()!=null) { addMailRow(gwtQueryResult, new Score(gwtQueryResult.getScore())); } } /** * Adding document row * * @param gwtQueryResult Query result * @param score Document score */ private void addDocumentRow(GWTQueryResult gwtQueryResult, Score score) { int rows = table.getRowCount(); final GWTDocument doc; if (gwtQueryResult.getDocument() != null) { doc = gwtQueryResult.getDocument(); } else if (gwtQueryResult.getAttachment() != null) { doc = gwtQueryResult.getAttachment(); } else { doc = new GWTDocument(); } // Document row HorizontalPanel hPanel = new HorizontalPanel(); hPanel.setStyleName("okm-NoWrap"); hPanel.add(new HTML(score.getHTML())); hPanel.add(Util.hSpace("5px")); hPanel.add(new HTML(Util.mimeImageHTML(doc.getMimeType()))); hPanel.add(Util.hSpace("5px")); Anchor anchor = new Anchor(); anchor.setHTML(doc.getName()); anchor.setStyleName("okm-Hyperlink"); String path = ""; // On attachment case must remove last folder path, because it's internal usage not for visualization if (doc.isAttachment()) { anchor.setTitle(Util.getParent(doc.getParentPath())); path = doc.getParentPath(); // path will contains mail path } else { anchor.setTitle(doc.getParentPath()); path = doc.getPath(); } final String docPath = path; anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { CommonUI.openPath(Util.getParent(docPath), docPath); } }); hPanel.add(anchor); hPanel.add(Util.hSpace("5px")); hPanel.add(new HTML(doc.getActualVersion().getName())); hPanel.add(Util.hSpace("5px")); // Search similar documents if (Main.get().workspaceUserProperties.getWorkspace().getAvailableOption().isSimilarDocumentVisible()) { final String uuid = doc.getUuid(); Image findSimilarDocument = new Image(OKMBundleResources.INSTANCE.findSimilarDocument()); findSimilarDocument.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Main.get().findSimilarDocumentSelectPopup.show(); Main.get().findSimilarDocumentSelectPopup.find(uuid); } }); findSimilarDocument.setTitle(Main.i18n("general.menu.file.find.similar.document")); findSimilarDocument.setStyleName("okm-KeyMap-ImageHover"); hPanel.add(findSimilarDocument); hPanel.add(Util.hSpace("5px")); } // Download if (Main.get().workspaceUserProperties.getWorkspace().getAvailableOption().isDownloadOption()) { Image downloadDocument = new Image(OKMBundleResources.INSTANCE.download()); downloadDocument.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Util.downloadFileByUUID(doc.getUuid(), ""); } }); downloadDocument.setTitle(Main.i18n("general.menu.file.download.document")); downloadDocument.setStyleName("okm-KeyMap-ImageHover"); hPanel.add(downloadDocument); } table.setWidget(rows++, 0, hPanel); // Excerpt row if ((Main.get().mainPanel.search.searchBrowser.searchIn.searchControl.getSearchMode() == SearchControl.SEARCH_MODE_SIMPLE || !Main.get().mainPanel.search.searchBrowser.searchIn.searchNormal.content.getText().equals("")) && gwtQueryResult.getExcerpt() != null) { table.setHTML(rows++, 0, ""+gwtQueryResult.getExcerpt()+(gwtQueryResult.getExcerpt().length()>256?" ...":"")); HTML space = new HTML(); table.setWidget(rows, 0, space); table.getFlexCellFormatter().setHeight(rows++, 0, "5px"); } // Folder row HorizontalPanel hPanel2 = new HorizontalPanel(); hPanel2.setStyleName("okm-NoWrap"); hPanel2.add(new HTML("<b>"+Main.i18n("document.folder")+":</b>&nbsp;")); if (doc.isAttachment()) { String convertedPath = doc.getParentPath(); convertedPath = Util.getParent(convertedPath) + "/"+ Util.getName(convertedPath).substring(37); hPanel2.add(drawMailWithAttachment(convertedPath, path)); } else { hPanel2.add(drawFolder(doc.getParentPath())); } table.setWidget(rows++, 0, hPanel2); // Document detail HorizontalPanel hPanel4 = new HorizontalPanel(); hPanel4.setStyleName("okm-NoWrap"); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.author")+":</b>&nbsp;")); hPanel4.add(new HTML(doc.getActualVersion().getUser().getUsername())); hPanel4.add(Util.hSpace("33px")); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.size")+":</b>&nbsp;")); hPanel4.add(new HTML(Util.formatSize(doc.getActualVersion().getSize()))); hPanel4.add(Util.hSpace("33px")); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.version")+":</b>&nbsp;")); hPanel4.add(new HTML(doc.getActualVersion().getName())); hPanel4.add(Util.hSpace("33px")); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.date.update")+":&nbsp;</b>")); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern")); hPanel4.add(new HTML(dtf.format(doc.getLastModified()))); table.setWidget(rows++, 0, hPanel4); // Categories and tagcloud rows = addCategoriesKeywords(doc.getCategories(),doc.getKeywords(), table); // PropertyGroups rows = addPropertyGroups(doc.getPath(), table); // Separator end line Image horizontalLine = new Image("img/transparent_pixel.gif"); horizontalLine.setStyleName("okm-TopPanel-Line-Border"); horizontalLine.setSize("100%", "2px"); table.setWidget(rows, 0, horizontalLine); table.getFlexCellFormatter().setVerticalAlignment(rows, 0, HasAlignment.ALIGN_BOTTOM); table.getFlexCellFormatter().setHeight(rows, 0, "30px"); } /** * addPropertyGroups */ private int addPropertyGroups(final String path, FlexTable table) { int rows = table.getRowCount(); if (Main.get().mainPanel.search.searchBrowser.searchIn.searchControl.showPropertyGroups.getValue()) { final HorizontalPanel propertyGroupsPanel = new HorizontalPanel(); table.setWidget(rows++, 0, propertyGroupsPanel); propertyGroupService.getGroups(path, new AsyncCallback<List<GWTPropertyGroup>>() { @Override public void onSuccess(List<GWTPropertyGroup> result) { drawPropertyGroups(path, result, propertyGroupsPanel); } @Override public void onFailure(Throwable caught) { Main.get().showError("getGroups", caught); } }); } return rows; } /** * drawCategoriesKeywords */ private int addCategoriesKeywords(Set<GWTFolder> categories, Set<String> keywords, FlexTable table) { int rows = table.getRowCount(); // Categories and tagcloud if (categories.size() > 0 || keywords.size() > 0) { HorizontalPanel hPanel = new HorizontalPanel(); hPanel.setStyleName("okm-NoWrap"); if (categories.size() > 0) { FlexTable tableSubscribedCategories = new FlexTable(); tableSubscribedCategories.setStyleName("okm-DisableSelect"); // Sets the document categories for (Iterator<GWTFolder> it = categories.iterator(); it.hasNext();) { drawCategory(tableSubscribedCategories, it.next()); } hPanel.add(new HTML("<b>"+Main.i18n("document.categories")+"</b>")); hPanel.add(Util.hSpace("5px")); hPanel.add(tableSubscribedCategories); hPanel.add(Util.hSpace("33px")); } if (keywords.size() > 0) { // Tag cloud TagCloud keywordsCloud = new TagCloud(); keywordsCloud.setWidth("350px"); WidgetUtil.drawTagCloud(keywordsCloud, keywords); hPanel.add(new HTML("<b>"+Main.i18n("document.keywords.cloud")+"</b>")); hPanel.add(Util.hSpace("5px")); hPanel.add(keywordsCloud); } table.setWidget(rows++, 0, hPanel); } return rows; } /** * drawPropertyGroups */ private void drawPropertyGroups(final String docPath, final List<GWTPropertyGroup> propertyGroups, final HorizontalPanel propertyGroupsPanel) { if (propertyGroups.size() > 0) { Status status = Main.get().mainPanel.search.searchBrowser.searchResult.status; status.setFlag_refreshPropertyGroups(); final GWTPropertyGroup propertyGroup = propertyGroups.remove(0); propertyGroupService.getProperties(docPath, propertyGroup.getName(), false, new AsyncCallback<List<GWTFormElement>>() { @Override public void onSuccess(List<GWTFormElement> result) { if (propertyGroupsPanel.getWidgetCount()==0) { HTML label = new HTML(""); label.setStyleName("okm-Security-Title"); label.setHeight("15px"); Image verticalLine = new Image("img/transparent_pixel.gif"); verticalLine.setStyleName("okm-Vertical-Line-Border"); verticalLine.setSize("2px","100%"); VerticalPanel vlPanel = new VerticalPanel(); vlPanel.add(label); vlPanel.add(verticalLine); vlPanel.setCellWidth(verticalLine, "7px"); vlPanel.setCellHeight(verticalLine, "100%"); vlPanel.setHeight("100%"); propertyGroupsPanel.add(vlPanel); propertyGroupsPanel.setCellHorizontalAlignment(vlPanel, HasAlignment.ALIGN_LEFT); propertyGroupsPanel.setCellWidth(vlPanel, "7px"); propertyGroupsPanel.setCellHeight(vlPanel, "100%"); } Image verticalLine = new Image("img/transparent_pixel.gif"); verticalLine.setStyleName("okm-Vertical-Line-Border"); verticalLine.setSize("2px","100%"); FormManager manager = new FormManager(); manager.setFormElements(result); manager.draw(true); // read only ! VerticalPanel vPanel = new VerticalPanel(); HTML label = new HTML(propertyGroup.getLabel()); label.setStyleName("okm-Security-Title"); label.setHeight("15px"); vPanel.add(label); vPanel.add(manager.getTable()); propertyGroupsPanel.add(vPanel); propertyGroupsPanel.add(verticalLine); propertyGroupsPanel.setCellVerticalAlignment(vPanel, HasAlignment.ALIGN_TOP); propertyGroupsPanel.setCellHorizontalAlignment(verticalLine, HasAlignment.ALIGN_CENTER); propertyGroupsPanel.setCellWidth(verticalLine, "12px"); propertyGroupsPanel.setCellHeight(verticalLine, "100%"); drawPropertyGroups(docPath, propertyGroups, propertyGroupsPanel); } @Override public void onFailure(Throwable caught) { Main.get().showError("drawPropertyGroups", caught); } }); } else { Status status = Main.get().mainPanel.search.searchBrowser.searchResult.status; status.unsetFlag_refreshPropertyGroups(); } } /** * Adding folder * * @param gwtQueryResult Query result * @param score The folder score */ private void addFolderRow(GWTQueryResult gwtQueryResult, Score score) { int rows = table.getRowCount(); final GWTFolder folder = gwtQueryResult.getFolder(); // Folder row HorizontalPanel hPanel = new HorizontalPanel(); hPanel.setStyleName("okm-NoWrap"); hPanel.add(new HTML(score.getHTML())); hPanel.add(Util.hSpace("5px")); // Looks if must change icon on parent if now has no childs and properties with user security atention if ( (folder.getPermissions() & GWTPermission.WRITE) == GWTPermission.WRITE) { if (folder.isHasChildren()) { hPanel.add(new HTML(Util.imageItemHTML("img/menuitem_childs.gif"))); } else { hPanel.add(new HTML(Util.imageItemHTML("img/menuitem_empty.gif"))); } } else { if (folder.isHasChildren()) { hPanel.add(new HTML(Util.imageItemHTML("img/menuitem_childs_ro.gif"))); } else { hPanel.add(new HTML(Util.imageItemHTML("img/menuitem_empty_ro.gif"))); } } Anchor anchor = new Anchor(); anchor.setHTML(folder.getName()); anchor.setTitle(folder.getParentPath()); anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { CommonUI.openPath(folder.getPath(), ""); } }); anchor.setStyleName("okm-Hyperlink"); hPanel.add(anchor); table.setWidget(rows++, 0, hPanel); // Folder row HorizontalPanel hPanel2 = new HorizontalPanel(); hPanel2.setStyleName("okm-NoWrap"); hPanel2.add(new HTML("<b>"+Main.i18n("folder.parent")+":</b>&nbsp;")); hPanel2.add(drawFolder(folder.getParentPath())); table.setWidget(rows++, 0, hPanel2); // Folder detail HorizontalPanel hPanel3 = new HorizontalPanel(); hPanel3.setStyleName("okm-NoWrap"); hPanel3.add(new HTML("<b>"+Main.i18n("search.result.author")+":</b>&nbsp;")); hPanel3.add(new HTML(folder.getUser().getUsername())); hPanel3.add(Util.hSpace("33px")); hPanel3.add(new HTML("<b>"+Main.i18n("folder.created")+":&nbsp;</b>")); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern")); hPanel3.add(new HTML(dtf.format(folder.getCreated()))); table.setWidget(rows++, 0, hPanel3); // Categories and tagcloud rows = addCategoriesKeywords(folder.getCategories(),folder.getKeywords(), table); // PropertyGroups rows = addPropertyGroups(folder.getPath(), table); // Separator end line Image horizontalLine = new Image("img/transparent_pixel.gif"); horizontalLine.setStyleName("okm-TopPanel-Line-Border"); horizontalLine.setSize("100%", "2px"); table.setWidget(rows, 0, horizontalLine); table.getFlexCellFormatter().setVerticalAlignment(rows, 0, HasAlignment.ALIGN_BOTTOM); table.getFlexCellFormatter().setHeight(rows, 0, "30px"); } /** * Adding mail * * @param gwtQueryResult Query result * @param score The mail score */ private void addMailRow(GWTQueryResult gwtQueryResult, Score score) { int rows = table.getRowCount(); final GWTMail mail = gwtQueryResult.getMail(); // Mail row HorizontalPanel hPanel = new HorizontalPanel(); hPanel.setStyleName("okm-NoWrap"); hPanel.add(new HTML(score.getHTML())); hPanel.add(Util.hSpace("5px")); if (mail.getAttachments().size() > 0) { hPanel.add(new HTML(Util.imageItemHTML("img/email_attach.gif"))); } else { hPanel.add(new HTML(Util.imageItemHTML("img/email.gif"))); } Anchor anchor = new Anchor(); anchor.setHTML(mail.getSubject()); anchor.setTitle(mail.getParentPath()); anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { String docPath = mail.getPath(); CommonUI.openPath(Util.getParent(docPath), docPath); } }); anchor.setStyleName("okm-Hyperlink"); hPanel.add(anchor); table.setWidget(rows++, 0, hPanel); // Mail Subject HorizontalPanel hPanel2 = new HorizontalPanel(); hPanel2.setStyleName("okm-NoWrap"); hPanel2.add(new HTML("<b>"+Main.i18n("mail.subject")+":</b>&nbsp;")); hPanel2.add(new HTML(mail.getSubject())); // Excerpt row if ((Main.get().mainPanel.search.searchBrowser.searchIn.searchControl.getSearchMode() == SearchControl.SEARCH_MODE_SIMPLE || !Main.get().mainPanel.search.searchBrowser.searchIn.searchNormal.content.getText().equals("")) && gwtQueryResult.getExcerpt() != null) { table.setHTML(rows++, 0, ""+gwtQueryResult.getExcerpt()+(gwtQueryResult.getExcerpt().length()>256?" ...":"")); HTML space = new HTML(); table.setWidget(rows, 0, space); table.getFlexCellFormatter().setHeight(rows++, 0, "5px"); } // Folder row HorizontalPanel hPanel3 = new HorizontalPanel(); hPanel3.setStyleName("okm-NoWrap"); hPanel3.add(new HTML("<b>"+Main.i18n("document.folder")+":</b>&nbsp;")); hPanel3.add(drawFolder(mail.getParentPath())); table.setWidget(rows++, 0, hPanel3); // mail details HorizontalPanel hPanel4 = new HorizontalPanel(); hPanel4.setStyleName("okm-NoWrap"); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.author")+":</b>&nbsp;")); hPanel4.add(new HTML(mail.getAuthor())); hPanel4.add(Util.hSpace("33px")); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.size")+":</b>&nbsp;")); hPanel4.add(new HTML(Util.formatSize(mail.getSize()))); hPanel4.add(Util.hSpace("33px")); hPanel4.add(new HTML("<b>"+Main.i18n("search.result.date.create")+":&nbsp;</b>")); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern")); hPanel4.add(new HTML(dtf.format(mail.getCreated()))); table.setWidget(rows++, 0, hPanel4); // Categories and tagcloud rows = addCategoriesKeywords(mail.getCategories(),mail.getKeywords(), table); // PropertyGroups rows = addPropertyGroups(mail.getPath(), table); // From, To and Reply panel HorizontalPanel hPanel5 = new HorizontalPanel(); hPanel5.setStyleName("okm-NoWrap"); hPanel5.add(new HTML("<b>"+Main.i18n("mail.from")+":</b>&nbsp;")); hPanel5.add(new HTML(mail.getFrom())); if (mail.getTo().length > 0) { VerticalPanel toPanel = new VerticalPanel(); for (int i=0; i < mail.getTo().length; i++) { Anchor hTo = new Anchor(); final String mailTo = mail.getTo()[i].contains("<") ? mail.getTo()[i].substring(mail.getTo()[i].indexOf("<") + 1, mail.getTo()[i].indexOf(">")):mail.getTo()[i]; hTo.setHTML(mail.getTo()[i].replace("<", "&lt;").replace(">", "&gt;")); hTo.setTitle("mailto:" + mailTo); hTo.setStyleName("okm-Mail-Link"); hTo.addStyleName("okm-NoWrap"); hTo.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.open("mailto:" + mailTo, "_self", ""); } }); toPanel.add(hTo); } hPanel5.add(Util.hSpace("33px")); hPanel5.add((new HTML("<b>" + Main.i18n("mail.to") + ":</b>&nbsp;"))); hPanel5.add(toPanel); } if (mail.getReply().length > 0) { VerticalPanel replyPanel = new VerticalPanel(); for (int i=0; i < mail.getReply().length; i++) { Anchor hReply = new Anchor(); final String mailReply = mail.getReply()[i].contains("<") ? mail.getReply()[i].substring(mail.getReply()[i].indexOf("<") + 1, mail.getReply()[i].indexOf(">")):mail.getReply()[i]; hReply.setHTML(mail.getReply()[i].replace("<", "&lt;").replace(">", "&gt;")); hReply.setTitle("mailto:" + mailReply); hReply.setStyleName("okm-Mail-Link"); hReply.addStyleName("okm-NoWrap"); hReply.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.open("mailto:" + mailReply, "_self", ""); } }); replyPanel.add(hReply); } hPanel5.add(Util.hSpace("33px")); hPanel5.add(new HTML("<b>" + Main.i18n("mail.reply") + ":</b>&nbsp;")); hPanel5.add(replyPanel); } table.setWidget(rows++, 0, hPanel5); // Separator end line Image horizontalLine = new Image("img/transparent_pixel.gif"); horizontalLine.setStyleName("okm-TopPanel-Line-Border"); horizontalLine.setSize("100%", "2px"); table.setWidget(rows, 0, horizontalLine); table.getFlexCellFormatter().setVerticalAlignment(rows, 0, HasAlignment.ALIGN_BOTTOM); table.getFlexCellFormatter().setHeight(rows, 0, "30px"); } /** * drawCategory */ private void drawCategory(final FlexTable tableSubscribedCategories, final GWTFolder category) { int row = tableSubscribedCategories.getRowCount(); Anchor anchor = new Anchor(); // Looks if must change icon on parent if now has no childs and properties with user security atention String path = category.getPath().substring(16); // Removes /okm:categories if (category.isHasChildren()) { anchor.setHTML(Util.imageItemHTML("img/menuitem_childs.gif", path, "top")); } else { anchor.setHTML(Util.imageItemHTML("img/menuitem_empty.gif", path, "top")); } anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { CommonUI.openPath(category.getPath(), null); } }); anchor.setStyleName("okm-KeyMap-ImageHover"); tableSubscribedCategories.setWidget(row, 0, anchor); } /** * drawFolder */ private Anchor drawFolder(final String path) { Anchor anchor = new Anchor(); anchor.setHTML(Util.imageItemHTML("img/menuitem_childs.gif", path, "top")); anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { CommonUI.openPath(path, null); } }); anchor.setStyleName("okm-KeyMap-ImageHover"); return anchor; } /** * drawMailWithAttachment */ private Anchor drawMailWithAttachment(String convertedPath, final String path) { Anchor anchor = new Anchor(); anchor.setHTML(Util.imageItemHTML("img/email_attach.gif", convertedPath, "top")); anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { CommonUI.openPath(Util.getParent(path), path); } }); anchor.setStyleName("okm-KeyMap-ImageHover"); return anchor; } /** * removeAllRows */ public void removeAllRows() { table.removeAllRows(); } }
package com.common.pojo; /** * @author GanZhen * @version 2017- 05- 11 11:05 * @description 数据库通用参数的主键值,使用主键查询的效率比使用 * varchar类型的key速度快很多 * @copyright www.zhgtrade.com */ public class CommonParamsId { /** * 非法头像的图片主键id */ public static final Long ILLEGALITY_HEADER = 1L; public static final Long USERSYS_BASE = 2L; public static final Long USERSYS_APP_ID = 3L; public static final Long USERSYS_APP_SECRET = 4L; public static final Long USERSYS_REGISTER_URL = 5L; public static final Long USERSYS_LOGIN_URL = 6L; public static final Long USERSYS_SYN_URL = 7L; public static final Long BASE_TRADE_URL = 8L; public static final Long TRADE_OUTBTCADDRESS_URL = 9L; public static final Long TRADE_ADDRESS_URL = 10L; public static final Long TRADE_REST_MONEY_URL = 11L; public static final Long TRADE_MODIFYWITHDRAWBTCADDR_URL = 12L; public static final Long TRADE_COINOPERATE_URL = 13L; public static final Long TRADE_WITHDRAWBTC_URL = 14L; public static final Long TRADE_SMS_URL = 15L; public static final Long TRADE_EXCHANGE_URL = 16L; public static final Long PLATFORM_RATE = 17L; public static final Long EXPRESS_QUERY_INTERVAL_ID = 18L; public static final Long MONEY_TO_POINT_RATE_ID = 19L; public static final Long TRADE_USER_LOGIN_URL = 20L; public static final Long USER_SYSTEM_ENABLE = 21L; public static final Long USER_SYS_IPS = 22L; public static final Long TRANSFER_SECRET = 23L; public static final Long USER_TRANSFER_SYSTEM_TAG = 24L; public static final Long USER_TRANSFER_COIN_ENABLE_URL = 25L; public static final Long USER_TRANSFER_URL = 26L; public static final Long CHANGE_ACCOUNT = 27L; public static final Long MINWITHDRAW = 28L; public static final Long MAXWITHDRAW = 29L; public static final Long DAY_DRAW_COIN_TIMES = 30L; public static final Long MESSAGE_NAME = 31L; public static final Long MESSAGE_PASSWORD = 32L; public static final Long EXPRESS_FEE = 33L; public static final Long DEFAULT_EXPRESS = 34L; }
package be.klak.whatsthat.domain; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; @Entity public class Rebus { @Id private Long id; private Drawing drawing; private String answer; public Rebus() { } public Rebus(Drawing drawing, String answer) { this.drawing = drawing; this.answer = answer; } public void setDrawing(Drawing drawing) { this.drawing = drawing; } public void setAnswer(String answer) { this.answer = answer; } public Drawing getDrawing() { return drawing; } public String getAnswer() { return answer; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } }
package com.ds.algo.matters.tree; import java.util.ArrayList; import java.util.LinkedList; public class KthSmallestBST { private static ArrayList<Integer> list = new ArrayList<>(); public static void main(String[] args){ TreeNode root = new TreeNode(5); root.left = new TreeNode(3); root.right = new TreeNode(6); root.left.left = new TreeNode(2); root.left.right = new TreeNode(4); root.left.left.left = new TreeNode(1); System.out.println(kthSmallestIterative(root, 3)); } /** This method will find kth smallest element in BST * Problem Link - https://leetcode.com/problems/kth-smallest-element-in-a-bst/ **/ private static int kthSmallest(TreeNode root, int k) { inorder(root); return list.get(k - 1); } private static void inorder(TreeNode root){ if(root == null) return; inorder(root.left); list.add(root.data); inorder(root.right); } /** This method will find kth smallest element in BST using iterative method **/ private static int kthSmallestIterative(TreeNode root, int k){ LinkedList<TreeNode> stack = new LinkedList<>(); while (true){ while (root != null){ stack.add(root); root = root.left; } root = stack.removeLast(); System.out.println(root.data); if (--k == 0) return root.data; root = root.right; } } }
package br.com.tomioka.vendashortalicas.controllers; import br.com.tomioka.vendashortalicas.dto.ProdutoDto; import br.com.tomioka.vendashortalicas.models.Produto; import br.com.tomioka.vendashortalicas.services.ProdutoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/produtos") public class ProdutoController { @Autowired private ProdutoService service; @GetMapping("/{id}") public ResponseEntity<Produto> find(@PathVariable Long id) { Optional<Produto> produto = service.find(id); if (produto.isPresent()) return ResponseEntity.ok().body(produto.get()); else return ResponseEntity.notFound().build(); } @GetMapping public ResponseEntity<List<Produto>> findAll() { List<Produto> produtos = service.findAll(); return ResponseEntity.ok().body(produtos); } @PostMapping @Transactional public ResponseEntity<?> create(@RequestBody ProdutoDto dao) { service.save(dao); return ResponseEntity.ok().build(); } }
package com.cskaoyan.service; import com.cskaoyan.bean.PCountCheck; import com.cskaoyan.bean.PMeasureCheck; import com.cskaoyan.bean.QueryStatus; import java.util.List; /** * @auther 芮狼Dan * @date 2019-05-20 00:29 */ public interface PCountCheckService { List<PCountCheck> findList(Integer rows, int offset); List<PCountCheck> findAllList(); QueryStatus insert(PCountCheck pCountCheck); QueryStatus updateAll(PCountCheck pCountCheck); QueryStatus updateNote(String pCountCheckId, String note); QueryStatus deleteBatch(String[] ids); List<PCountCheck> searchById(String searchValue, Integer rows, int offset); List<PCountCheck> searchAllById(String searchValue); }
package com.jobboardmount; import net.thucydides.jbehave.ThucydidesJUnitStories; /** * Created with IntelliJ IDEA. * User: admin * Date: 10.10.13 * Time: 22:12 * To change this template use File | Settings | File Templates. */ public class JBehaveTestSuite extends ThucydidesJUnitStories { }
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.mgmt.generator; import org.jboss.mgmt.annotation.RootResource; import javax.lang.model.type.DeclaredType; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ final class RootResourceBuilderImpl extends GeneralResourceBuilderImpl<RootResourceBuilderImpl> implements RootResourceBuilder { private final Session session; private String namespace; private String version = "1.0"; private String schemaLocation; private RootResource.Kind kind = RootResource.Kind.EXTENSION; RootResourceBuilderImpl(final Session session, final String type, final DeclaredType resourceInterface) { super(type, resourceInterface); this.session = session; } public RootResourceBuilder schemaLocation(final String schemaLocation) { this.schemaLocation = schemaLocation; return this; } public RootResourceBuilder version(final String version) { this.version = version; return this; } public RootResourceBuilder kind(final RootResource.Kind kind) { this.kind = kind; return this; } public RootResourceBuilder namespace(final String namespace) { this.namespace = namespace; return this; } public Session end() { return session; } String getNamespace() { return namespace; } String getVersion() { return version; } String getSchemaLocation() { return schemaLocation; } RootResource.Kind getKind() { return kind; } }
package com.snow.gk.core.ui.elements.impl; import com.google.common.base.Function; import com.snow.gk.core.exception.CustomException; import com.snow.gk.core.log.Assert; import com.snow.gk.core.log.Logger; import com.snow.gk.core.ui.drivers.DriverSetup; import com.snow.gk.core.ui.elements.IElement; import com.snow.gk.core.utils.Config; import com.snow.gk.core.utils.Constants; import com.snow.gk.core.utils.JSExecutor; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.asserts.Assertion; import java.time.Duration; import static com.snow.gk.core.utils.JSExecutor.getJavaScriptExec; public class Element implements IElement { protected WebElement element; protected WebDriver driver; public String elementOriginalName = ""; protected long duration = Long.parseLong(Config.getConfig().getConfigProperty(Constants.ELEMENTWAITTIME)); public Element(){ getInitializedDriver(); } public Element(WebElement element) { this.element = element; getInitializedDriver(); } public Element(WebElement element, String elementName) { this.element = element; elementOriginalName = elementName; getInitializedDriver(); } private void getInitializedDriver() { driver = DriverSetup.getDriver(); } @Override public WebElement getElement() { return element; } @Override public boolean waitforPageLoadJS() { return new WebDriverWait(driver, 10000) .until(new java.util.function.Function<WebDriver, Boolean>() { public Boolean apply(WebDriver webDriver) { return ("complete").equals(getJavaScriptExec().executeScript("return document.readyState")); } }); } @Override public WebElement waitForPresent() { try { return new FluentWait<>(driver).withTimeout(Duration.ofSeconds(duration)) .ignoring(NoSuchElementException.class, StaleElementReferenceException.class) .pollingEvery(Duration.ofSeconds(1)) .until(elementEnabled()); } catch (Exception e) { throw new CustomException("Element: "+element+" not found " + e); } } public Function<WebDriver, WebElement> elementEnabled() { return new Function<WebDriver, WebElement>() { @Override public WebElement apply(WebDriver input) { boolean isPresent = element.isDisplayed() && element.isEnabled(); if (isPresent) { return element; } else { return null; } } }; } @Override public boolean click() { try { if(waitForPresent() != null) { element.click(); return true; } else { Logger.error(Constants.FORMATTER + Constants.ELEMENTLOGMESSAGE + elementOriginalName + Constants.ISLOADEDLOGMESSAGE_FAILURE); return false; } } catch (Exception fe) { Logger.error(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " getText() of Element class"); return false; } } @Override public boolean isElementLoaded() { try { boolean flag = false; if (waitForPresent() != null) { flag = true; Logger.info(Constants.ELEMENTLOGMESSAGE + elementOriginalName + " loaded"); } else { Assert.assertFalse(true, Constants.ELEMENTLOGMESSAGE + elementOriginalName + Constants.ISLOADEDLOGMESSAGE_FAILURE); } return flag; } catch (CustomException ex) { Logger.error(Constants.FORMATTER + Constants.ELEMENTLOGMESSAGE + elementOriginalName + Constants.ISLOADEDLOGMESSAGE_FAILURE); throw new CustomException("Element: " + elementOriginalName + " not loaded"+ex); } } @Override public boolean jsClick() { try { if (isLoaded()) { JSExecutor.jsClick(element); return true; } else { Logger.error(Constants.FORMATTER + Constants.ELEMENTLOGMESSAGE + elementOriginalName + Constants.ISLOADEDLOGMESSAGE_FAILURE); return false; } } catch (Exception fe) { Logger.error(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " getText() of Element class"); return false; } } public boolean isLoaded() { try { boolean flag = false; if (waitForPresent() != null) { flag = true; Logger.info(Constants.ELEMENTLOGMESSAGE + elementOriginalName + " loaded"); } else { Assert.assertFalse(true, Constants.ELEMENTLOGMESSAGE + elementOriginalName + Constants.ISLOADEDLOGMESSAGE_FAILURE); } return flag; } catch (CustomException ex) { Logger.error(Constants.FORMATTER + Constants.ELEMENTLOGMESSAGE + elementOriginalName + Constants.ISLOADEDLOGMESSAGE_FAILURE); throw new CustomException("Element: " + elementOriginalName + " not loaded " + ex); } } @Override public boolean isDisplayed() { boolean flag = false; try { if (element.isDisplayed()) { flag = true; } else { flag = false; } } catch (Exception fe) { Logger.error(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " isDisplayed() of Element class"); return false; } return flag; } @Override public String getText() { try { if (isLoaded()) { String text = null; if (getAttribute("value") != null) text = getAttribute("value"); Logger.info(Constants.ELEMENTLOGMESSAGE + elementOriginalName + " get text successfully"); return text; } else { Logger.error(Constants.FORMATTER + Constants.ELEMENTLOGMESSAGE + elementOriginalName + " failed to get text"); throw new CustomException("Element Element: " + elementOriginalName + " not loaded in method getText()"); } } catch (Exception fe) { Logger.error(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " getText() of Element class"); throw new CustomException(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " getText() of Element class." + fe); } } @Override public String getAttribute(String value) { try { return java.util.Optional.ofNullable(getElement().getAttribute("value")).orElse(""); } catch (Exception fe) { Logger.error(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " getAttribute() of Element class"); throw new CustomException(Constants.FORMATTER + Constants.FAILURE_METHOD_MESSAGE + " getAttribute() of Element class." + fe); } } @Override public boolean isEditable() throws CustomException { return element.isEnabled(); } }
package BD; import UML.Partido; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; /** * * @author Luis H. Alves */ public class tablaPartidos { private static Connection con; public static void crearPartido(Partido p) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); PreparedStatement ps = con.prepareStatement("INSERT INTO PARTIDOS (HORA, IDJO0RNADA) VALUES (?, ?, ?)"); ps.setTime(1, java.sql.Time.valueOf(p.getHora())); ps.setInt(2, p.getJornada().getIdJornada()); int n = ps.executeUpdate(); if(n != 1) throw new Exception("Se ha insertado más de un Partido."); System.out.println("Partido insertado con exito."); BaseDatos.desconectar(); } public static void modHoraPartiddo(Partido p) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); PreparedStatement ps = con.prepareStatement("UPDATE PARTIDOS SET HORA = ? WHERE IDPARTIDO = ?"); ps.setTime(1, java.sql.Time.valueOf(p.getHora())); ps.setInt(2, p.getIdPartido()); int n = ps.executeUpdate(); BaseDatos.desconectar(); if( n > 1) throw new Exception("Se ha modificado mas de un Partido."); } public static void eliminarPartido(Partido p) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); PreparedStatement ps = con.prepareStatement("DELETE FROM PARTIDOS WHERE IDPARTIDO = ?"); ps.setInt(1, p.getIdPartido()); int n = ps.executeUpdate(); BaseDatos.desconectar(); if( n > 1) throw new Exception("Se ha eliminado mas de una Partido"); } public static Partido partidoById(int idPartido) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); PreparedStatement ps = con.prepareStatement("SELECT * FROM PARTIDOS WHERE IDPARTIDO = ?"); ps.setInt(1, idPartido); ResultSet resultado = ps.executeQuery(); Partido p = new Partido(); p.setIdPartido(resultado.getInt("IDPARTIDO")); p.setHora(resultado.getTime("HORA").toLocalTime()); p.setJornada(tablaJornadas.jornadaByIdJornada(resultado.getString("IDJORNADA"))); BaseDatos.desconectar(); return p; } public static ArrayList<Partido> allPartidos() throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); PreparedStatement ps = con.prepareStatement("SELECT * FROM PARTIDOS"); ResultSet resultado = ps.executeQuery(); ArrayList<Partido> listaPartidos= new ArrayList(); while(resultado.next()){ Partido p = new Partido(); p.setIdPartido(resultado.getInt("IDPARTIDO")); p.setHora(resultado.getTime("HORA").toLocalTime()); p.setJornada(tablaJornadas.jornadaByIdJornada(resultado.getString("IDJORNADA"))); listaPartidos.add(p); } BaseDatos.desconectar(); if(!listaPartidos.isEmpty()){ return listaPartidos; } else{ return null; } } public static ArrayList<Partido> partidosByIdJornada(int idJornada) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); PreparedStatement ps = con.prepareStatement("SELECT * FROM PARTIDOS WHERE IDJORNADA = ?"); ps.setInt(1, idJornada); ResultSet resultado = ps.executeQuery(); ArrayList<Partido> listaPartidos= new ArrayList(); while(resultado.next()){ Partido p = new Partido(); p.setIdPartido(resultado.getInt("IDPARTIDO")); p.setHora(resultado.getTime("HORA").toLocalTime()); p.setJornada(tablaJornadas.jornadaByIdJornada(resultado.getString("IDJORNADA"))); listaPartidos.add(p); } BaseDatos.desconectar(); if(listaPartidos.isEmpty()){ return null; } return listaPartidos; } }
package com.home.neo4j; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.neo4j.kernel.GraphDatabaseAPI; import org.neo4j.server.WrappingNeoServerBootstrapper; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.configuration.ServerConfigurator; import org.neo4j.shell.ShellSettings; import org.neo4j.unsafe.batchinsert.BatchInserter; public class Neo4JServer { public static void main(String[] args) { BatchInserter ba = null; // BatchInserters.inserter GraphDatabaseAPI graphdb = (GraphDatabaseAPI) new GraphDatabaseFactory() .newEmbeddedDatabaseBuilder( "/home/pubmatic/Downloads/neo4j-community-2.2.2/data/Neo4jDB.db" ) .setConfig( ShellSettings.remote_shell_enabled, "true" ) .newGraphDatabase(); ServerConfigurator config; config = new ServerConfigurator( graphdb ); // let the server endpoint be on a custom port config.configuration().setProperty(Configurator.WEBSERVER_PORT_PROPERTY_KEY, 7575 ); WrappingNeoServerBootstrapper srv; srv = new WrappingNeoServerBootstrapper( graphdb, config ); srv.start(); } }
package com.TelRan.course.application; import com.TelRan.course.model.ListData; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import java.io.File; public class ListHelper extends HelperBase { public ListHelper(WebDriver wd) { super(wd); } public void enterNewListName(ListData listData) { wd.findElement(By.xpath("//textarea[@class='list-header-name mod-list-name js-list-name-input']")).clear(); wd.findElement(By.xpath("//textarea[@class='list-header-name mod-list-name js-list-name-input']")).sendKeys(listData.getNewname()); } public void selectListTitle() { wd.findElement(By.xpath("//div[@class='list-header-target js-editing-target']")).click(); } public void enterListName(ListData listData) { wd.findElement(By.xpath("//input[@class='list-name-input']")).click(); wd.findElement(By.xpath("//input[@class='list-name-input']")).clear(); wd.findElement(By.xpath("//input[@class='list-name-input']")).sendKeys(listData.getName()); } public void clickAddList() { wd.findElement(By.cssSelector("span.placeholder.js-open-add-list")).click(); } public void clickSaveButton() { wd.findElement(By.xpath("//input[@class='primary mod-list-add-button js-save-edit']")).click(); } public void clickArchiveThisList() { wd.findElement(By.cssSelector("a.js-close-list")).click(); } public void clickListMenuButton() { wd.findElement(By.xpath("//span[@class='icon-sm icon-overflow-menu-horizontal']")).click(); } }
package ar.edu.utn.frlp.app.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.util.List; @Entity @Table(name = "COLUMN_BOARD") public class ColumnBoard { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "order_board") private Integer order; @ManyToOne private Board board; @OneToMany(mappedBy = "columnBoard") @JsonIgnoreProperties(value = {"columnBoard"}, allowSetters = true) private List<Card> cards; public ColumnBoard() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public List<Card> getCards() { return cards; } public void setCards(List<Card> cards) { this.cards = cards; } }
package partitioning.jobs; import java.io.IOException; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import common.Config; public class ReplacePredId { public static class Map extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); if (!StringUtils.isBlank(line)) { String[] data = StringUtils.split(line, Config.VerticesSeparator); String[] so = ArrayUtils.EMPTY_STRING_ARRAY; so = (String[]) ArrayUtils.add(so, data[0]); so = (String[]) ArrayUtils.add(so, data[2]); if (!ArrayUtils.isEmpty(data)) { context.write(new Text(data[1]), new Text(StringUtils.join(so, Config.VerticesSeparator))); } } } } public static class LookUpMap extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); if (!StringUtils.isBlank(line)) { String[] data = StringUtils.split(line, Config.VerticesSeparator); if (!ArrayUtils.isEmpty(data)) { context.write(new Text(data[0]), new Text(data[1])); } } } } public static class Red extends Reducer<Text, Text, Text, NullWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String subject = StringUtils.EMPTY; String object = StringUtils.EMPTY; long pid = -1; for (Text value : values) { if (!StringUtils.contains(value.toString(), Config.VerticesSeparator)) { pid = Long.parseLong(value.toString()); } else { subject = StringUtils.split(value.toString(), Config.VerticesSeparator)[0]; object = StringUtils .split(value.toString(), Config.VerticesSeparator)[1]; } if (!StringUtils.isBlank(subject) && !StringUtils.isBlank(object) && pid != -1) { context.write( new Text(subject + Config.VerticesSeparator + String.valueOf(pid) + Config.VerticesSeparator + object), null); } } } } }
package org.terasoluna.gfw.examples.common.domain.service; import org.terasoluna.gfw.examples.common.domain.model.Article; public interface ArticleSharedService { Article createArticle(Article article, boolean usingSequencer); }
package redis.as.message.broker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.CountDownLatch; @Component public class Receiver { private Logger logger = LoggerFactory.getLogger(getClass()); private CountDownLatch latch; @Autowired public Receiver(CountDownLatch latch) { this.latch = latch; } public void onReceive(String message){ logger.info("receive message:{}", message); latch.countDown(); } }
package com.tibco.as.io; public interface IExecutorListener { void executing(ITransfer transfer); void executed(ITransfer transfer); }
/* * Copyright (c) 2009-2011 by Jan Stender, Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.mrc.osdselection; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.util.Properties; import org.xtreemfs.foundation.LRUCache; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; /** * Base class for policies that use datacenter maps. * * @author bjko, stender */ public abstract class DCMapPolicyBase implements OSDSelectionPolicy { public static final String CONFIG_FILE_PATH = "/etc/xos/xtreemfs/datacentermap"; protected int[][] distMap; protected Inet4AddressMatcher[][] matchers; protected LRUCache<Inet4Address, Integer> matchingDCcache; private boolean initialized; public DCMapPolicyBase() { try { File f = new File(CONFIG_FILE_PATH); Properties p = new Properties(); p.load(new FileInputStream(f)); readConfig(p); int maxCacheSize = Integer.valueOf(p.getProperty("max_cache_size", "1000").trim()); matchingDCcache = new LRUCache<Inet4Address, Integer>(maxCacheSize); initialized = true; } catch (IOException ex) { Logging.logMessage(Logging.LEVEL_WARN, Category.misc, this, "cannot load %s, DCMap replica selection policy will not work", CONFIG_FILE_PATH); Logging.logError(Logging.LEVEL_WARN, this, ex); initialized = false; } } public DCMapPolicyBase(Properties p) { readConfig(p); int maxCacheSize = Integer.valueOf(p.getProperty("max_cache_size", "1000")); matchingDCcache = new LRUCache<Inet4Address, Integer>(maxCacheSize); initialized = true; } private void readConfig(Properties p) { String tmp = p.getProperty("datacenters"); if (tmp == null) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": a list of datacenters must be specified in the configuration"); } final String[] dcs = tmp.split(","); if (dcs.length == 0) { Logging.logMessage(Logging.LEVEL_WARN, this, "no datacenters specified"); return; } for (int i = 0; i < dcs.length; i++) { if (!dcs[i].matches("[a-zA-Z0-9_]+")) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": datacenter name '" + dcs[i] + "' is invalid"); } } distMap = new int[dcs.length][dcs.length]; matchers = new Inet4AddressMatcher[dcs.length][]; for (int i = 0; i < dcs.length; i++) { for (int j = i + 1; j < dcs.length; j++) { String distStr = p.getProperty("distance." + dcs[i] + "-" + dcs[j]); if (distStr == null) { distStr = p.getProperty("distance." + dcs[j] + "-" + dcs[i]); } if (distStr == null) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": distance between datacenter '" + dcs[i] + "' and '" + dcs[j] + "' is not specified"); } try { distMap[i][j] = distMap[j][i] = Integer.valueOf(distStr); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": distance '" + distStr + "' between datacenter '" + dcs[i] + "' and '" + dcs[j] + "' is not a valid integer"); } } // evaluate the address ranges for the data centers String dcMatch = p.getProperty("addresses." + dcs[i]); if (dcMatch == null) dcMatch = p.getProperty(dcs[i] + ".addresses"); if (dcMatch == null) { matchers[i] = new Inet4AddressMatcher[0]; // allow empty datacenters Logging.logMessage(Logging.LEVEL_WARN, this, "datacenter '" + dcs[i] + "' has no entries!"); } else { String entries[] = dcMatch.split(","); matchers[i] = new Inet4AddressMatcher[entries.length]; for (int e = 0; e < entries.length; e++) { final String entry = entries[e]; if (entry.contains("/")) { // network match try { String ipAddr = entry.substring(0, entry.indexOf("/")); String prefix = entry.substring(entry.indexOf("/") + 1); Inet4Address ia = (Inet4Address) InetAddress.getByName(ipAddr); matchers[i][e] = new Inet4AddressMatcher(ia, Integer.valueOf(prefix)); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": netmask in '" + entry + "' for datacenter '" + dcs[i] + "' is not a valid integer"); } catch (Exception ex) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": address '" + entry + "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address"); } } else { // IP match try { Inet4Address ia = (Inet4Address) InetAddress.getByName(entry); matchers[i][e] = new Inet4AddressMatcher(ia); } catch (Exception ex) { throw new IllegalArgumentException("Cannot initialize " + this.getClass().getSimpleName() + ": address '" + entry + "' for datacenter '" + dcs[i] + "' is not a valid IPv4 address"); } } } } } } protected int getDistance(Inet4Address addr1, Inet4Address addr2) { if(!initialized) return 0; final int dc1 = getMatchingDC(addr1); final int dc2 = getMatchingDC(addr2); if ((dc1 != -1) && (dc2 != -1)) { return distMap[dc1][dc2]; } else { return Integer.MAX_VALUE; } } protected int getMatchingDC(Inet4Address addr) { if(!initialized) return -1; Integer cached = matchingDCcache.get(addr); if (cached == null) { for (int i = 0; i < matchers.length; i++) { for (int j = 0; j < matchers[i].length; j++) { if (matchers[i][j].matches(addr)) { matchingDCcache.put(addr, i); return i; } } } matchingDCcache.put(addr, -1); return -1; } else { return cached; } } }
package com.github.limboc.sample.ui.item; /** * Created by Chen on 2016/3/11. */ public interface OnItemClickListener { void onClick(int position); }
package com.tencent.mm.plugin.soter.b; import com.tencent.mm.ab.j; import com.tencent.mm.plugin.soter.b.c.a; import com.tencent.mm.protocal.k.d; import com.tencent.mm.protocal.k.e; final class b extends j { a ont = new a(); com.tencent.mm.plugin.soter.b.c.b onu = new com.tencent.mm.plugin.soter.b.c.b(); b() { } public final int getType() { return 627; } public final String getUri() { return "/cgi-bin/micromsg-bin/updatesoteraskrsa"; } public final e Id() { return this.onu; } protected final d Ic() { return this.ont; } public final int KP() { return 1; } }
/** * @author Simone Notargiacomo, Giuseppe Schipani */ package taskspider.data.document; import java.util.Vector; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import websphinx.Element; import websphinx.Page; /** * @author Simone Notargiacomo, Giuseppe Schipani * */ public class DocsManager { private Vector<Document> docs; private Document tempDoc; private String url; private String title; private String description; private String keywords; private String keyphrases; private String body; private Element[] elements; public DocsManager() { docs = new Vector<Document>(); } public Document addDocument(Page page) { tempDoc = new Document(); url = page.getOrigin().toURL(); tempDoc.add(new Field("url", url, Field.Store.YES, Field.Index.TOKENIZED)); if((title = page.getTitle())!=null) { tempDoc.add(new Field("title", title, Field.Store.YES, Field.Index.TOKENIZED)); } if((elements=page.getElements())!=null) { description=getTagContent("meta", "description", elements); if(description!=null) tempDoc.add(new Field("description", description, Field.Store.YES, Field.Index.TOKENIZED)); } if((elements=page.getElements())!=null) { keywords=getTagContent("meta", "keywords", elements); if(keywords!=null) tempDoc.add(new Field("keywords", keywords, Field.Store.YES, Field.Index.TOKENIZED)); } if((elements=page.getElements())!=null) { keyphrases=getTagContent("meta", "keyphrases", elements); if(keyphrases!=null) tempDoc.add(new Field("keyphrases", keyphrases, Field.Store.YES, Field.Index.TOKENIZED)); } if((elements=page.getElements())!=null) { body=this.getTagContent("body", elements); if(body!=null) { body = body.replaceAll("[\\w&&[\\S]]*[\\W&&[\\S]]+[\\w&&[\\S]]*", ""); System.out.println("body: "+body); tempDoc.add(new Field("body", body, Field.Store.YES, Field.Index.TOKENIZED)); } } tempDoc.add(new Field("date", String.valueOf(page.getExpiration()), Field.Store.YES, Field.Index.TOKENIZED)); if(!isPresent(tempDoc)) { docs.add(tempDoc); } return tempDoc; } private boolean isPresent(Document doc) { for(int i=0; i<docs.size(); i++) { if(docs.get(i).get("url").equals(doc.get("url"))) return true; } return false; } private String getTagContent(String tagName, String attribute, Element[] elems) { if(elems!=null) { for(int i=0; i<elems.length; i++) { if(elems[i].getTagName().equals(tagName)) { if(attribute!=null && elems[i].getHTMLAttribute("name")!=null) { //System.out.println("tag: "+elems[i].getTagName()+", attr: "+elems[i].getHTMLAttribute("name")); if(elems[i].getHTMLAttribute("name").equals(attribute)) return elems[i].getHTMLAttribute("content"); else continue; } else if(attribute!=null) continue; else { return elems[i].toText(); } } } } return null; } private String getTagContent(String tagName, Element[] elems) { if(elems!=null) { for(int i=0; i<elems.length; i++) { if(elems[i].getTagName().equals(tagName)) { return elems[i].toText(); } } } return null; } public Document getDocument(int index) { if(index > docs.size()) return null; return docs.get(index); } public Document delDocument(int index) { if(index > docs.size()) return null; return docs.remove(index); } public void clearDocs() { docs.clear(); } public Vector<Document> getDocs() { return docs; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.Progressable; /** * An {@link OutputFormat} that writes keys, values to * {@link SequenceFile}s in binary(raw) format * * @deprecated Use * {@link org.apache.hadoop.mapreduce.lib.output.SequenceFileAsBinaryOutputFormat} * instead */ @Deprecated @InterfaceAudience.Public @InterfaceStability.Stable public class SequenceFileAsBinaryOutputFormat extends SequenceFileOutputFormat <BytesWritable,BytesWritable> { /** * Inner class used for appendRaw */ static protected class WritableValueBytes extends org.apache.hadoop.mapreduce .lib.output.SequenceFileAsBinaryOutputFormat.WritableValueBytes { } /** * Set the key class for the {@link SequenceFile} * <p>This allows the user to specify the key class to be different * from the actual class ({@link BytesWritable}) used for writing </p> * * @param conf the {@link JobConf} to modify * @param theClass the SequenceFile output key class. */ static public void setSequenceFileOutputKeyClass(JobConf conf, Class<?> theClass) { conf.setClass(org.apache.hadoop.mapreduce.lib.output. SequenceFileAsBinaryOutputFormat.KEY_CLASS, theClass, Object.class); } /** * Set the value class for the {@link SequenceFile} * <p>This allows the user to specify the value class to be different * from the actual class ({@link BytesWritable}) used for writing </p> * * @param conf the {@link JobConf} to modify * @param theClass the SequenceFile output key class. */ static public void setSequenceFileOutputValueClass(JobConf conf, Class<?> theClass) { conf.setClass(org.apache.hadoop.mapreduce.lib.output. SequenceFileAsBinaryOutputFormat.VALUE_CLASS, theClass, Object.class); } /** * Get the key class for the {@link SequenceFile} * * @return the key class of the {@link SequenceFile} */ static public Class<? extends WritableComparable> getSequenceFileOutputKeyClass(JobConf conf) { return conf.getClass(org.apache.hadoop.mapreduce.lib.output. SequenceFileAsBinaryOutputFormat.KEY_CLASS, conf.getOutputKeyClass().asSubclass(WritableComparable.class), WritableComparable.class); } /** * Get the value class for the {@link SequenceFile} * * @return the value class of the {@link SequenceFile} */ static public Class<? extends Writable> getSequenceFileOutputValueClass(JobConf conf) { return conf.getClass(org.apache.hadoop.mapreduce.lib.output. SequenceFileAsBinaryOutputFormat.VALUE_CLASS, conf.getOutputValueClass().asSubclass(Writable.class), Writable.class); } @Override public RecordWriter <BytesWritable, BytesWritable> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { // get the path of the temporary output file Path file = FileOutputFormat.getTaskOutputPath(job, name); FileSystem fs = file.getFileSystem(job); CompressionCodec codec = null; CompressionType compressionType = CompressionType.NONE; if (getCompressOutput(job)) { // find the kind of compression to do compressionType = getOutputCompressionType(job); // find the right codec Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, DefaultCodec.class); codec = ReflectionUtils.newInstance(codecClass, job); } final SequenceFile.Writer out = SequenceFile.createWriter(fs, job, file, getSequenceFileOutputKeyClass(job), getSequenceFileOutputValueClass(job), compressionType, codec, progress); return new RecordWriter<BytesWritable, BytesWritable>() { private WritableValueBytes wvaluebytes = new WritableValueBytes(); public void write(BytesWritable bkey, BytesWritable bvalue) throws IOException { wvaluebytes.reset(bvalue); out.appendRaw(bkey.getBytes(), 0, bkey.getLength(), wvaluebytes); wvaluebytes.reset(null); } public void close(Reporter reporter) throws IOException { out.close(); } }; } @Override public void checkOutputSpecs(FileSystem ignored, JobConf job) throws IOException { super.checkOutputSpecs(ignored, job); if (getCompressOutput(job) && getOutputCompressionType(job) == CompressionType.RECORD ){ throw new InvalidJobConfException("SequenceFileAsBinaryOutputFormat " + "doesn't support Record Compression" ); } } }
package com.feecalculator.feecalculatorApp; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; import com.feecalculator.feecalculatorApp.Service.GenerateFeeReportService; @Component public class CommandLineAppStartupRunner implements CommandLineRunner { @Autowired GenerateFeeReportService generateFee; @Override public void run(String... arg0) throws Exception { generateFee.generateReport(); } }
package cn.yansui.constant; /** * @Description 常量 * @Author maogen.ymg * @Date 2020/2/24 21:49 */ public class VenusConstant { private VenusConstant() {} public static final String MAIN_FXML_PATH = "\\fxml\\Main.fxml"; public static final String ICON_URL = "/images/logo/logo.png"; /***************************** Title ********************************/ public static final String MAIN_TITLE = "算法"; public static final String FILE_STRUCT_TITLE = "文件结构分析"; /***************************** View ********************************/ public static final String FILE_VIEW_CLASS = "cn.yansui.module.file.view.FileView"; public static final String FILE_LOCAL_VIEW_CLASS = "cn.yansui.module.file.view.LocalDataView"; public static final String FILE_ONLINE_VIEW_CLASS = "cn.yansui.module.file.view.OnlineDataView"; public static final String QUERY_VIEW_CLASS = "cn.yansui.module.query.view.QueryView"; public static final String QUERY_TIME_VIEW_CLASS = "cn.yansui.module.query.view.QueryTimeView"; public static final String QUERY_DIST_VIEW_CLASS = "cn.yansui.module.query.view.QueryDistView"; public static final String QUERY_USER_VIEW_CLASS = "cn.yansui.module.query.view.QueryUserView"; public static final String QUERY_LOCATION_VIEW_CLASS = "cn.yansui.module.query.view.QueryLocationView"; public static final String ANALYSIS_VIEW_CLASS = "cn.yansui.module.analysis.view.AnalysisView"; public static final String ANALYSIS_DBSCAN_VIEW_CLASS = "cn.yansui.module.analysis.view.DbScanView"; public static final String ANALYSIS_OUTLIER_DETECT_VIEW_CLASS = "cn.yansui.module.analysis.view.OutlierDetectView"; public static final String VISUAL_VIEW_CLASS = "cn.yansui.module.visualization.view.VisualizeView"; public static final String VISUAL_TRACK_VIEW_CLASS = "cn.yansui.module.visualization.view.VisualTrackView"; public static final String VISUAL_OUTLIER_VIEW_CLASS = "cn.yansui.module.visualization.view.VisualOutlierView"; public static final String VISUAL_DBSCAN_VIEW_CLASS = "cn.yansui.module.visualization.view.VisualDbScanView"; public static final String ABOUT_VIEW_CLASS = "cn.yansui.module.login.view.ForgetView"; public static final double EARTH_RADIUS_IN_METERS = 6378137.0; }
package com.ht.springboot_power; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @MapperScan(basePackages = { "com.ht.springboot_power.mapper" }) @ServletComponentScan public class SpringbootPowerApplication { public static void main(String[] args) { SpringApplication.run(SpringbootPowerApplication.class, args); } }
package com.inaryzen.easyproperties; import org.junit.Assert; import org.junit.Test; /** * Created by inaryzen on 10/10/2016. */ public class PropertyTest { @Test public void write() throws Exception { Property property = new Property(); property.setter = TestClass.class.getMethod("setPrice", double.class); property.setWriteConverter(Double::parseDouble); TestClass testClass = new TestClass(); property.write(testClass, "42.999"); Assert.assertEquals(42.999, testClass.getPrice(), 0.0); } @Test public void read() throws Exception { Property property = new Property(); property.getter = TestClass.class.getMethod("getPrice"); property.setReadConverter(d -> Double.toString((Double)d)); TestClass testClass = new TestClass(); testClass.setPrice(42.999); String price = property.read(testClass); Assert.assertEquals("42.999", price); } public static class TestClass { private double price; public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } }
package com.marvl.imt_lille_douai.marvl.comparison.usage; import com.marvl.imt_lille_douai.marvl.comparison.tools.DisplayTools; public class HowToDisplayAndUse { public void diplay() { // Display SIFT Matching between the 2 images //DisplayTools.displayComparisonBetweenTwoImage("CocaLogo_1.jpg","CocaLogo_2.png"); // Display the best matching of Coca_1.jpg compared to all the DataBank images //DisplayTools.displayBestImageInDataBankComparedTo("Coca_1.jpg"); // Display each top 5 best matching image of Coca_1.jpg compared to all the DataBank images (starting with the best one) + distances + best class found //DisplayTools.displayXNbOfBestImageInDataBankComparedTo("Coca_1.jpg",5); } }
package xyz.tanku.suggestionbox.sql.utils; import xyz.tanku.suggestionbox.SuggestionBox; import xyz.tanku.suggestionbox.sql.MySQLAccess; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; public class SQLUtils { private Connection connection = null; private PreparedStatement ps = null; private MySQLAccess mySQLAccess = SuggestionBox.getInstance().getMySQLAccess(); public void addSuggestion(String uuid, String suggestion) throws Exception { String fixedUuid = getFixedUUID(uuid); connection = mySQLAccess.getConnection(); ps = connection.prepareStatement( "CREATE TABLE IF NOT EXISTS ? (suggestions TEXT) INSERT INTO ? (suggestions) VALUES ('?')"); ps.setString(1, fixedUuid); ps.setString(2, fixedUuid); ps.setString(3, suggestion); ps.executeUpdate(); connection.commit(); } public static String getFixedUUID(String uuid) { /* This function is used as SQL doesn't like when dashes are in the name of the tables. */ return uuid.replace("-", "_"); } public static String getUUID(String uuid) { /* This function is used as SQL doesn't like when dashes are in the name of the tables. */ return uuid.replace("_", "-"); } public List<String> getTables() throws Exception { connection = mySQLAccess.getConnection(); ps = connection.prepareStatement("SHOW TABLES"); List<String> l = new ArrayList<>(); ResultSet set = ps.executeQuery(); connection.commit(); while (set.next()) { l.add(set.getString("Tables_in_suggestionbox")); } return l; } public List<String> getSuggestions(String uuid) throws Exception { connection = mySQLAccess.getConnection(); ps = connection.prepareStatement("SELECT suggestions FROM ?"); ps.setString(1, uuid); List<String> l = new ArrayList<>(); ResultSet set = ps.executeQuery(); connection.commit(); while (set.next()) { l.add(set.getString("suggestions")); } return l; } public Map<String, List<String>> getAllSuggestions() throws Exception { connection = mySQLAccess.getConnection(); ps = connection.prepareStatement("SELECT suggestions FROM ?"); List<String> tables = this.getTables(); Map<String, List<String>> map = new HashMap<>(); for (String str : tables) { ps.setString(1, str); ResultSet set = ps.executeQuery(); connection.commit(); List<String> l = new ArrayList<>(); while (set.next()) { l.add(set.getString("suggestions")); } map.put(str.replace("_", "-"), l); } return map; } }
/* * 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 service; import dao.PersonnelContractDAO; import dto.PersonnelContractDTO; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; /** * * @author Asus */ public class PersonnelContractService { PersonnelContractDAO perDAO= new PersonnelContractDAO(); public ArrayList<PersonnelContractDTO> getAllPersonnelContract(Connection connection, String emp_id) throws SQLException{ return perDAO.getAllPersonnelContract(connection, emp_id); } public ArrayList<PersonnelContractDTO> getAllSalaryDetails(Connection connection, String emp_id) throws SQLException{ System.out.println("7"); return perDAO.getAllSalaryDetails(connection, emp_id); } }
package android.support.design.widget; import android.support.design.widget.BottomSheetBehavior.a; class c$2 extends a { final /* synthetic */ c cM; c$2(c cVar) { this.cM = cVar; } public final void u(int i) { if (i == 5) { this.cM.dismiss(); } } public final void g(float f) { } }
package externals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static junit.framework.Assert.assertNotNull; /** * Created by Jared Ramirez on 4/4/2015. * Byte-Pushers */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = config.class) public class ExternalFileTest { @Autowired BlankDisk disk; @Test public void isNotNull(){ assertNotNull(disk); } }
package problemas; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Suma { String[] operandos; public Suma(String[] operandos) { this.operandos = operandos; } public int getNumResultados() { Map<Character, Integer> valoresLetras = new HashMap<>(); for( String l : this.operandos ) { for( char c : l.toCharArray() ) { valoresLetras.put(c, 0); } } ArrayList<Character> cl = new ArrayList<>( valoresLetras.keySet() ); ArrayList<Boolean> numerosLibres = new ArrayList<Boolean>(); for ( int i = 0; i < 10; i++ ) numerosLibres.add( true ); int numResultados = numResultadosRecursivo( valoresLetras, cl, numerosLibres, 0); return numResultados; } private int numResultadosRecursivo( Map<Character, Integer> valoresLetras, ArrayList<Character> letras, ArrayList<Boolean> numerosLibres, int indiceCaracterActual ) { if ( letras.size() <= indiceCaracterActual ) { int vv = 0; int v = 0; for( String l : this.operandos ) { v = 0; if ( valoresLetras.get( l.charAt(0) ) == 0 ) return 0; for( char c : l.toCharArray() ) { v *= 10; v += valoresLetras.get( c ); } if ( v == 0 ) return 0; vv += v; } vv -= v*2; return ( vv == 0 ) ? 1 : 0; } int numResultados = 0; for ( int n = 0; n < 10 ; n++ ) { if ( numerosLibres.get(n) ) { valoresLetras.put( letras.get( indiceCaracterActual ), n ); numerosLibres.set( n, false ); numResultados += numResultadosRecursivo(valoresLetras, letras, numerosLibres, indiceCaracterActual+1); numerosLibres.set( n, true ); } } return numResultados; } }
package com.espendwise.manta.model.view; // Generated by Hibernate Tools import com.espendwise.manta.model.ValueObject; import com.espendwise.manta.model.data.AddressData; import com.espendwise.manta.model.data.EmailData; import com.espendwise.manta.model.data.PhoneData; /** * ContactView generated by hbm2java */ public class ContactView extends ValueObject implements java.io.Serializable { private static final long serialVersionUID = -1; public static final String ADDRESS = "address"; public static final String PHONE = "phone"; public static final String FAX_PHONE = "faxPhone"; public static final String MOBILE_PHONE = "mobilePhone"; public static final String EMAIL = "email"; private AddressData address; private PhoneData phone; private PhoneData faxPhone; private PhoneData mobilePhone; private EmailData email; public ContactView() { } public ContactView(AddressData address) { this.setAddress(address); } public ContactView(AddressData address, PhoneData phone, PhoneData faxPhone, PhoneData mobilePhone, EmailData email) { this.setAddress(address); this.setPhone(phone); this.setFaxPhone(faxPhone); this.setMobilePhone(mobilePhone); this.setEmail(email); } public AddressData getAddress() { return this.address; } public void setAddress(AddressData address) { this.address = address; setDirty(true); } public PhoneData getPhone() { return this.phone; } public void setPhone(PhoneData phone) { this.phone = phone; setDirty(true); } public PhoneData getFaxPhone() { return this.faxPhone; } public void setFaxPhone(PhoneData faxPhone) { this.faxPhone = faxPhone; setDirty(true); } public PhoneData getMobilePhone() { return this.mobilePhone; } public void setMobilePhone(PhoneData mobilePhone) { this.mobilePhone = mobilePhone; setDirty(true); } public EmailData getEmail() { return this.email; } public void setEmail(EmailData email) { this.email = email; setDirty(true); } }
import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import javax.swing.JOptionPane; import java.io.BufferedReader; import java.io.BufferedWriter; public class Controller { private String file = "src\\Report.txt"; private String species; private String sex; private double weight; private double bloodPressure; private int numOfSpot; private String dentalHealth; private Animal animal; private String gpsData; public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public double getBloodPressure() { return bloodPressure; } public void setBloodPressure(double bloodPressure) { this.bloodPressure = bloodPressure; } public int getNumOfSpot() { return numOfSpot; } public void setNumOfSpot(int numOfSpot) { this.numOfSpot = numOfSpot; } public String getDentalHealth() { return dentalHealth; } public void setDentalHealth(String dentalHealth) { this.dentalHealth = dentalHealth; } public void setgpsData(String gpsData) { this.gpsData = gpsData; } ////////////////////////////////////////////////////////////////////////// public String ReportData() { String report=""; ArrayList<String> GPSline = Reading(); for(String line:GPSline) { report+=line+"\n"; } return report; } private ArrayList<String> Reading() { // Read the file ArrayList<String> lines=new ArrayList<String>(); try { BufferedReader Reader = new BufferedReader(new FileReader(file)); String sCurrentLine; while((sCurrentLine=Reader.readLine())!=null)//while stuff to read { lines.add(sCurrentLine); } Reader.close(); } catch(IOException e) { JOptionPane.showMessageDialog(null,"Failed to read a file"); System.out.println(e.getMessage());//explain error to user e.printStackTrace(); } catch(Exception e) { JOptionPane.showMessageDialog(null,"Failed to read a file"); System.out.println(e.getMessage());//explain error to user e.printStackTrace(); } return lines; } public boolean entry() { boolean valid = true; return valid; } private boolean writing(String data) { // writing data to Report.txt boolean valid = true; BufferedWriter bw = null; FileWriter fw = null; try { bw = new BufferedWriter(new FileWriter(file, true)); bw.write(data); bw.newLine(); bw.flush(); }catch(IOException e) { e.printStackTrace(); valid = false; }finally { try { if(bw !=null) bw.close(); if(fw != null) fw.close(); } catch(IOException ex) { valid = false; ex.printStackTrace(); } } return valid; } public boolean saveAnimal() { boolean isSuccess = true; //create Animal this.animal = getAnimal(); //get toString message String line = animal.stringdata(); //save to file if(!writing(line)) isSuccess = false; //return result return isSuccess; } private Animal getAnimal() { // generate animal from input if(this.species.equals("Penguins")) { return new Penguins(this.species, this.sex, this.weight, this.bloodPressure, getGPS()); }else if(this.species.equals("Sea lion")) { return new Sealions(this.species, this.sex, this.weight, this.numOfSpot, getGPS()); }else { return new Walrus(this.species, this.sex, this.weight, this.dentalHealth, getGPS()); } } private GPS getGPS() { // split gpsdata each line String[] gpsSet = gpsData.split("\n"); ArrayList<String> gps = new ArrayList<String>(); //save splited gps data in to the array for(String tmp: gpsSet) { gps.add(tmp); } return new GPS(gps); } public void reset() {// reset entry before going to first panel. species=""; sex=""; weight=0; bloodPressure=0; numOfSpot=0; dentalHealth=""; animal=null; gpsData=""; } }
package com.tencent.mm.plugin.fav.ui; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tencent.mm.e.b.j; import com.tencent.mm.plugin.fav.a.b; import com.tencent.mm.plugin.fav.a.g; import com.tencent.mm.plugin.fav.ui.m.d; import com.tencent.mm.plugin.fav.ui.m.e; import com.tencent.mm.plugin.fav.ui.m.f; import com.tencent.mm.plugin.fav.ui.m.i; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.vx; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.al.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMBaseActivity; import com.tencent.mm.ui.y; public class FavPostVoiceUI extends MMBaseActivity { private static final int[] erx = new int[]{d.amp1, d.amp2, d.amp3, d.amp4, d.amp5, d.amp6, d.amp7}; private static final int[] hnd = new int[]{0, 15, 30, 45, 60, 75, 90, 100}; private long duration; private final al erD = new al(new a() { public final boolean vD() { int maxAmplitude; int i = 0; j a = FavPostVoiceUI.this.iZl; if (a.status == 1) { maxAmplitude = a.bFv.getMaxAmplitude(); if (maxAmplitude > j.bFx) { j.bFx = maxAmplitude; } maxAmplitude = (maxAmplitude * 100) / j.bFx; } else { maxAmplitude = 0; } while (i < FavPostVoiceUI.erx.length) { if (maxAmplitude >= FavPostVoiceUI.hnd[i] && maxAmplitude < FavPostVoiceUI.hnd[i + 1]) { FavPostVoiceUI.this.hnl.setBackgroundResource(FavPostVoiceUI.erx[i]); break; } i++; } return true; } }, true); private int hmW; private final ag hnB = new 6(this); private long hng = -1; private Toast hnh; private ImageView hnl; private boolean hnt; private boolean hnu; private final al hnz = new al(new 7(this), true); private Button iZd; private long iZe; private View iZf; private View iZg; private View iZh; private View iZi; private TextView iZj; private View iZk; private j iZl; boolean iZm = false; private String path; static /* synthetic */ void j(FavPostVoiceUI favPostVoiceUI) { favPostVoiceUI.iZd.setKeepScreenOn(true); favPostVoiceUI.iZd.setBackgroundResource(d.record_shape_press); favPostVoiceUI.iZd.setText(i.favorite_release_to_fav); favPostVoiceUI.hnu = false; favPostVoiceUI.iZl = favPostVoiceUI.aMm(); if (favPostVoiceUI.iZl.de(favPostVoiceUI.path)) { favPostVoiceUI.iZe = bi.VG(); favPostVoiceUI.hnz.J(200, 200); favPostVoiceUI.hnl.setVisibility(0); favPostVoiceUI.erD.J(100, 100); favPostVoiceUI.iZj.setText(i.favorite_move_up_cancel); return; } favPostVoiceUI.iZe = 0; } static /* synthetic */ void n(FavPostVoiceUI favPostVoiceUI) { favPostVoiceUI.iZd.setKeepScreenOn(false); favPostVoiceUI.iZl.we(); favPostVoiceUI.erD.SO(); favPostVoiceUI.hnz.SO(); favPostVoiceUI.aMp(); favPostVoiceUI.aMo(); } public void onCreate(Bundle bundle) { String str; super.onCreate(bundle); setContentView(y.gq(this).inflate(f.fav_post_voice, null)); this.hnl = (ImageView) findViewById(e.voice_rcd_hint_anim); this.iZh = findViewById(e.voice_rcd_hint_anim_area); this.iZi = findViewById(e.voice_rcd_hint_cancel_area); this.iZf = findViewById(e.voice_rcd_hint_rcding); this.iZg = findViewById(e.voice_rcd_hint_tooshort); this.iZj = (TextView) findViewById(e.voice_rcd_hint_word); this.iZk = findViewById(e.voice_rcd_hint_bg); findViewById(e.voice_rcd_hint).setVisibility(8); this.iZk.setVisibility(8); findViewById(e.voice_rcd_hint).setOnTouchListener(new OnTouchListener() { public final boolean onTouch(View view, MotionEvent motionEvent) { FavPostVoiceUI.this.aMq(); return false; } }); findViewById(e.fav_post_voice_footer).setVisibility(8); this.iZl = aMm(); this.iZd = (Button) findViewById(e.fav_post_voice_btn); this.iZd.setOnTouchListener(new 5(this)); aMo(); String aKX = b.aKX(); com.tencent.mm.vfs.b bVar = new com.tencent.mm.vfs.b(aKX); if (!bVar.exists()) { bVar.mkdirs(); } do { str = aKX + "/" + System.currentTimeMillis(); } while (new com.tencent.mm.vfs.b(str).exists()); this.path = str; this.iZj.post(new 3(this)); } private j aMm() { com.tencent.mm.compatible.b.b.a aVar = com.tencent.mm.compatible.b.b.a.daM; j jVar = new j(); jVar.bFw = new 4(this); return jVar; } private void aMn() { long j = 0; if (this.hnt) { boolean z; this.iZd.setKeepScreenOn(true); this.iZd.setBackgroundResource(d.record_shape_normal); this.iZd.setText(i.favorite_press_talk_to_fav); this.iZl.we(); if (this.iZe != 0) { j = bi.bI(this.iZe); } this.duration = j; if (this.duration < 800) { z = true; } else { z = false; } this.erD.SO(); this.hnz.SO(); if (z) { aMp(); this.iZd.setEnabled(false); this.iZd.setBackgroundResource(d.record_shape_disable); this.iZg.setVisibility(0); this.iZf.setVisibility(8); this.hnB.sendEmptyMessageDelayed(0, 500); } else { String str = this.path; int i = (int) this.duration; if (bi.oW(str)) { x.e("MicroMsg.FavPostLogic", "postVoice path null"); } else { g gVar = new g(); gVar.field_type = 3; gVar.field_sourceType = 6; g.E(gVar); vx vxVar = new vx(); vxVar.UP(str); vxVar.CE(i); vxVar.kY(true); vxVar.CF(gVar.field_type); vxVar.UL("amr"); gVar.field_favProto.rBI.add(vxVar); b.B(gVar); h.mEJ.h(10648, new Object[]{Integer.valueOf(1), Integer.valueOf(0)}); } setResult(-1); finish(); overridePendingTransition(0, 0); } this.hnt = false; } } public final void aMo() { this.iZf.setVisibility(0); this.iZg.setVisibility(8); this.iZi.setVisibility(8); this.iZh.setVisibility(0); this.iZj.setText(i.fav_press_talk_start_record); this.iZd.setBackgroundResource(d.record_shape_press); this.iZd.setText(i.favorite_press_talk_to_fav); this.hnl.setVisibility(4); this.hnt = false; } private void aMp() { com.tencent.mm.vfs.b bVar = new com.tencent.mm.vfs.b(this.path); if (bVar.exists()) { bVar.delete(); } } protected void onDestroy() { super.onDestroy(); } protected void onResume() { super.onResume(); } protected void onPause() { super.onPause(); aMn(); } public boolean onKeyDown(int i, KeyEvent keyEvent) { if (4 != i) { return super.onKeyDown(i, keyEvent); } aMq(); return true; } private void aMq() { if (!this.iZm) { this.iZm = true; Animation translateAnimation = new TranslateAnimation(1, 0.0f, 1, 0.0f, 1, 0.0f, 1, 1.0f); translateAnimation.setDuration(300); Animation alphaAnimation = new AlphaAnimation(1.0f, 0.0f); alphaAnimation.setDuration(300); translateAnimation.setAnimationListener(new 8(this)); findViewById(e.voice_rcd_hint).setVisibility(8); findViewById(e.fav_post_voice_footer).setVisibility(8); this.iZk.setVisibility(8); this.iZk.startAnimation(alphaAnimation); findViewById(e.voice_rcd_hint).startAnimation(alphaAnimation); findViewById(e.fav_post_voice_footer).startAnimation(translateAnimation); } } }
package io.zipcoder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import zipcoder.RedlightbackendApplication; import zipcoder.models.RedLightDAO; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by ghumphrey on 11/9/15. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes= RedlightbackendApplication.class) @WebAppConfiguration public class RedLightControllerSpec { private MockMvc mvc; @Autowired private RedLightDAO redLightDAO; @Autowired private WebApplicationContext wac; @Before public void setUp(){ this.mvc= MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void testReadCamera() throws Exception { this.mvc.perform(get("/camera")) .andExpect(status().isOk()); } }
import pages.PDP; import testConfig.BaseTest; import testConfig.tags.Prod; import testConfig.tags.Stage; class OperationsAtPDPTest extends BaseTest { private PDP pdp = new PDP(); @Stage @Prod void selectingProductQuantity() { pdp.open("/sonora-response-card-w783-182781202202.html") .selectQuantity(20) .assertPrice("$42.80"); } @Stage @Prod void addingSuiteProductToCart() { pdp.open("/sonora-response-card-w783-182781202202.html") .selectCoordinateItem("Stationery") .personalize() .next() .nextReviewOrder() .addToBag() .continueToPDP() .skipStep() .assertCompleteMessage("Congratulations! Your project is complete.") .assertMiniCartSize(200); } }
package com.mahendra; import java.io.*; public class Main2 { public static void main(String[] args) { try { // System.in is BYTE STREAM : takes BYTES inputs // InputStreamReader is CHARACTER STREAM : converts EACH BYTE into CHARACTER // BufferedReader is providing BUFFERRING by converting CHARS into STRINGs BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter your name: "); String line = br.readLine(); // User input captures ENTER key as well, which takes 2 Bytes on Windows and 1 Byte on Unix/Linux/Mac System.out.println("New String: "+line+" which has "+line.length()+" characters"); //Removes all WHITESPACES (Invisible characters like space or line-break (enter) ) line = line.trim(); System.out.println("New String: "+line+" which has "+line.length()+" characters"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package org.ca.View; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class CustomerLogout */ @WebServlet("/CustomerLogout") public class CustomerLogout extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CustomerLogout() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession ses=request.getSession(); try{ ses.invalidate(); response.sendRedirect("CustomerLogin"); } catch(Exception e) { response.sendRedirect("CustomerLogin"); } } }
package net.kr9ly.trout; import java.io.Serializable; /** * Copyright 2015 kr9ly * <br /> * 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 * <br /> * http://www.apache.org/licenses/LICENSE-2.0 * <br /> * 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 */ interface FieldHolder { Serializable getField(); void setField(Serializable object); void commit(); void markNotifyFinished(); boolean isUpdated(); boolean needsNotify(); FieldContainer toFieldContainer(String key); }
package top.skyzc.juke.util; import android.util.Log; import java.util.List; import java.util.Random; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; import cn.bmob.v3.listener.SaveListener; import top.skyzc.juke.model.Upgrade; import top.skyzc.juke.model.User; /** * 用户提交升级时判断,传入用户的当前等级,来分析升级条件 * 等级 0~9 * 0->1: 需要名下拥有3个子用户,并且通过上级认证和九星认证 * 1->2: 需要一个2星用户认证 * 2->3: 需要一个3星用户认证 * 3->4: 需要一个4星用户认证 * 4->5: 需要一个5星用户认证 * 5->6: 需要一个6星用户认证 * 6->7: 需要一个7星用户认证 * 8->9: 需要一个9星用户认证 * */ public class UserUpgradeCase { private final String TAG = "UserUpgradeCase"; private int nowLevel; private int toLevel; public UserUpgradeCase(int nowlevel) { this.nowLevel = nowlevel; this.toLevel = nowlevel + 1; } public User upgradePlanCase(){ return null; } /** 1到8星的升级方案 * 根据等级获取该等级的所有用户 * 并从中随机返回一个User * */ public User getRandomUserOfLevel(final int level){ final User[] user = new User[1]; BmobQuery<User> bmobQuery = new BmobQuery<>(); bmobQuery.addWhereEqualTo("level", level); bmobQuery.findObjects(new FindListener<User>() { @Override public void done(List<User> list, BmobException e) { if (e == null) { Random random = new Random(); int n = random.nextInt(list.size()); // 获取一个随机的九星级别用户 user[0] = list.get(n); } else { Log.e(TAG, "随机取得" + level+ "星User失败"+e.getMessage()); } } }); return user[0]; } }
package com.game; import com.game.engine.Box; import com.game.engine.GameEngine; import java.util.List; /** * @author Krystian Życiński */ public class GameSimulator { public static Double simulateGame() { GameEngine gameEngine = new GameEngine(); List<Box> boxList = gameEngine.getGameBoxList(); int counter = 0; int gameOverCounter = 0; while (boxList != null) { if (boxList.size() == 12) { boxList = gameEngine.action(boxList.get(counter)); counter++; } else { boxList = gameEngine.action(boxList.get(gameOverCounter)); gameOverCounter++; } } return (double) gameEngine.getReward(); } }
package com.example.mysqlite; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.example.mysqlite.annotion.DbFiled; import com.example.mysqlite.annotion.DbTable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * PROJECT_NAME:MyApplication * PACKAGE_NAME:com.example.mysqlite * USER:Frank * DATE:2018/10/29 * TIME:9:26 * DAY_NAME_FULL:星期一 * DESCRIPTION:On the description and function of the document **/ public class BaseDao<T> implements IBaseDao<T> { private SQLiteDatabase database; private Class<T> entityClass; private String tableName; private boolean isInit=false; private HashMap<String,Field> cacheMap; protected synchronized boolean init(Class<T> entity,SQLiteDatabase sqLiteDatabase){ if (!isInit){ entityClass=entity; database=sqLiteDatabase; tableName=entity.getAnnotation(DbTable.class).value(); if (!sqLiteDatabase.isOpen()){ return false; } if (!autoCreateTable()){ return false; } isInit=true; } initCacheMap(); return isInit; } private void initCacheMap() { //查一次空表,做缓存 cacheMap=new HashMap<>(); String sql="select * from "+this.tableName+" limit 1,0"; Cursor cursor=database.rawQuery(sql,null); //得到字段名数组 String[] coloumNames=cursor.getColumnNames(); Field[]columnFields=entityClass.getDeclaredFields(); for (String columnName:coloumNames){ Field resultField=null; for (Field field:columnFields){ if (columnName.equals(field.getAnnotation(DbFiled.class).value())){ resultField=field; break; } } if (resultField!=null){ cacheMap.put(columnName,resultField); } } cursor.close(); } private boolean autoCreateTable() { StringBuffer stringBuffer=new StringBuffer(); stringBuffer.append("CREATE TABLE IF NOT EXISTS "); stringBuffer.append(tableName+" ("); Field[] fields=entityClass.getDeclaredFields(); for (Field field:fields ){ Class type=field.getType(); if (type==String.class){ stringBuffer.append(field.getAnnotation(DbFiled.class).value()+" TEXT,"); }else if (type==Double.class){ stringBuffer.append(field.getAnnotation(DbFiled.class).value()+" DOUBLE,"); }else if (type==Integer.class){ stringBuffer.append(field.getAnnotation(DbFiled.class).value()+" INTEGER,"); }else if (type==Long.class){ stringBuffer.append(field.getAnnotation(DbFiled.class).value()+" BIGINT,"); }else if (type==byte[].class){ stringBuffer.append(field.getAnnotation(DbFiled.class).value()+" BLOB,"); }else if (type==String.class){ stringBuffer.append(field.getAnnotation(DbFiled.class).value()+" TEXT,"); }else { continue; } } if (stringBuffer.charAt(stringBuffer.length()-1)==','){ stringBuffer.deleteCharAt(stringBuffer.length()-1); } stringBuffer.append(")"); try { Log.i("CreateTable",stringBuffer.toString()); this.database.execSQL(stringBuffer.toString()); }catch (Exception e){ e.printStackTrace(); return false; } return true; } @Override public Long insert(T entity) { ContentValues contentValues=getValuesByInsert(entity); long result=database.insert(tableName,null,contentValues); return result; } @Override public List<T> query(T entity) { return queryData(entity,null,null,null,null,null); } @Override public List<T> query(T entity, String orderBy) { return queryData(entity,null,null,null,null,orderBy); } @Override public List<T> query(T entity, String groupBy, String having) { return queryData(entity,null,null,groupBy,having,null); } @Override public List<T> query(T entity, Integer startIndex, Integer limit) { return queryData(entity,startIndex,limit,null,null,null); } @Override public List<T> query(T entity, Integer startIndex, Integer limit, String orderBy) { return queryData(entity,startIndex,limit,null,null,orderBy); } @Override public List<T> query(T entity, Integer startIndex, Integer limit, String groupBy, String having) { return queryData(entity,startIndex,limit,groupBy,having,null); } @Override public List<T> query(T entity, Integer startIndex, Integer limit, String groupBy, String having, String orderBy) { return queryData(entity,startIndex,limit,groupBy,having,orderBy); } @Override public Long update(T entityUpdate, T entityWhere) { ContentValues contentValues=getValuesByUpdate(entityUpdate); Condition condition=new Condition(getContentValues(entityWhere)); long result=database.update(tableName,contentValues,condition.getWhereClause(),condition.getWhereArgs()); return result; } @Override public Long delete(T entity) { //ContentValues contentValues=getValues(entity); Condition condition=new Condition(getContentValues(entity)); long result=database.delete(tableName,condition.getWhereClause(),condition.getWhereArgs()); return result; } private List<T> queryData(T where,Integer startIndex,Integer limit,String groupBy,String having,String orderBy){ String limitString=null; if (startIndex!=null&&limit!=null){ limitString=startIndex+","+limit; } Condition condition=new Condition(getContentValues(where)); Cursor cursor=null; List<T> result=new ArrayList<>(); try{ cursor=database.query(tableName,null,condition.getWhereClause(),condition.getWhereArgs(),groupBy,having,orderBy,limitString); if (cursor!=null){ result=getResult(cursor,where); } }catch (Exception e){ e.printStackTrace(); }finally { if (cursor!=null){ cursor.close(); } } return result; } private ContentValues getContentValues(T entity) { ContentValues contentValues=new ContentValues(); try{ for (Map.Entry<String,Field> me:cacheMap.entrySet()){ if (me.getValue().get(entity)==null){ continue; } contentValues.put(me.getKey(),me.getValue().get(entity).toString()); } } catch (IllegalAccessException e) { e.printStackTrace(); } return contentValues; } private ContentValues getValuesByInsert(T entity) { ContentValues contentValues=new ContentValues(); Iterator<Map.Entry<String ,Field>> iterator=cacheMap.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String ,Field> fieldEntry=iterator.next(); Field field=fieldEntry.getValue(); String key=fieldEntry.getKey(); field.setAccessible(true); try { Object object=field.get(entity); Class type=field.getType(); if (type==String.class){ String value= (String) object; contentValues.put(key,value); }else if (type==Double.class){ Double value= (Double) object; contentValues.put(key,value); }else if (type==Integer.class){ Integer value= (Integer) object; contentValues.put(key,value); }else if (type==Long.class){ Long value= (Long) object; contentValues.put(key,value); }else if (type==byte[].class){ byte[] value= (byte[]) object; contentValues.put(key,value); }else { continue; } } catch (IllegalAccessException e) { e.printStackTrace(); } } return contentValues; } private ContentValues getValuesByUpdate(T entity) { ContentValues contentValues=new ContentValues(); Iterator<Map.Entry<String ,Field>> iterator=cacheMap.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String ,Field> fieldEntry=iterator.next(); Field field=fieldEntry.getValue(); String key=fieldEntry.getKey(); field.setAccessible(true); try { Object object=field.get(entity); Class type=field.getType(); if (type==String.class){ String value= (String) object; if (value!=null){ contentValues.put(key,value); } }else if (type==Double.class){ Double value= (Double) object; if (value!=null) { contentValues.put(key, value); } }else if (type==Integer.class){ Integer value= (Integer) object; if (value!=null) { contentValues.put(key, value); } }else if (type==Long.class){ Long value= (Long) object; if (value!=null) { contentValues.put(key, value); } }else if (type==byte[].class){ byte[] value= (byte[]) object; if (value!=null) { contentValues.put(key, value); } }else { continue; } } catch (IllegalAccessException e) { e.printStackTrace(); } } return contentValues; } protected List<T> getResult(Cursor cursor,T where){ ArrayList list=new ArrayList(); Object item; while (cursor.moveToNext()){ try { item=where.getClass().newInstance(); Iterator<Map.Entry<String,Field>> iterator=cacheMap.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<String,Field> entry=iterator.next(); String colmunName=entry.getKey(); Field field=entry.getValue(); int columnIndex=cursor.getColumnIndex(colmunName); Class type=field.getType(); if (columnIndex!=-1){ if (type==String.class){ field.set(item,cursor.getString(columnIndex)); }else if (type==Double.class){ field.set(item,cursor.getDouble(columnIndex)); }else if (type==Integer.class){ field.set(item,cursor.getInt(columnIndex)); }else if (type==Long.class){ field.set(item,cursor.getLong(columnIndex)); }else if (type==byte[].class){ field.set(item,cursor.getBlob(columnIndex)); }else { continue; } } } list.add(item); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return list; } class Condition{ private String whereClause; private String[]whereArgs; public Condition(ContentValues whereClause){ ArrayList list=new ArrayList(); StringBuilder stringBuilder=new StringBuilder(); stringBuilder.append(" 1=1 "); Set keys=whereClause.keySet(); Iterator iterator=keys.iterator(); while (iterator.hasNext()){ String key=(String)iterator.next(); String value=(String)whereClause.get(key); if (value!=null){ stringBuilder.append("and "+key+"=?"); list.add(value); } } this.whereClause=stringBuilder.toString(); this.whereArgs=(String[])list.toArray(new String[list.size()]); } public String[] getWhereArgs(){ return whereArgs; } public String getWhereClause(){ return whereClause; } } }
package leetcode; /** * @author kangkang lou */ public class Main_209 { public int minSubArrayLen(int s, int[] nums) { int total = 0, start = 0; int min = nums.length + 1; for (int i = 0; i < nums.length; i++) { total += nums[i]; while (total >= s) { min = Math.min(min, i - start + 1); total -= nums[start++]; } } return min == nums.length + 1 ? 0 : min; } public static void main(String[] args) { } }
package ru.nikozavr.auto; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.Arrays; import java.util.List; import ru.nikozavr.auto.fragments.HelpFragment; import ru.nikozavr.auto.fragments.HistoryFragment; import ru.nikozavr.auto.fragments.HomeFragment; import ru.nikozavr.auto.fragments.InfoFragment; import ru.nikozavr.auto.fragments.MarqInfoFragment; import ru.nikozavr.auto.fragments.MarquesFragment; import ru.nikozavr.auto.fragments.ProfileFragment; public class MainActivity extends BaseActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, MarqInfoFragment.OnFragmentInteractionListener, FragmentsInteraction.ChangeToolbox{ private MainActivity mainActivity; /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; public FragmentsInteraction fragmentsInteraction; private FragmentManager fragmentManager; /** }. */ private CharSequence mTitle; private Resources res; private Boolean first; private Toolbar toolbar; private List<String> navDrawNames; private AutoEncyclopedia globe; @Override protected void onCreate(Bundle savedInstanceState) { mainActivity = this; super.onCreate(savedInstanceState); res = getResources(); // setContentView(R.layout.activity_main); /* toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.inflateMenu(R.menu.main); setSupportActionBar(toolbar); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); */ fragmentManager = getSupportFragmentManager(); navDrawNames = Arrays.asList(res.getStringArray(R.array.nav_drawer_list_items)); } public MainActivity getMainActivity(){ return this; } @Override public void onNavigationDrawerItemSelected(int position) { String curr_tag = null; String tag = navDrawNames.get(position); globe = (AutoEncyclopedia)getApplicationContext(); if(position ==0 && !globe.isLoggedIn()) { Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME); startActivity(intent); } else{ int count = fragmentManager.getBackStackEntryCount(); if(count != 0){ curr_tag = fragmentManager.getBackStackEntryAt(count - 1).getName(); } if(curr_tag != tag) { Fragment fragment = fragmentManager.findFragmentByTag(tag); Fragment curr_fragment = fragmentManager.findFragmentByTag(curr_tag); if (fragment == null) { switch (position) { case 0: fragment = new ProfileFragment(); break; case 1: fragment = new HomeFragment(); break; case 2: fragment = new MarquesFragment(); break; case 3: fragment = new HistoryFragment(); break; case 4: fragment = new HelpFragment(); break; case 5: fragment = new InfoFragment(); break; } } if (fragment != null) { if (!fragment.isVisible()) { if (curr_fragment != null) { fragmentManager.beginTransaction().remove(curr_fragment).commit(); } if (fragment.isAdded()) { fragmentManager.beginTransaction().show(fragment).addToBackStack(tag).commit(); } else { fragmentManager.beginTransaction() .add(R.id.container, fragment, tag).addToBackStack(tag).commit(); } } } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.main, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); // return true; // } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(Uri uri) { } public Toolbar getToolBar(){ return toolbar; } @Override public void ChangeToolboxIcon(boolean isArrow, int numberTitle) { mNavigationDrawerFragment.ChangeToolboxIcon(isArrow, numberTitle); } @Override public void onBackPressed() { if(!fragmentsInteraction.NavigiteUpFragments()) finish(); } // @Override // public final MainActivity getParent(){ // } public void LaunchNewActivity(){ Intent i = new Intent(getApplicationContext(), MarqInfoActivity.class); // ((AutoEncyclopedia)getActivity().getApplication()).addBitmapToMemoryCache(result.get(position).getImage().getKey(), // result.get(position).getImage().getBitmap()); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivityForResult(i, 1); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { int position = data.getIntExtra("position", -1); onNavigationDrawerItemSelected(position); } }
package com.coco.winter.utils; import com.coco.winter.common.entity.Identity; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.Data; import lombok.extern.slf4j.Slf4j; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; /** * @ClassName JWTTokenUtil * @Description TODO * @Author like * @Data 2018/11/10 16:59 * @Version 1.0 **/ @Data @Slf4j public class JWTTokenUtil { /** * 传递一个载荷 然后通过jjwt 自动生成Token * * @param poyload * @return */ public static String createJWT(String poyload, String authJm) { //加密方式HS256 使用jsonwebtoken SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(authJm); Key siginingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //生成jwt JwtBuilder jwtBuilder = Jwts.builder() .setHeaderParam("typ", "JWT") .setHeaderParam("alg", "HS256") .setPayload(poyload)//载荷 .signWith(signatureAlgorithm, siginingKey);//签名 //生成token并序列化编码成一个URL安全的字符串 log.info("token生成成功"); return jwtBuilder.compact(); } /** * @param identity * @param apiKeySecret * @return */ public static String createToken(Identity identity, String apiKeySecret) { //JWT采用的签名算法 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //获取当前时间戳 long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //封装好加密算法与私钥apiKeySecret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKeySecret); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //采用建造者模式定制化token属性 JwtBuilder builder = Jwts.builder().setId(identity.getId()) .setIssuedAt(now) .setSubject(identity.getId() + "," + identity.getUserName() + "," + identity.getRole()) .setIssuer(identity.getIssuer()) .signWith(signatureAlgorithm, signingKey); //设置失效时间戳 long ttlMillis = identity.getDuration(); if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); // identity.setDuration(exp.getTime()); } //生成token并序列化编码成一个URL安全的字符串 log.info("token生成成功"); return builder.compact(); } /** * 解析jwt 并判断是否被修改,如验证通过则返回新的 * * @param jwt * @return * @throws Exception */ public static Claims parseJWT(String jwt, String authJm) throws Exception { if (jwt.split("\\.").length == 3) { String sign = jwt.split("\\.")[2];//签名 System.out.println("签名jwt中:" + sign); Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(authJm)) .parseClaimsJws(jwt).getBody(); String signNew = createJWT(JacksonJsonUtil.obj2json(claims), authJm).split("\\.")[2]; if (signNew.equals(sign)) { log.info("token解析成功,匹配一致,数据没有篡改!"); return claims; } else { return null; } } else { return null; } } /** * @param token * @param apiKeySecret * @return * @throws Exception */ public static Identity parseToken(String token, String apiKeySecret) throws Exception { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(apiKeySecret)) .parseClaimsJws(token).getBody(); String[] subjectInfos = claims.getSubject().split(","); String id = subjectInfos[0]; String userName = subjectInfos[1]; String role = subjectInfos[2]; // 封装成pojo Identity identity = new Identity(); identity.setId(id); identity.setUserName(userName); identity.setRole(role); identity.setDuration(claims.getExpiration().getTime()); log.info("已登录的用户,有效token"); return identity; } }
package com.tencent.mm.plugin.appbrand.config; import android.os.Parcel; import android.os.Parcelable.Creator; import com.tencent.mm.plugin.appbrand.config.AppBrandGlobalSystemConfig.HttpSetting; class AppBrandGlobalSystemConfig$HttpSetting$1 implements Creator<HttpSetting> { AppBrandGlobalSystemConfig$HttpSetting$1() { } public final /* synthetic */ Object createFromParcel(Parcel parcel) { return new HttpSetting(parcel); } public final /* bridge */ /* synthetic */ Object[] newArray(int i) { return new HttpSetting[i]; } }
package jogoDaVelha; public class Jogador { private String marcacao; private String nome; public String getMarcacao() { return marcacao; } public void setMarcacao(String marcacao) { this.marcacao = marcacao; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
package org.wit.snr.nn.srbm.visualization; import org.wit.snr.nn.srbm.math.collection.Matrix; import java.awt.*; import java.util.List; public class MatrixRendererSample { final private int x; final private int y; final private Matrix m; final private Graphics g; final Color color; public MatrixRendererSample(int x, int y, Matrix m, Graphics g, Color color) { this.x = x; this.y = y; this.m = m; this.g = g; this.color = color; } public void render() { int colidx = 0; for (List<Double> column : m.getMatrixAsCollection()) { for (int i = 0; i < 28; i++) { for (int j = 0; j < 28; j++) { double matrixVals = column.get(i * 28 + j); g.setColor(color); int offset_i = x + 28 * (colidx % 20) + 2; int offset_j = y + 28 * (Math.round(colidx / 20)) + 2; if (matrixVals > 0) g.drawLine(i + offset_i, j + offset_j, i + offset_i, j + offset_j); } } colidx++; } } }
package com.ericlam.mc.minigames.core.factory; import com.ericlam.mc.minigames.core.factory.compass.CompassFactory; import com.ericlam.mc.minigames.core.factory.scoreboard.ScoreboardFactory; /** * 遊戲工廠 */ public interface GameFactory { /** * 創建計分版工廠 * * @return 計分版工廠 */ ScoreboardFactory getScoreboardFactory(); /** * 創建羅盤追蹤器工廠 * @return 羅盤追蹤器工廠 */ CompassFactory getCompassFactory(); }
package com.rappidjs.webtest; import com.rappidjs.webtest.model.Person; import com.rappidjs.webtest.module.HomeModule; import io.rappid.webtest.common.WebElementPanel; import io.rappid.webtest.testng.TestDevelopment; import org.openqa.selenium.By; import org.testng.Assert; import org.testng.annotations.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * User: tony * Date: 26.10.13 * Time: 17:10 */ public class HomeTest extends RappidJsWebTest { @Test() public void SimpleAppTest() { HomeModule homeModule = getHomeModule(); HomeModule.SimpleApp simpleApp = homeModule.simpleApp(); Assert.assertEquals(simpleApp.input().getValue(), ""); Assert.assertEquals(simpleApp.headline(), "Simple App"); Assert.assertEquals(simpleApp.output(), "Hello !"); simpleApp.input().setValue("Tony"); Assert.assertEquals(simpleApp.output(), "Hello Tony!"); } @Test() public void TodoListTest() { HomeModule.TodoApp todoApp = getHomeModule().getTodoApp(); Assert.assertEquals(todoApp.headline(), "Todo"); Assert.assertEquals(todoApp.totalItems(), 0); Assert.assertEquals(todoApp.openItems(), 0); Assert.assertEquals(todoApp.input().getValue(), ""); Random random = new Random(); // add several items ArrayList<String> list = new ArrayList<String>(30); ArrayList<String> uncheckedList = new ArrayList<String>(30); int itemCount = random.nextInt(19) + 7; for (int i = 0; i < itemCount; i++) { String item = new BigInteger(100, random).toString(32); list.add(item); todoApp.input().setValue(item); todoApp.input().pressEnter(); Assert.assertEquals(todoApp.totalItems(), i + 1); } uncheckedList.addAll(list); // check some items int checkedCount = 0; for (int i = 0; i < itemCount; i++) { WebElementPanel item = new WebElementPanel(todoApp.getChildren(By.cssSelector("label")).get(i)); Assert.assertEquals(item.getWebElement().getText().trim(), list.get(i)); if (random.nextInt(2) == 1) { uncheckedList.remove(i - checkedCount); checkedCount++; // click the checkbox item.getChild("input").click(); Assert.assertTrue(item.hasClass("done")); } Assert.assertEquals(todoApp.openItems(), itemCount - checkedCount); } if (checkedCount > 0) { Assert.assertTrue(todoApp.archive().isDisplayed()); } todoApp.archive().click(); Assert.assertEquals(todoApp.openItems(), uncheckedList.size()); Assert.assertEquals(todoApp.totalItems(), uncheckedList.size()); } @Test() @TestDevelopment() public void ContactsTest() { HomeModule.ContactsApp app = getHomeModule().getContactsApp(); Random random = new Random(); int itemCount = random.nextInt(10) + 5; ArrayList<Person> contacts = new ArrayList<Person>(); for (int i = 0; i < itemCount; i++) { Assert.assertFalse(app.previewIsVisible()); Person p = new Person(new BigInteger(50, random).toString(32), new BigInteger(70, random).toString(32), new BigInteger(10, random).toString()); contacts.add(p); app.firstName().setValue(p.getFirstName()); app.lastName().setValue(p.getLastName()); app.phone().setValue(p.getPhone()); Assert.assertTrue(app.previewIsVisible()); Assert.assertTrue(app.preview().shows(p)); app.phone().pressEnter(); Assert.assertFalse(app.previewIsVisible()); } // check cards List<HomeModule.ContactsApp.Card> cards = app.cards(); Assert.assertEquals(contacts.size(), cards.size()); for (int i = 0; i < cards.size(); i++) { Assert.assertTrue(cards.get(i).shows(contacts.get(i))); } } private HomeModule getHomeModule() { IndexPage indexPage = getIndexPage(); Assert.assertEquals(indexPage.getUri().getFragment(), "/home"); return indexPage.getHomeModule(); } }
package Monsters; public class Dracula extends HorribleMonster implements Monster { @Override public void destroy() { } @Override public void kill() { } @Override public void scareChildren() { } }
package com.tencent.mm.plugin.wenote.ui.nativenote.a; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView$m; import android.support.v7.widget.RecyclerView.q; import com.tencent.mm.compatible.util.j; import com.tencent.mm.plugin.wenote.model.nativenote.manager.k; import com.tencent.mm.sdk.platformtools.ad; public final class a extends LinearLayoutManager { private final int qvb = j.s(ad.getContext(), true); public int qvc = -1; public boolean qvd = false; public final int b(int i, RecyclerView$m recyclerView$m, q qVar) { int i2 = 1; int i3 = 0; if (!this.qvd) { return super.b(i, recyclerView$m, qVar); } int i4 = i < 0 ? k.aq(49.0f) <= ((float) Math.abs(i)) ? 1 : i3 : i3; if (i <= 0) { i2 = i4; } else if (((float) this.qvb) + k.aq(49.0f) >= ((float) i)) { i2 = i3; } if (i2 != 0 && this.qvd) { return i3; } try { return super.b(i, recyclerView$m, qVar); } catch (Exception e) { return i3; } } protected final int a(q qVar) { if (this.qvc > 0) { return this.qvc; } return 900; } public final void c(RecyclerView$m recyclerView$m, q qVar) { try { super.c(recyclerView$m, qVar); } catch (Exception e) { } } }
package bank; public class Individual extends Client { public Individual(double balance) { setPaymentAccount(balance); } }
package com.google.cacheserver; public interface Operations { public enum OPCODE{GET, PUT}; }
package org.murinrad.android.musicmultiply.upnp; import android.util.Log; import org.fourthline.cling.binding.annotations.UpnpInputArgument; import org.fourthline.cling.model.types.UnsignedIntegerFourBytes; import org.fourthline.cling.model.types.UnsignedIntegerTwoBytes; import org.fourthline.cling.support.model.Channel; import org.fourthline.cling.support.renderingcontrol.AbstractAudioRenderingControl; import org.fourthline.cling.support.renderingcontrol.RenderingControlException; import org.murinrad.android.musicmultiply.MainActivity; /** * Created by Radovan Murin on 1.4.2015. */ public class RenderingControl extends AbstractAudioRenderingControl { @Override public boolean getMute(@UpnpInputArgument(name = "InstanceID") UnsignedIntegerFourBytes unsignedIntegerFourBytes, @UpnpInputArgument(name = "Channel") String s) throws RenderingControlException { Log.i(MainActivity.APP_TAG, "getMute"); return false; } @Override public void setMute(@UpnpInputArgument(name = "InstanceID") UnsignedIntegerFourBytes unsignedIntegerFourBytes, @UpnpInputArgument(name = "Channel") String s, @UpnpInputArgument(name = "DesiredMute", stateVariable = "Mute") boolean b) throws RenderingControlException { Log.i(MainActivity.APP_TAG, "setMute"); } @Override public UnsignedIntegerTwoBytes getVolume(@UpnpInputArgument(name = "InstanceID") UnsignedIntegerFourBytes unsignedIntegerFourBytes, @UpnpInputArgument(name = "Channel") String s) throws RenderingControlException { Log.i(MainActivity.APP_TAG, "getVolume"); UnsignedIntegerTwoBytes bytes = new UnsignedIntegerTwoBytes(50); return bytes; } @Override public void setVolume(@UpnpInputArgument(name = "InstanceID") UnsignedIntegerFourBytes unsignedIntegerFourBytes, @UpnpInputArgument(name = "Channel") String s, @UpnpInputArgument(name = "DesiredVolume", stateVariable = "Volume") UnsignedIntegerTwoBytes unsignedIntegerTwoBytes) throws RenderingControlException { Log.i(MainActivity.APP_TAG, "setVolume"); } @Override protected Channel[] getCurrentChannels() { Log.i(MainActivity.APP_TAG, "getCurrentChannels"); return new Channel[0]; } @Override public UnsignedIntegerFourBytes[] getCurrentInstanceIds() { Log.i(MainActivity.APP_TAG, "getCurrentInstanceIds"); return new UnsignedIntegerFourBytes[0]; } }
package net.cupmouse.minecraft.eplugin.minigame.snipe; import net.cupmouse.minecraft.eplugin.minigame.Minigame; import net.cupmouse.minecraft.eplugin.minigame.MinigamePlayer; import org.spongepowered.api.entity.living.player.User; public final class SnipePlayer extends MinigamePlayer { protected boolean leftGame; public SnipePlayer(Minigame minigame, User user) { super(minigame, user); } public boolean didLeaveGame() { return leftGame; } @Override public SnipeGame getMinigame() { return (SnipeGame) super.minigame; } }
package com.brady.euler; public class Problem104 extends Problem { @Override public long solve() { int fPrev = 1, f = 1; for (int i = 3; i < 1000000; i++) { int t = f; f = (fPrev + f) % 1000000000; fPrev = t; if (EulerUtils.isPandigital(first9Digits(i)) && EulerUtils.isPandigital(f)) { return i; } } return -1; } private int first9Digits(int n) { double digits = n * 0.20898764024997873 - 0.3494850021680094; return (int) Math.pow(10, digits - (int) digits + 9 - 1); } }
package com.onplan.service.impl; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.onplan.adviser.AdviserListener; import com.onplan.adviser.AlertInfo; import com.onplan.adviser.alert.Alert; import com.onplan.adviser.alert.AlertEvent; import com.onplan.adviser.predicate.AdviserPredicate; import com.onplan.connector.HistoricalPriceService; import com.onplan.connector.InstrumentService; import com.onplan.domain.configuration.AdviserPredicateConfiguration; import com.onplan.domain.configuration.AlertConfiguration; import com.onplan.domain.transitory.PriceTick; import com.onplan.persistence.AlertConfigurationDao; import com.onplan.service.AlertService; import com.onplan.service.EventNotificationService; import org.apache.log4j.Logger; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Collection; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.onplan.adviser.predicate.AdviserPredicateUtil.createAdviserPredicateInfo; import static com.onplan.service.impl.AdviserFactory.createAlert; import static com.onplan.util.ExceptionUtils.stackTraceToString; import static com.onplan.util.MorePreconditions.checkNotNullOrEmpty; @Singleton public final class AlertServiceImpl extends AbstractAdviserService implements AlertService { private static final Logger LOGGER = Logger.getLogger(AlertServiceImpl.class); private final Map<String, Collection<Alert>> alertsMapping = Maps.newTreeMap(); private final AdviserListener<AlertEvent> alertEventListener = new InternalAlertListener(); private volatile boolean hasAlerts = false; private EventNotificationService eventNotificationService; private AlertConfigurationDao alertConfigurationDao; private InstrumentService instrumentService; private HistoricalPriceService historicalPriceService; @Inject public void setEventNotificationService(EventNotificationService eventNotificationService) { this.eventNotificationService = eventNotificationService; } @Inject public void setAlertConfigurationDao(AlertConfigurationDao alertConfigurationDao) { this.alertConfigurationDao = alertConfigurationDao; } @Inject public void setInstrumentService(InstrumentService instrumentService) { this.instrumentService = instrumentService; } @Inject public void setHistoricalPriceService(HistoricalPriceService historicalPriceService) { this.historicalPriceService = historicalPriceService; } @Override public void onPriceTick(final PriceTick priceTick) { checkNotNull(priceTick); synchronized (alertsMapping) { Iterable<Alert> alerts = alertsMapping.get(priceTick.getInstrumentId()); for (Alert alert : alerts) { alert.onPriceTick(priceTick); } } } @Override public List<Alert> getAlerts() { ImmutableList.Builder result = ImmutableList.builder(); synchronized (alertsMapping) { for (Collection<Alert> alerts : alertsMapping.values()) { result.addAll(alerts); } } return result.build(); } @Override public boolean hasAlerts() { return hasAlerts; } @Override public boolean removeAlert(String alertId) throws Exception { checkNotNullOrEmpty(alertId); boolean result; try { alertConfigurationDao.removeById(alertId); result = unLoadAlert(alertId); } catch (Exception e) { LOGGER.error(String.format( "Error while un-loading alert [%s]: [%s] [%s].", alertId, e.getMessage(), stackTraceToString(e))); throw e; } synchronized (alertsMapping) { hasAlerts = !alertsMapping.isEmpty(); } return result; } @Override public String addAlert(AlertConfiguration alertConfiguration) throws Exception { checkAlertConfiguration(alertConfiguration); String id = alertConfigurationDao.save(alertConfiguration); try { if (!isNullOrEmpty(alertConfiguration.getId())) { unLoadAlert(id); } alertConfiguration = alertConfigurationDao.findById(id); loadAlert(alertConfiguration); } catch (Exception e) { LOGGER.error(String.format( "Error while loading alert configuration [%s]: [%s].", alertConfiguration, e.getMessage())); alertConfigurationDao.removeById(id); throw e; } synchronized (alertsMapping) { hasAlerts = !alertsMapping.isEmpty(); } LOGGER.info(String.format("Alert [%s] saved in database.", id)); return id; } @Override public List<AlertInfo> getAlertsInfo() { ImmutableList.Builder result = ImmutableList.builder(); synchronized (alertsMapping) { for (Collection<Alert> alerts : alertsMapping.values()) { for (Alert alert : alerts) { result.add(createAlertInfo(alert)); } } } return result.build(); } @Override public void loadSampleAlerts() throws Exception { List<AlertConfiguration> oldAlerts = alertConfigurationDao.findAll(); List<AlertConfiguration> sampleAlerts = alertConfigurationDao.getSampleAlertsConfiguration(); LOGGER.info(String.format( "Replacing [%d] old alerts with [%d] sample alerts.", oldAlerts.size(), sampleAlerts.size())); try { unLoadAllAlerts(); alertConfigurationDao.removeAll(); alertConfigurationDao.insertAll(sampleAlerts); loadAllAlerts(); } catch (Exception e) { LOGGER.error(String.format("Error while loading alerts: [%s].", e.getMessage())); alertConfigurationDao.removeAll(); alertConfigurationDao.insertAll(oldAlerts); throw e; } } @Override public void loadAllAlerts() throws Exception { checkArgument(alertsMapping.isEmpty(), "Remove all the previously registered alerts first."); LOGGER.info("Loading alerts configuration from database."); List<AlertConfiguration> alertConfigurations = alertConfigurationDao.findAll(); LOGGER.info(String.format("[%s] alerts found in database.", alertConfigurations.size())); for (AlertConfiguration alertConfiguration : alertConfigurations) { try { loadAlert(alertConfiguration); } catch (Exception e) { LOGGER.error(String.format("Error while loading alert [%s]: [%s] [%s].", alertConfiguration.getId(), e.getMessage(), stackTraceToString(e))); throw e; } } LOGGER.info(String.format( "[%d] alerts loaded for instruments [%s].", alertConfigurations.size(), Joiner.on(", ").join(alertsMapping.keySet()))); } @Override public void unLoadAllAlerts() { synchronized (alertsMapping) { if (!alertsMapping.isEmpty()) { for (String instrumentId : alertsMapping.keySet()) { dispatchInstrumentUnSubscriptionRequired(instrumentId); } alertsMapping.clear(); } hasAlerts = !alertsMapping.isEmpty(); } } private static void checkAlertConfiguration(final AlertConfiguration alertConfiguration) { checkNotNull(alertConfiguration); checkNotNullOrEmpty(alertConfiguration.getMessage()); checkNotNull(alertConfiguration.getInstrumentId()); checkNotNull(alertConfiguration.getPredicatesChain()); checkNotNull(alertConfiguration.getSeverityLevel()); checkArgument(!Iterables.isEmpty(alertConfiguration.getPredicatesChain())); for (AdviserPredicateConfiguration predicateConfiguration : alertConfiguration.getPredicatesChain()) { checkNotNullOrEmpty(predicateConfiguration.getClassName()); checkNotNull(predicateConfiguration.getParameters()); } } private static AlertInfo createAlertInfo(final Alert alert) { checkNotNull(alert); ImmutableList.Builder predicatesInfo = ImmutableList.builder(); for (AdviserPredicate adviserPredicate : alert.getPredicatesChain()) { predicatesInfo.add(createAdviserPredicateInfo(adviserPredicate)); } return new AlertInfo( alert.getId(), alert.getInstrumentId(), alert.getSeverityLevel(), predicatesInfo.build(), alert.getMessage(), alert.getCreatedOn(), alert.getLastFiredOn(), alert.getRepeat()); } private void loadAlert(AlertConfiguration alertConfiguration) throws Exception { checkAlertConfiguration(alertConfiguration); Alert alert = createAlert( alertConfiguration, alertEventListener, instrumentService, historicalPriceService); alert.init(); synchronized (alertsMapping) { Collection<Alert> alertsEntry = alertsMapping.get(alert.getInstrumentId()); if (null == alertsEntry) { alertsEntry = Lists.newArrayList(); alertsMapping.put(alert.getInstrumentId(), alertsEntry); dispatchInstrumentSubscriptionRequired(alert.getInstrumentId()); } alertsEntry.add(alert); hasAlerts = !alertsMapping.isEmpty(); } LOGGER.info( String.format("Alert [%s] for [%s] loaded.", alert.getId(), alert.getInstrumentId())); } private boolean unLoadAlert(String alertId) throws Exception { checkNotNullOrEmpty(alertId); for (Map.Entry<String, Collection<Alert>> entry : alertsMapping.entrySet()) { for (Alert alert : entry.getValue()) { if (alertId.equals(alert.getId())) { entry.getValue().remove(alert); if (entry.getValue().isEmpty()) { alertsMapping.remove(entry.getKey()); dispatchInstrumentUnSubscriptionRequired(entry.getKey()); } LOGGER.info(String.format("Alert [%s] unloaded.", alertId)); if (hasAlerts && alertsMapping.isEmpty()) { hasAlerts = !alertsMapping.isEmpty(); } return true; } } } return false; } private final class InternalAlertListener implements AdviserListener<AlertEvent> { @Override public void onEvent(AlertEvent event) { eventNotificationService.notifyAlertEventAsync(event); // TODO(robertom): Non-repeat event remains in memory, however they should be removed. } } }
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.lib.SA; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; import jdk.test.lib.Asserts; import jdk.test.lib.Platform; import jtreg.SkippedException; public class SATestUtils { public static boolean canAddPrivileges() throws IOException, InterruptedException { List<String> echoList = new ArrayList<String>(); echoList.add("sudo"); echoList.add("-E"); echoList.add("/bin/echo"); echoList.add("'Checking for sudo'"); ProcessBuilder pb = new ProcessBuilder(echoList); Process echoProcess = pb.start(); if (echoProcess.waitFor(60, TimeUnit.SECONDS) == false) { // 'sudo' has been added but we don't have a no-password // entry for the user in the /etc/sudoers list. Could // have timed out waiting for the password. Skip the // test if there is a timeout here. System.out.println("Timed out waiting for the password to be entered."); echoProcess.destroyForcibly(); return false; } if (echoProcess.exitValue() == 0) { return true; } java.io.InputStream is = echoProcess.getErrorStream(); String err = new String(is.readAllBytes()); System.out.println(err); // 'sudo' has been added but we don't have a no-password // entry for the user in the /etc/sudoers list. Check for // the sudo error message and skip the test. if (err.contains("no tty present") || err.contains("a password is required")) { return false; } else { throw new Error("Unknown Error from 'sudo'"); } } public static List<String> addPrivileges(List<String> cmdStringList) throws IOException { Asserts.assertTrue(Platform.isOSX()); System.out.println("Adding 'sudo -E' to the command."); List<String> outStringList = new ArrayList<String>(); outStringList.add("sudo"); outStringList.add("-E"); outStringList.addAll(cmdStringList); return outStringList; } public static void unzipCores(File dir) { File[] gzCores = dir.listFiles((directory, name) -> name.matches("core(\\.\\d+)?\\.gz")); for (File gzCore : gzCores) { String coreFileName = gzCore.getName().replace(".gz", ""); System.out.println("Unzipping core into " + coreFileName); try (GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(gzCore)); FileOutputStream fos = new FileOutputStream(coreFileName)) { byte[] buffer = new byte[1024]; int length; while ((length = gzis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } catch (IOException e) { throw new SkippedException("Not able to unzip file: " + gzCore.getAbsolutePath(), e); } } } }
package com.huawei.esdk.demo.autogen; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for SiteInfoEx complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SiteInfoEx"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="uri" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="type" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="from" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="dialingMode" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="rate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="videoFormat" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="videoProtocol" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="status" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SiteInfoEx", propOrder = { "name", "uri", "type", "from", "dialingMode", "rate", "videoFormat", "videoProtocol", "status" }) public class SiteInfoEx { protected String name; protected String uri; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter2 .class) @XmlSchemaType(name = "int") protected Integer type; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter2 .class) @XmlSchemaType(name = "int") protected Integer from; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter2 .class) @XmlSchemaType(name = "int") protected Integer dialingMode; protected String rate; @XmlElement(type = String.class) @XmlJavaTypeAdapter(Adapter2 .class) @XmlSchemaType(name = "int") protected Integer videoFormat; @XmlElement(type = String.class) @XmlJavaTypeAdapter(Adapter2 .class) @XmlSchemaType(name = "int") protected Integer videoProtocol; @XmlElement(type = String.class) @XmlJavaTypeAdapter(Adapter2 .class) @XmlSchemaType(name = "int") protected Integer status; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the uri property. * * @return * possible object is * {@link String } * */ public String getUri() { return uri; } /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setUri(String value) { this.uri = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public Integer getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(Integer value) { this.type = value; } /** * Gets the value of the from property. * * @return * possible object is * {@link String } * */ public Integer getFrom() { return from; } /** * Sets the value of the from property. * * @param value * allowed object is * {@link String } * */ public void setFrom(Integer value) { this.from = value; } /** * Gets the value of the dialingMode property. * * @return * possible object is * {@link String } * */ public Integer getDialingMode() { return dialingMode; } /** * Sets the value of the dialingMode property. * * @param value * allowed object is * {@link String } * */ public void setDialingMode(Integer value) { this.dialingMode = value; } /** * Gets the value of the rate property. * * @return * possible object is * {@link String } * */ public String getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is * {@link String } * */ public void setRate(String value) { this.rate = value; } /** * Gets the value of the videoFormat property. * * @return * possible object is * {@link String } * */ public Integer getVideoFormat() { return videoFormat; } /** * Sets the value of the videoFormat property. * * @param value * allowed object is * {@link String } * */ public void setVideoFormat(Integer value) { this.videoFormat = value; } /** * Gets the value of the videoProtocol property. * * @return * possible object is * {@link String } * */ public Integer getVideoProtocol() { return videoProtocol; } /** * Sets the value of the videoProtocol property. * * @param value * allowed object is * {@link String } * */ public void setVideoProtocol(Integer value) { this.videoProtocol = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link String } * */ public Integer getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link String } * */ public void setStatus(Integer value) { this.status = value; } }
package com.tencent.mm.plugin.ipcall; import com.tencent.mm.g.a.ho; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.x; class a$1 implements Runnable { final /* synthetic */ a knP; a$1(a aVar) { this.knP = aVar; } public final void run() { x.d("MicroMsg.IPCallAddressBookUsernameUpdater", "start GetMFriend"); ho hoVar = new ho(); hoVar.bQU.scene = 2; a.sFg.m(hoVar); a.a(this.knP, System.currentTimeMillis()); } }
package org.jcarvajal.webapp.utils; import java.util.HashMap; import java.util.Map; public class StringUtils { /** * Check whether a string is empty or not. * @param value * @return */ public static boolean isNotEmpty(String value) { return value != null && !value.trim().isEmpty(); } public static Map<String, String> map(String text, String paramSep, String fieldSep) { Map<String, String> params = new HashMap<String, String>(); if (text != null) { String[] paramsSplit = text.split(paramSep); for (String param : paramsSplit) { String[] fields = param.split(fieldSep); String value = null; if (fields.length > 1) { value = fields[1]; } params.put(fields[0].trim(), value); } } return params; } }