text
stringlengths
10
2.72M
package com.jianwuch.giaifu.module; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.chad.library.adapter.base.BaseQuickAdapter; import com.jianwuch.giaifu.R; import com.jianwuch.giaifu.model.BaseHttpResult; import com.jianwuch.giaifu.model.GifImageBean; import com.jianwuch.giaifu.model.SearchResultDataBean; import com.jianwuch.giaifu.module.adapter.SearGifAdapter; import com.jianwuch.giaifu.net.DownloadService; import com.jianwuch.giaifu.net.GifImagerRequest; import com.jianwuch.giaifu.net.RetrofitInstance; import com.jianwuch.giaifu.util.LogUtil; import com.jianwuch.giaifu.util.ShareFileUtils; import com.jianwuch.giaifu.util.ToastUtils; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import okhttp3.ResponseBody; /** * A fragment representing a list of Items. * <p /> * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} * interface. */ public class ItemFragment extends Fragment { private static final String KEY_SEARCH_NAME = "search_name"; private final static String TAG = ItemFragment.class.getSimpleName(); private final static int PAGE_COUNT = 22; private int currentPage = 0; private int start = 0; private int total; private SearGifAdapter mAdapter; private String searchName; private ViewGroup mRootView; private RecyclerView recyclerView; private SwipeRefreshLayout spLayout; private boolean isRefleshing; private boolean isLoadingMore; public ItemFragment() { } @SuppressWarnings("unused") public static ItemFragment newInstance(String name) { ItemFragment fragment = new ItemFragment(); Bundle args = new Bundle(); args.putString(KEY_SEARCH_NAME, name); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { searchName = getArguments().getString(KEY_SEARCH_NAME); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_item_list, container, false); spLayout = mRootView.findViewById(R.id.sp_layout); return mRootView; } private void initView(View view) { Context context = view.getContext(); recyclerView = view.findViewById(R.id.list); mAdapter = new SearGifAdapter(); recyclerView.setLayoutManager(new GridLayoutManager(context, 2)); recyclerView.setAdapter(mAdapter); recyclerView.setHasFixedSize(true); spLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (isRefleshing) { return; } currentPage = 0; start = 0; loadData(searchName); isRefleshing = true; } }); mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() { @Override public void onLoadMoreRequested() { if (isLoadingMore) { return; } start = (++currentPage) * PAGE_COUNT; if (total != 0 && start + PAGE_COUNT >= total) { mAdapter.loadMoreEnd(); } loadData(searchName); isLoadingMore = true; } }, recyclerView); mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() { @Override public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) { GifImageBean bean = ((GifImageBean) adapter.getData().get(position)); String gifUrl = bean.url; String title = bean.title.trim(); Toast.makeText(context, "ๅพฎไฟกๅˆ†ไบซ" + position, Toast.LENGTH_SHORT).show(); RetrofitInstance.getInstance() .create(DownloadService.class) .downloadFile(gifUrl) .subscribeOn(Schedulers.io()) .map(new Function<ResponseBody, InputStream>() { @Override public InputStream apply(ResponseBody responseBody) throws Exception { LogUtil.d(TAG, "ๅฝ“ๅ…ˆ็บฟ็จ‹1"+Thread.currentThread().getName()); return responseBody.byteStream(); } }) .observeOn(Schedulers.computation()) .doOnNext(new Consumer<InputStream>() { @Override public void accept(InputStream inputStream) throws Exception { LogUtil.d(TAG, "ๅฝ“ๅ…ˆ็บฟ็จ‹2"+Thread.currentThread().getName()); String path = getActivity().getExternalFilesDir("gif_files") .getAbsolutePath(); File saveFile = new File(path + File.separator + title + ".gif"); FileOutputStream fos = new FileOutputStream(saveFile); byte[] b = new byte[1024]; int length; while ((length = inputStream.read(b)) > 0) { fos.write(b, 0, length); } inputStream.close(); fos.close(); } }) .map(new Function<InputStream, File>() { @Override public File apply(InputStream inputStream) throws Exception { LogUtil.d(TAG, "ๅฝ“ๅ…ˆ็บฟ็จ‹3"+Thread.currentThread().getName()); String path = getActivity().getExternalFilesDir("gif_files") .getAbsolutePath(); File saveFile = new File(path + File.separator + title + ".gif"); return saveFile; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<File>() { @Override public void accept(File file) throws Exception { LogUtil.d(TAG, "ๅฝ“ๅ…ˆ็บฟ็จ‹4"+Thread.currentThread().getName()); ShareFileUtils.shareImageToWeChat(getActivity(), file.getAbsolutePath()); } }); } }); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(mRootView); loadData(searchName); } private void loadData(String name) { RetrofitInstance.getInstance() .create(GifImagerRequest.class) .searchGif(name, "timestamp_0", start, PAGE_COUNT, 0) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<BaseHttpResult<SearchResultDataBean>>() { @Override public void onError(Throwable e) { Toast.makeText(getActivity(), "ๆœๅŠกๅ™จๅ‘็”Ÿ้”™่ฏฏ", Toast.LENGTH_SHORT).show(); isRefleshing = false; isLoadingMore = false; mAdapter.loadMoreFail(); } @Override public void onComplete() { isRefleshing = false; isLoadingMore = false; } @Override public void onSubscribe(Disposable d) { } @Override public void onNext( BaseHttpResult<SearchResultDataBean> searchResultDataBeanBaseHttpResult) { List<GifImageBean> data = mAdapter.getData(); if (isRefleshing) { mAdapter.setNewData(searchResultDataBeanBaseHttpResult.data.list); } else { if (data == null || mAdapter.getData().size() == 0) { mAdapter.setNewData(searchResultDataBeanBaseHttpResult.data.list); } else { mAdapter.addData(searchResultDataBeanBaseHttpResult.data.list); } } mAdapter.loadMoreComplete(); mAdapter.notifyDataSetChanged(); spLayout.setRefreshing(false); isRefleshing = false; isLoadingMore = false; total = searchResultDataBeanBaseHttpResult.data.resuLtTotal; } }); } private void shareToWechat(File file) { if (!file.exists()) { return; } Intent intent = new Intent(Intent.ACTION_SEND); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); //ไผ ่พ“ๅ›พ็‰‡ๆˆ–่€…ๆ–‡ไปถ ้‡‡็”จๆต็š„ๆ–นๅผ intent.setType("*/*"); //ๅˆ†ไบซๆ–‡ไปถ getActivity().startActivity(Intent.createChooser(intent, "ๅˆ†ไบซ")); } }
/* * ๋ชจ๋“  ํ•˜์œ„ ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ๋ฐ˜๋“œ์‹œ ๊ตฌํ˜„ํ•ด์•ผ ํ•  ๋ฉ”์„œ๋“œ๋ฅผ ์ •์˜ํ•œ๋‹ค. * */ package com.model2.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface Controller { //์•Œ๋งž๋Š” ๋น„์ฆˆ๋‹ˆ์Šค ๊ฐ์ฒด์— ์ผ์‹œํ‚ค๊ธฐ. public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; //์–ด๋–ค ๋ทฐ ํŽ˜์ด์ง€๋ฅผ ๋ณด์—ฌ์ค˜์•ผ ํ• ์ง€ //๋งŒ์ผ ํ•˜์œ„ ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ์ด ์—…๋ฌด๋ฅผ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š์œผ๋ฉด, DispatcherServlet์—์„œ if๋ฌธ์„ ๋˜ ์ฒ˜๋ฆฌํ•ด์•ผํ•œ๋‹ค //if๋ฌธ์„ ์—†์• ๊ธฐ ์œ„ํ•ด ๋ฉ”์„œ๋“œ ์ถ”๊ฐ€ public String getResultView(); //์š”์ฒญ์„ ๋Š์–ด์•ผํ• ์ง€, ์œ ์ง€ํ•ด์•ผํ• ์ง€๋ฅผ ๊ฒฐ์ •ํ•˜๋Š” ๋ฉ”์„œ๋“œ public boolean isForward(); }
package com.ljh.dto; /** * @Author laijinhan * @date 2020/9/24 4:52 ไธ‹ๅˆ */ public class Dog { public void show(){ System.out.println("ๆˆ‘ๆ˜ฏไธ€ๅช็‹—"); } }
package com.in28minutes.rest.restfulwebservices; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ControllerErrorHandler { @ExceptionHandler(Exception.class) public ResponseEntity<errorResponse> handleError(Exception e) { errorResponse er = new errorResponse(); er.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); er.setErrorMessage(e.getMessage()); return new ResponseEntity<errorResponse>(er,HttpStatus.INTERNAL_SERVER_ERROR); } }
/* __ * \ \ * _ _ \ \ ______ * | | | | > \( __ ) * | |_| |/ ^ \| || | * | ._,_/_/ \_\_||_| * | | * |_| * * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <rob โˆ‚ CLABS dot CC> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. * ---------------------------------------------------------------------------- */ package cc.clabs.stratosphere.mlp.utils; import cc.clabs.stratosphere.mlp.types.Sentence; import cc.clabs.stratosphere.mlp.types.Word; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author rob */ public class SentenceUtils { private static final Log LOG = LogFactory.getLog( SentenceUtils.class ); public final static String WILDCARD = "*"; public final static String MORE = "+"; public static Sentence replaceAllByPattern( Sentence sentence, String regex, String withTag ) { for ( Word word: sentence ) if ( word.getWord().matches( regex ) ) word.setTag( withTag ); return sentence; } public static Sentence replaceAllByTag( Sentence sentence, String tag, String regex, String replacement ) { for ( Word word : sentence ) // skip other words than those with a specific tag if ( word.getTag().equals( tag ) ) { String text = word.getWord(); text = text.replaceAll( regex, replacement ); word.setWord( text ); } return sentence; } /** * Joins a set of PactWords, described by a pattern, * together with a given tag into a new Word within * the sentence. A pattern is a string containing tags * and wildcards where every part is separated by a space * character. * * @param sentence the sentence * @param pattern a string containing the pattern * @param withTag tag given to new PactWords * * @return a new sentence with the joined PactWords */ public static Sentence joinByTagPattern( Sentence sentence, String pattern, String withTag ) { Sentence result = new Sentence(); String[] tags = pattern.trim().split( " " ); // nothing to compare to if ( tags.length == 0 ) return sentence; // pattern can never be matched if ( tags.length > sentence.size() ) return sentence; int ptr = 0; boolean isRangeTag = false; String curTag = "", nexTag = "", prevTag = "", poo = "\uD83D\uDCA9"; ArrayList<Word> candidates = new ArrayList<>(); // for every word โ€ฆ for ( Word word : sentence ) { // get the tags form tags array prevTag = ( ptr - 1 >= 0 ) ? tags[ ptr - 1 ] : poo; curTag = ( ptr < tags.length ) ? tags[ ptr ] : poo; nexTag = ( ptr + 1 < tags.length ) ? tags[ ptr + 1 ] : poo; // is range tag? isRangeTag = curTag.equals( WILDCARD ) || curTag.equals( MORE ); if ( isRangeTag ) { // current tag is wildcard symbol if ( curTag.equals( WILDCARD ) ) { // when the tag of the next word matches if ( word.getTag().contains( nexTag ) ) { candidates.add( word ); result.add( new Word( joinPactWords( candidates ), withTag ) ); candidates.clear(); ptr += 1; // otherwise add the current word to the concat } else { // concatenate the current word candidates.add( word ); } } // current tag is a more symbol else if ( curTag.equals( MORE ) ) { // when the tag of the next word matches if ( word.getTag().contains( nexTag ) ) { candidates.add( word ); result.add( new Word( joinPactWords( candidates ), withTag ) ); candidates.clear(); ptr += 2; // otherwise check if the previous tag matches } else if ( word.getTag().contains( prevTag ) ) { candidates.add( word ); // when nothing matches flush everything to the results } else { // at least two hits need to be found if ( candidates.size() > 1 ) { result.add( new Word( joinPactWords( candidates ), withTag ) ); } else { result.addAll( candidates ); } candidates.clear(); result.add( word ); ptr = 0; } } } // simple tag else { // the current tag matches the tag of the word if ( word.getTag().contains( curTag ) ) { // concatenate the current word candidates.add( word ); // and increment the position of pattern array ptr += 1; // current tag doesn't match } else { if ( !candidates.isEmpty() ) { result.addAll( candidates ); candidates.clear(); } ptr = 0; result.add( word ); } // reset the position if needed if ( ptr >= tags.length ) { result.add( new Word( joinPactWords( candidates ), withTag ) ); candidates.clear(); ptr = 0; } } } // deal with a possible remainders if ( !candidates.isEmpty() ) { // join candidates together if last tag was ranged if ( isRangeTag ) { result.add( new Word( joinPactWords( candidates ), withTag ) ); // otherwise simply add candidates to the results } else { result.addAll( candidates ); } candidates.clear(); } return result; } public static class Tuple<X, Y> { public final X first; public final Y second; public Tuple(X x, Y y) { this.first = x; this.second = y; } } /** * * @param sentence * @param pattern * @return */ public static Integer findByPattern( Sentence sentence, String patternstring ) { String[] parts = patternstring.split( "\t" ); ArrayList<Tuple<String,Pattern>> test = new ArrayList<>(); for ( String part : parts ) { String type = ( part.matches( "^\\(.*?\\)$" ) ) ? "tag" : "word"; part = part.replaceAll( "^\\(|\\)$", "" ); Pattern p = Pattern.compile( "\\A" + part + "\\z", Pattern.CASE_INSENSITIVE ); test.add( new Tuple( type, p ) ); } // quickwins ;) if ( test.isEmpty() ) return -1; if ( sentence.size() < test.size() ) return -1; String type, word; Word pWord; Pattern pattern; Matcher m; for (Integer i = 0, j = 0; i < sentence.size(); i += 1 ) { if ( j < test.size() ) { type = test.get( j ).first; pattern = test.get( j ).second; pWord = sentence.get( i ); word = ( type.equals( "tag" ) ) ? pWord.getTag() : pWord.getWord(); m = pattern.matcher( word ); if ( m.find() ) { // found j += 1; } else { // reset i -= j; j = 0; } } else { // found match return i-j; } } // nothing found return -1; } /** * * @param candidates * @return */ private static String joinPactWords( List<Word> candidates ) { String result = ""; for( Word word : candidates ) result += word.getWord() + " "; return result.trim(); } }
package com.factory.factoryviewdetails.dao; import com.factory.factoryviewdetails.model.ApplicationModel; import java.util.List; /** * Author: Amit * Date: 02-01-2020 */ public interface ApplicationViewDao { public List<ApplicationModel> getAllApplicationDetailsFromDb(); public List<ApplicationModel> getSingleApplicationDetailsByIdFromDb(int id); }
package com.cloudgame.nativeaudiorecoder; public class AudioRecorder { static { System.loadLibrary("native-recorder"); } public native void startRecord(int sampleRate, int channels, int bitRate, String pcmPath); public native void stopRecord(); }
package com.oxymore.practice.match.arena; import com.oxymore.practice.configuration.match.ArenaConfiguration; import lombok.Data; import org.bukkit.util.BlockVector; import java.io.File; import java.util.List; @Data public class Arena { private final ArenaConfiguration configuration; private final File schematicFile; private final BlockVector centerPoint; private final List<BlockVector> spawnLocations; }
package com.zhicai.byteera.service.serversdk; @SuppressWarnings("static-access") public abstract class IThread { private Thread m_thread; private boolean _run = false; public int start() { if (_run) return 0; if (_prepare() < 0) { System.out.println("Prepare fail!"); return -1; } _run = true; m_thread = new Thread(new Runnable() { @Override public void run() { while (_run) { _kernel(); try { m_thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); m_thread.start(); return 0; } public int stop() { if ( !_run ) return -1; _run = false; try { m_thread.join(50); } catch (InterruptedException e) { e.printStackTrace(); } _finish(); return 0; } abstract int _prepare(); abstract int _kernel(); abstract void _finish(); }
package inheritance; import java.util.Scanner; /** * @file_name : Phone.java * @author : dingo44kr@gmail.com * @date : 2015. 9. 30. * @story : ์ƒ์†์˜ˆ์ œ */ public class PhoneMain { // ๊ฐ€์žฅ๋ฉ”์ธ, ํ•œ๋…€์„๋งŒ ์žˆ์–ด์•ผ๋จ. // ํ”„๋กœ์ ํŠธ > ํŒจํ‚ค์ง€ > ํด๋ž˜์Šค > ๋ฉ”์„œ๋“œ > ๊ตฌ๋ฌธ /** * */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // ์ธ์Šคํ„ด์Šค => ์ฐธ์กฐ๋ณ€์ˆ˜ Phone androidPhone = new AndroidPhone(); System.out.println("๊ตฌ๋งคํ•  ์‚ฌ์ด์ฆˆ ์„ ํƒ"); String size = scanner.next(); System.out.println("์•ˆ๋“œ๋กœ์ด๋“œํฐ์œผ๋กœ ํ†ตํ™”ํ•  ์‚ฌ๋žŒ"); String name2 = scanner.next(); System.out.println("๋ณด๋‚ผ ๋ฉ”์‹œ์ง€ ์ž…๋ ฅ"); String msg2 = scanner.next(); ((AndroidPhone) androidPhone).setData(msg2, name2, size); System.out.println(((AndroidPhone) androidPhone).getData()); System.out.println("==================="); Phone iphone = new Iphone(); System.out.println("์•„์ดํฐ์œผ๋กœ ํ†ตํ™”ํ•  ์‚ฌ๋žŒ"); String name = scanner.next(); System.out.println("๋ณด๋‚ผ ๋ฉ”์‹œ์ง€ ์ž…๋ ฅ"); String msg = scanner.next(); ((Iphone) iphone).setData(msg, name); System.out.println(((AndroidPhone) iphone).getData()); System.out.println("=================="); Phone nokia = new Celphone(); nokia.setCompany("๋…ธํ‚ค์•„"); System.out.println(nokia.getCompany()+"๋ฅผ ์‚ฌ์šฉ"); System.out.println("ํœด๋Œ€ํฐ์œผ๋กœ ํ†ตํ™”ํ•  ์‚ฌ๋žŒ"); nokia.setCall(scanner.next()); System.out.println(nokia.getCall()); System.out.println("====================="); Phone phone = new Phone(); // ํƒ€์ž… ์ธ์Šคํ„ด์Šค(๊ฐ์ฒด) = new ์ƒ์„ฑ์ž phone.setCompany("์‚ผ์„ฑ ์ง‘์ „ํ™”๊ธฐ"); System.out.println(phone.getCompany() + "๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค."); System.out.println("ํ†ตํ™”ํ•  ์‚ฌ๋žŒ"); phone.setCall(scanner.next()); System.out.println(phone.getCall()); } } class Iphone extends Celphone{ private String data; // ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜ public static String BRAND = "์•„์ดํฐ"; // static ์€ ๊ณ ์ •๋œ ์ด๋ž€ ์˜๋ฏธ๋กœ // ์•„์ดํฐ์ด๋ผ๋Š” ๋ธŒ๋žœ๋“œ ์ด๋ฆ„์€ ๋ฐ”๊ฟ€ ์ˆ˜ ์—†๋‹ค. // static ์ด ๋ถ™์€ ๋ณ€์ˆ˜๋Š” ํด๋ž˜์Šค๋ณ€์ˆ˜๋ผ๊ณ ๋„ ํ•œ๋‹ค. // "๊ฑด๋ฌผ" public static boolean TRUE = true; public String getData() { return data; } public void setData(String data) { this.data = data; } public void setData(String data, String name) { // ์˜ค๋ฒ„๋กœ๋”ฉ("์ถ”๊ฐ€ ์ ์žฌ", ์ฑ… ์ฐธ์กฐ) super.setCompany(BRAND); // ๋ถ€๋ชจ๋‹˜๊ฒƒ์„ ๊ทธ๋Œ€๋กœ ๊ฐ€์ ธ์˜จ๋‹ค(ํŠœ๋‹๋„ ์•ˆํ•˜๊ณ ) super. // ์• ํ”Œ์€ ์—ฌ๋Ÿฌ๋ธŒ๋žœ๋“œ๋ฅผ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ๋ฌด์กฐ๊ฑด ์•„์ดํฐ์ด๋ผ ํ•œ๋‹ค.(static) super.setPortable(TRUE); // ์• ํ”Œ์€ ์ง‘์ „ํ™”๊ธฐ๋Š” ์•ˆ๋งŒ๋“ค๊ณ  ๋ฌด์กฐ๊ฑด ํœด๋Œ€ํฐ๋งŒ ๋งŒ๋“ ๋‹ค. super.setCall(name); this.data = super.getCompany()+"\t" +super.isPortable()+"\t" + super.getCall() + "\t" + data + " : ๋ฉ”์‹œ์ง€ ์ „๋‹ฌ"; } } class AndroidPhone extends Iphone{ public static String BRAND = "์•ˆ๋“œ๋กœ์ด๋“œํฐ"; // ์˜ค๋ฒ„๋ผ์ด๋”ฉ private String size; private String data; public String getSize() { return size; } public void setSize(String size) { this.size = size; } public void setData(String data, String name, String size) { super.setCompany(BRAND); super.setPortable(TRUE); super.setCall(name); this.setSize(size); this.data = super.getCompany()+"\t" + super.isPortable()+"\t" + super.getCall()+"\t" + "๋Œ€ํ™”๋ฉด" +this.getSize()+"๋กœ ๋ณผ ์ˆ˜ ์žˆ์Œ\t" + data+" : ์นดํ†ก๋ฉ”์‹œ์ง€ ์ „๋‹ฌ"; } @Override public String getData() { return data; } } class Phone { private String company, call; // ์ธ์Šคํ„ด์Šค(์˜) ๋ณ€์ˆ˜ => ํž™์˜์—ญ์œผ๋กœ // ALT + SHIFT + S + R = ๊ฒŸํ„ฐ์…‹ํ„ฐ final static double TAX_RATE = 0.095; // ์Šคํƒœํ‹ฑ ๋ณ€์ˆ˜ => Global variable ์ „์—ญ๋ณ€์ˆ˜ // (์ง€์—ญ๋ณ€์ˆ˜์˜ ๋ฐ˜๋Œ€๊ฐœ๋…) => ์Šคํƒœํ‹ฑ ์˜์—ญ์œผ๋กœ // ์ด TAX_RATE๋Š”, ํ”„๋กœ์ ํŠธ ์ „์—ญ์— ์˜ํ–ฅ์„ ๋ฏธ์นœ๋‹ค. public String getCompany() { return company; } public void setCompany(String company) { this.company = company; // ์ง€์—ญ(์˜) ๋ณ€์ˆ˜ Or (๋ฉ”์„œ๋“œ์˜ ๋ณ€์ˆ˜) =>์Šคํƒ์ด๋ผ๋Š” ์˜์—ญ์œผ๋กœ... } public String getCall() { return call; } public void setCall(String call) { this.call = call + "์—๊ฒŒ ์ „ํ™”๋ฅผ ๊ฒ€"; } } class Celphone extends Phone { private boolean portable; // ์ด๋™์„ฑ... ๊ฐ€์ง€๊ณ  ๋‹ค๋‹ ์ˆ˜ ์žˆ๋А๋ƒ ์—†๋А๋ƒ? private String move; public boolean isPortable() { return portable; } public void setPortable(boolean portable) { if (portable) { this.setMove("ํฐ์„ ๊ฐ€์ง€๊ณ  ๋‹ค๋‹ ์ˆ˜ ์žˆ์Œ"); } else { this.setMove("ํฐ์„ ๊ฐ€์ง€๊ณ  ๋‹ค๋‹ ์ˆ˜ ์—†์Œ"); } this.portable = portable; } public String getMove() { return move; } public void setMove(String move) { this.move = move; } }
//Program to show the use of interface i:e style in java //Defining interface(style) interface Automobile{ void gear(); void brak(); }//close of interface //defining class Maruti class maruti implements Automobile { public void gear(){ System.out.println("Four gear in Action"); } public void brak(){ System.out.println("Normale break in Action"); } }//close of class maruti //defining class Honda class Honda implements Automobile { public void gear(){ System.out.println("Five gear in Action"); } public void brak(){ System.out.println("Power break in Action"); } }//close of class Honda //Defining main class class InterFace{ public static void main(String args[]){ maruti m=new maruti(); Honda h=new Honda(); Automobile A; A=m; A.gear(); A=h; A.brak(); }//close of main }//close of main class
package com.example.ccripplebutton; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by henryzheng on 2017/2/27. */ public class RippleDrawable extends Drawable { private float touchX, touchY; Callback callback; private int width = 0; private int height = 0; public float mAlpha; private AnimatorSet set; int defaultAlpha = 48; List<ChangeData> changeDatas = new ArrayList<>(); private Paint paint; private int rediu = 0; public RippleDrawable(Callback c) { // mPaint = new Paint(); // mPaint.setColor(0x30000000); // mPaint.setAlpha(defaultAlpha); callback = c; setCallback(callback); set = new AnimatorSet(); } @Override public void draw(Canvas canvas) { for (int i = 0; i < changeDatas.size(); i++) { canvas.drawCircle(changeDatas.get(i).getTouchX(), changeDatas.get(i).getTouchY(), changeDatas.get(i).getRedic(), changeDatas.get(i).getPaint()); } } @Override public void setAlpha(int i) { } @Override public void setColorFilter(ColorFilter colorFilter) { } @Override public int getOpacity() { return PixelFormat.UNKNOWN; } public void onTouchEvent(final MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { touchX = event.getX(); touchY = event.getY(); final Paint mPaint = new Paint(); mPaint.setColor(0x30000000); mPaint.setAlpha(defaultAlpha); final int[] mRadius = {0}; changeDatas.add(new ChangeData(touchX, touchY, rediu, mPaint)); final Iterator<ChangeData> itear = changeDatas.iterator(); final ChangeData data = itear.next(); final float maxRadius = (float) Math.pow(Math.pow(width, 2) + Math.pow(height, 2), 0.5); final ObjectAnimator anim1 = ObjectAnimator// .ofFloat(this, "draw", 0F, maxRadius)// .setDuration(500);// final ObjectAnimator anim2 = ObjectAnimator// .ofFloat(this, "alpha", defaultAlpha, 0)// .setDuration(200);// anim1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float changeValue = (float) animation.getAnimatedValue(); mRadius[0] = (int) (changeValue); data.setRedic(mRadius[0]); invalidateSelf(); } }); anim2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float changeValue = (float) animation.getAnimatedValue(); mPaint.setAlpha((int) changeValue); data.setPaint(mPaint); invalidateSelf(); } }); anim1.start(); anim2.start(); } } // // // touchX = event.getX(); // touchY = event.getY(); // // Paint paint=new Paint(); // paint.setColor(0x30000000); // paint.setAlpha(defaultAlpha); // int rediu=0; // // // // final float mRadius= (float) Math.pow(Math.pow(width,2)+Math.pow(height,2),0.5); // final ObjectAnimator anim1 = ObjectAnimator// // .ofFloat(this, "draw", 0F, mRadius)// // .setDuration(500);// // final ObjectAnimator anim2 = ObjectAnimator// // .ofFloat(this, "alpha", defaultAlpha, 0)// // .setDuration(200);// // anim1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() // { // @Override // public void onAnimationUpdate(ValueAnimator animation) // { // float changeValue= (float) animation.getAnimatedValue(); // rediu = (int) (changeValue); // invalidateSelf(); // } // }); // // anim2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() // { // @Override // public void onAnimationUpdate(ValueAnimator animation) // { // float changeValue= (float) animation.getAnimatedValue(); // mAlpha = changeValue; // mPaint.setAlpha((int) mAlpha); // invalidateSelf(); // } // }); // // set.play(anim2).after(anim1); // // set.start(); // set.addListener(new Animator.AnimatorListener() { // @Override // public void onAnimationStart(Animator animation) { // // } // // @Override // public void onAnimationEnd(Animator animation) { // // } // // @Override // public void onAnimationCancel(Animator animation) { // mPaint.setAlpha(0); // radius=0; // invalidateSelf(); // CCLog.e("set onAnimationCancel"); // // } // // @Override // public void onAnimationRepeat(Animator animation) { // // } // }); // // } public void setWH(int width, int height) { this.width = width; this.height = height; } }
package ir.vasl.navigationcomponentimpl.viewModels; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import java.util.List; import ir.vasl.navigationcomponentimpl.models.CharacterModel; import ir.vasl.navigationcomponentimpl.repository.Repository; public class CharacterViewModel extends NetworkViewModel { private MutableLiveData<List<CharacterModel.Result>> liveData = new MutableLiveData<>(); public CharacterViewModel() { generateCharacters(); } public LiveData<List<CharacterModel.Result>> getLiveData() { return liveData; } public void setLiveData(List<CharacterModel.Result> resultList) { this.liveData.postValue(resultList); } public void generateCharacters() { Repository.getInstance().getCharacters(this); } }
package com.raymon.consumer.controller; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; /** * * ๅคš็บฟ็จ‹ๅฎž็Žฐ0-100่ฎกๆ•ฐ */ public class ThreadCount { public static List<Future> futureList=new ArrayList<Future>(); public static void main(String[] args) throws InterruptedException, ExecutionException { int sum=0; ThreadCount add = new ThreadCount(); ExecutorService pool= Executors.newFixedThreadPool(4); for(int i = 1; i <= 76;){ ThreadTest thread = add.new ThreadTest(i,i+24); Future<Integer> future=pool.submit(thread); futureList.add(future); i += 25; } if(futureList!=null && futureList.size()>0){ for(Future<Integer> future:futureList){ sum += (Integer)future.get(); } } System.out.println("total result: "+sum); pool.shutdown(); } class ThreadTest implements Callable<Integer> { private int begin; private int end; private int sum=0; public ThreadTest(int begin, int end) { this.begin = begin; this.end = end; } @Override public Integer call() throws Exception { for(int i = begin; i <= end; i++){ sum += i; } System.out.println("from "+Thread.currentThread().getName()+" sum="+sum); return sum; } } }
package com.masters.config; import com.masters.security.Constants; import com.masters.security.jwt.JWTConfigurer; import com.masters.security.jwt.TokenProvider; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; /** * Created by bartosz on 17.01.18. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private TokenProvider tokenProvider; public SecurityConfiguration(TokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } @Override protected void configure(HttpSecurity http) throws Exception { //.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) http.csrf().disable().authorizeRequests() .antMatchers("/api/register").permitAll() .antMatchers("/api/authorize").permitAll() .antMatchers("/api/categories").permitAll() .antMatchers("/api/user").authenticated() .antMatchers("/api/user/**").authenticated() .antMatchers("/api/advert").authenticated() .antMatchers("/api/adverts").permitAll() .antMatchers("/api/advert/add").permitAll() .antMatchers("/api/advert/user").authenticated() .antMatchers("/api/advert/*").permitAll() .anyRequest().authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .apply(JWTSecurityAdapter()); } private JWTConfigurer JWTSecurityAdapter() { return new JWTConfigurer(this.tokenProvider); } /** * Login by memory user */ /* @Autowired protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("user") .authorities("ROLE_USER"); }*/ }
package com.xwolf.eop.system.service; import com.xwolf.eop.system.entity.RoleMenu; /** * @author wolf * @date 2016-12-27 23:31 * @since V1.0.0 */ public interface IRoleMenuService extends BaseService<RoleMenu> { }
class Vehicle { public int speed; public int direction; public String name; public static int number; public int carID; public static void main(String args[]){ Vehicle car1 = new Vehicle(); car1.speed = 40; car1.direction = 60; car1.name = "A"; car1.number = 2; car1.carID = 1; Vehicle car2 = new Vehicle(); car2.speed = 50; car2.direction = 90; car2.name = "B"; car2.number = 3; car2.carID = 2; System.out.println("car1"); car1.print(); System.out.println("car2"); car2.print(); } public void print(){ System.out.println("speed: " + speed); System.out.println("direction: " + direction); System.out.println("name: " + name); System.out.println("carID: " + carID); } }
package com.moh.departments.fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.moh.departments.R; import com.moh.departments.activiteis.HomeActivity; import com.moh.departments.adapters.RadPhotoAdapter; import com.moh.departments.constants.Controller; import com.moh.departments.constants.CustomRequest; import com.moh.departments.models.RadphotoModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class radresFragment extends Fragment { private static RecyclerView.Adapter radPhotoAdapter; private static RecyclerView radrecyclerView; private static ArrayList<RadphotoModel> Carddata; TextView txtscnane, txtpatid, txtpatName; String patname, patid, indate; LinearLayout radheader; private RecyclerView.LayoutManager layoutManager; public radresFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_radres, container, false); patname = getArguments().getString("patname"); patid = getArguments().getString("patid"); indate = getArguments().getString("indate"); radrecyclerView = (RecyclerView) view.findViewById(R.id.radorder_recycler_view); radheader = view.findViewById(R.id.radheader); txtpatName = view.findViewById(R.id.txtpatName); txtpatid = view.findViewById(R.id.txtpatid); txtpatName.setText(patname); txtpatid.setText(patid); Carddata = new ArrayList<>(); radPhotoAdapter = new RadPhotoAdapter(Carddata, getContext()); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext()); radrecyclerView.setLayoutManager(mLayoutManager); radrecyclerView.setAdapter(radPhotoAdapter); prepareRadPhotoData(); setHasOptionsMenu(true);/// to disable icon from menu return view; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.action_dept); item.setVisible(false); super.onPrepareOptionsMenu(menu); } private void prepareRadPhotoData() { Map<String, String> map = new HashMap<>(); map.put("PATREC_CODE", patid); Log.e("PATREC_CODE", patid); // map.put("PATREC_CODE", "298933"); map.put("P_FROM_DATE", indate); // map.put("P_FROM_DATE", "04/04/2012"); Log.e("test", map.toString()); CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, Controller.GET_GET_PHOTO_RAD_URL, map, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { try { Log.e("jsonrad:", jsonObject.toString()); JSONArray RAD_ARR = (JSONArray) jsonObject.getJSONArray("RAD_REPORT"); Log.e("json", jsonObject.toString()); Log.e("json", "" + RAD_ARR.length()); if (RAD_ARR.length() > 0) { for (int i = 0; i < RAD_ARR.length(); i++) { JSONObject obj = RAD_ARR.getJSONObject(i); if (obj != null) { if (obj.getString("ORDER_CODE") != null) { RadphotoModel Card = new RadphotoModel( obj.getString("ORDER_DATE"), obj.getString("SERVICE_NAME_AR"), obj.getString("ORGAN_SERVICE_CD"), obj.getString("ORGAN_NAME_AR"), obj.getString("ORGAN_CODE"), obj.getString("MRP_ID") ); Carddata.add(Card); } } } } else { LinearLayout emptyEfile = (LinearLayout) getView().findViewById(R.id.emptyEfile_layout); radheader.setVisibility(View.GONE); emptyEfile.setVisibility(View.VISIBLE); } Log.e("json", "" + Carddata.size()); radrecyclerView.setAdapter(radPhotoAdapter); radPhotoAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); Log.e("json", "ERROR"); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError volleyError) { Log.e("json", "ErrorListener"); } }); Controller.getInstance().addToRequestQueue(jsObjRequest); } public void onResume() { super.onResume(); // Set title bar ((HomeActivity) getActivity()).setActionBarTitle("ู†ุชุงุฆุฌ ุงู„ุฃุดุนุฉ"); } }
package cn.fuyoushuo.fqbb.domain.entity; import java.io.Serializable; /** * Created by QA on 2016/11/11. */ public class TixianjiluItem implements Serializable { private Integer orderStatus; private String dateTimeString; private String orderDetail; private Integer tixianPoints; public String getDateTimeString() { return dateTimeString; } public void setDateTimeString(String dateTimeString) { this.dateTimeString = dateTimeString; } public String getOrderDetail() { return orderDetail; } public void setOrderDetail(String orderDetail) { this.orderDetail = orderDetail; } public Integer getOrderStatus() { return orderStatus; } public void setOrderStatus(Integer orderStatus) { this.orderStatus = orderStatus; } public Integer getTixianPoints() { return tixianPoints; } public void setTixianPoints(Integer tixianPoints) { this.tixianPoints = tixianPoints; } }
import java.util.*; class ques1d2 { public static void main(String main[]) { Scanner s=new Scanner(System.in); System.out.println("Enter no. to be checked"); String str=s.next(); int n=Integer.valueOf(str); int l=str.length(),sum=0; for(int i=0;i<l;i++) { String h=""+str.charAt(i); sum=sum+(int)Math.pow(Integer.valueOf(h),i+1); } if(n==sum) System.out.println(n+" is a disarium number"); else System.out.println(n+" is not a disarium number"); } }
/* * Classe amb la informaciรณ del Bicing * extreta de la pล•gina web https://api.bsmsa.eu/ext/api/bsm/gbfs/v2/en/station_status */ package at.project.stations; import java.util.List; public class Data { private long last_updated; private int ttl; private Stations data; public Data() { super(); } public Data(long last_updated, int ttl, Stations data) { super(); this.last_updated = last_updated; this.ttl = ttl; this.data = data; } public long getLast_updated() { return last_updated; } public void setLast_updated(long last_updated) { this.last_updated = last_updated; } public int getTtl() { return ttl; } public void setTtl(int ttl) { this.ttl = ttl; } public Stations getData() { return data; } public void setData(Stations data) { this.data = data; } /* * Mฤtode toString modificat per mostrar en un format mรฉs * llegible la informaciรณ de totes les estacions al lloc web */ @Override public String toString() { String bicingInfo = "&thinsp;Stations Info:<br>"; for (int i = 0; i < data.getStations().size(); i++) { if (i%2 == 0) bicingInfo = bicingInfo + "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;" + data.getStations().get(i).essentialInfo(); else bicingInfo = bicingInfo + "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;" + data.getStations().get(i).essentialInfo() + "<br>"; } return bicingInfo; } /* * Mฤtode per comprovar si una o mรฉs dels IDs * introduits per l'usuari no existeixen en les * dades recollides del Bicing */ public String stationsExist(List<Integer> stations) { String missingStations = ""; int size = 0; for(Integer id: stations) { size++; boolean exists = false; for(int i = 0; i <= id; i++) { // recorrem de la posiciรณ 0 a la posiciรณ id ja que les estacions estan ordenades if (this.data.getStations().get(i).getStation_id() == id) exists = true; } if (!exists) { missingStations += id.toString(); if (size < stations.size()) // no afegim coma desprรฉs de l'รบltima estaciรณ que falta missingStations += ", "; } } return missingStations; } }
package org.hadoop.praveen; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class CustomInputFormat { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Path inputPath = new Path("hdfs://localhost:9000/user/jivesh/xml.txt"); Path outputDir = new Path("hdfs://localhost:9000/user/jivesh/output/"); Configuration conf = new Configuration(); Job job = new Job(conf, "XML Reader"); job.setInputFormatClass(XMLInputFormat.class); //set your own input format class // name of driver class job.setJarByClass(CustomInputFormat.class); // name of mapper class job.setMapperClass(XMLMapper.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, inputPath); FileOutputFormat.setOutputPath(job, outputDir); outputDir.getFileSystem(job.getConfiguration()).delete(outputDir,true); job.waitForCompletion(true); } }
package com.c4wrd.loadtester.util; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; public class Output { private static LogLevel currentLogLevel = LogLevel.DEFAULT; private static OutputStream outStream; private static OutputStreamWriter writer; public static void write(int level, boolean flush, String formattedString, Object... args) { try { if ( level <= currentLogLevel.toInteger() ) { writer.write(String.format(formattedString, args)); if ( flush ) writer.flush(); } } catch (IOException e) { e.printStackTrace(); } } public static void write(int level, String formattedString, Object... args) { write(level, false, formattedString, args); } public static void print(int level, String formattedString, Object... args) { write(level, true, formattedString, args); } public static void println(int level, String formattedString, Object... args) { print(level, formattedString + "\n", args); } public static void print(LogLevel level, String formattedString, Object... args) { print(level.toInteger(), formattedString, args); } public static void println(LogLevel level, String formattedString, Object... args) { print(level.toInteger(), formattedString + "\n", args); } public static void flush() { try { writer.flush(); } catch (IOException ignored) { // todo? } } public static void setCurrentLogLevel(LogLevel level) { currentLogLevel = level; } public static void setOutputStream(OutputStream stream) { outStream = stream; writer = new OutputStreamWriter(outStream); } public static void println() { write(0, true, "\n"); } public static LogLevel getCurrentLogLevel() { return currentLogLevel; } }
package com.esum.router.monitor.notify; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.common.util.DateUtil; import com.esum.framework.core.management.mbean.notify.NotifyCreator; import com.esum.router.monitor.MonitorCode; import com.esum.router.monitor.MonitorConfig; /** * ๊ฐ์ง€๋œ ์žฅ์•  ์ •๋ณด๋ฅผ Main๋…ธ๋“œ์—๊ฒŒ ์ „์†กํ•œ๋‹ค. */ public class Notifier { private static Logger logger = LoggerFactory.getLogger(Notifier.class); private static String traceId = "[XMON] "; public static void sendNotify(String nodeId, String errorType, String errorContents) throws Exception { Map<String, String> message = new HashMap<String, String>(); message.put("logTime", DateUtil.getCYMDHMSS()); message.put("errorPattern", MonitorCode.ERROR_CATEGORY); message.put("errorType", errorType); message.put("errorCode", MonitorCode.ERROR_MONITOR_COMP); message.put("errorContents", errorContents); message.put("errorLocation", "notify()"); message.put("errorModuleId", MonitorConfig.MODULE_ID); message.put("nodeId", nodeId); message.put("sentFlag", "N"); logger.info(traceId+"Creating Notify message."); try { new NotifyCreator().insertNotify(message); logger.info(traceId+"Notify Message inserted."); } catch (Exception e) { logger.error(traceId+"["+nodeId+"] Notification failed by "+e.getMessage(), e); } } }
package com.innovativetech.socialmedia; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction; import com.fxn.OnBubbleClickListener; import com.innovativetech.socialmedia.Fragments.Home; import com.innovativetech.socialmedia.Fragments.Notify; import com.innovativetech.socialmedia.Fragments.Post; import com.innovativetech.socialmedia.Fragments.Profile; import com.innovativetech.socialmedia.Fragments.Search; import com.innovativetech.socialmedia.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_layout, new Home()); transaction.commit(); binding.bottomBar.addBubbleListener(new OnBubbleClickListener() { @Override public void onBubbleClick(int i) { switch (i) { case R.id.home2: FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_layout, new Home()); transaction.commit(); break; case R.id.search2: FragmentTransaction search = getSupportFragmentManager().beginTransaction(); search.replace(R.id.frame_layout, new Search()); search.commit(); break; case R.id.post2: FragmentTransaction post = getSupportFragmentManager().beginTransaction(); post.replace(R.id.frame_layout, new Post()); post.commit(); break; case R.id.notify: FragmentTransaction notify = getSupportFragmentManager().beginTransaction(); notify.replace(R.id.frame_layout, new Notify()); notify.commit(); break; case R.id.profile2: FragmentTransaction profile = getSupportFragmentManager().beginTransaction(); profile.replace(R.id.frame_layout, new Profile()); profile.commit(); break; } } }); } }
package com.newbig.im.common.serializer; import com.newbig.im.common.utils.StringUtil; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; import java.beans.PropertyEditorSupport; import java.util.Date; /** * ่ฟ™ไธชๆ˜ฏ็”จไบŽGETไธญๆ—ฅๆœŸ็š„่งฃๆž */ @Slf4j public class AppDateEditor extends PropertyEditorSupport { private final boolean allowEmpty; private final int exactDateLength; public AppDateEditor(boolean allowEmpty) { this.allowEmpty = allowEmpty; this.exactDateLength = -1; } @Override public void setAsText(String text) { if (this.allowEmpty && !org.springframework.util.StringUtils.hasText(text)) { this.setValue((Object) null); } else { if (text != null && this.exactDateLength >= 0) { throw new IllegalArgumentException("Could not parse date: it is not exactly" + this.exactDateLength + "characters long"); } this.setValue(this.convert(text)); } } // public String getAsText() { // Date value = (Date) this.getValue(); // DateFormat dateFormat = new SimpleDateFormat(format); // return value != null ? this.dateFormat.format(value) : ""; // } public Date convert(String source) { String value = source.trim(); if (StringUtil.isBlank(value)) { return null; } return parseDate(source); } /** * ๅŠŸ่ƒฝๆ่ฟฐ๏ผšๆ ผๅผๅŒ–ๆ—ฅๆœŸ * * @param dateStr String ๅญ—็ฌฆๅž‹ๆ—ฅๆœŸ * @return Date ๆ—ฅๆœŸ */ public Date parseDate(String dateStr) { return new DateTime(dateStr.replace(" ","T")).toDate(); } }
package io.dcbn.backend.graph; import eu.amidst.core.distribution.Multinomial; import eu.amidst.core.distribution.Multinomial_MultinomialParents; import eu.amidst.core.variables.Assignment; import eu.amidst.core.variables.HashMapAssignment; import eu.amidst.core.variables.Variable; import eu.amidst.dynamic.models.DynamicBayesianNetwork; import eu.amidst.dynamic.models.DynamicDAG; import eu.amidst.dynamic.variables.DynamicVariables; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; /** * This class is testing the AmidstGraphAdapter. */ public class GraphAdapterTests { private Node a; private Node b; private Node c; private Graph testGraph; private DynamicBayesianNetwork generatedDBN; private DynamicBayesianNetwork correctDBN; private final Position ZERO_POSITION = new Position(0.0, 0.0); /** * Creating the graph object and the DynamicBayesianNetwork object */ @BeforeEach public void setUp() { NodeDependency nodeATimeZeroDependency = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.3, 0.7}}); NodeDependency nodeATimeTDependency = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.3, 0.7}}); a = new Node("A", nodeATimeZeroDependency, nodeATimeTDependency, null, null, StateType.BOOLEAN, ZERO_POSITION); NodeDependency nodeBTimeZeroDependency = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.2, 0.8}}); NodeDependency nodeBTimeTDependency = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.2, 0.8}}); b = new Node("B", nodeBTimeZeroDependency, nodeBTimeTDependency, null, null, StateType.BOOLEAN, ZERO_POSITION); NodeDependency nodeCTimeZeroDependency = new NodeDependency(Arrays.asList(a, b), new ArrayList<>(), new double[][]{{0.999, 0.001}, {0.6, 0.4}, {0.8, 0.2}, {0.2, 0.8}}); c = new Node("C", nodeCTimeZeroDependency, null, null, null, StateType.BOOLEAN, ZERO_POSITION); NodeDependency nodeCTimeTDependency = new NodeDependency(Arrays.asList(a, b), Collections.singletonList(c), new double[][]{{0.1, 0.9}, {0.2, 0.8}, {0.3, 0.7}, {0.4, 0.6}, {0.5, 0.5}, {0.6, 0.4}, {0.7, 0.3}, {0.8, 0.2}}); c.setTimeTDependency(nodeCTimeTDependency); List<Node> nodeList = new ArrayList<>(); nodeList.add(a); nodeList.add(b); nodeList.add(c); testGraph = new Graph(0, "testGraph", 5, nodeList); AmidstGraphAdapter amidstGraphAdapter = new AmidstGraphAdapter(testGraph); generatedDBN = amidstGraphAdapter.getDbn(); //----------------generating correct DBN-------------------- DynamicVariables dynamicVariables = new DynamicVariables(); Variable a = dynamicVariables.newMultinomialDynamicVariable("A", 2); Variable b = dynamicVariables.newMultinomialDynamicVariable("B", 2); Variable c = dynamicVariables.newMultinomialDynamicVariable("C", 2); Variable c_interface = c.getInterfaceVariable(); DynamicDAG dynamicDAG = new DynamicDAG(dynamicVariables); dynamicDAG.getParentSetTime0(c).addParent(b); dynamicDAG.getParentSetTime0(c).addParent(a); dynamicDAG.getParentSetTimeT(c).addParent(c_interface); dynamicDAG.getParentSetTimeT(c).addParent(b); dynamicDAG.getParentSetTimeT(c).addParent(a); DynamicBayesianNetwork dbn = new DynamicBayesianNetwork(dynamicDAG); //SET PROBABILITIES AT TIME 0 Multinomial multinomialA = dbn.getConditionalDistributionTime0(a); Multinomial multinomialB = dbn.getConditionalDistributionTime0(b); Multinomial multinomialAT = dbn.getConditionalDistributionTimeT(a); Multinomial multinomialBT = dbn.getConditionalDistributionTimeT(b); Multinomial_MultinomialParents multinomial_multinomialParentsC0 = dbn.getConditionalDistributionTime0(c); Multinomial_MultinomialParents multinomial_multinomialParentsCT = dbn.getConditionalDistributionTimeT(c); // TIME 0 multinomialA.setProbabilities(new double[]{0.3, 0.7}); multinomialB.setProbabilities(new double[]{0.2, 0.8}); multinomialAT.setProbabilities(new double[]{0.3, 0.7}); multinomialBT.setProbabilities(new double[]{0.2, 0.8}); multinomial_multinomialParentsC0.getMultinomial(0).setProbabilities(new double[]{0.999, 0.001}); multinomial_multinomialParentsC0.getMultinomial(1).setProbabilities(new double[]{0.6, 0.4}); multinomial_multinomialParentsC0.getMultinomial(2).setProbabilities(new double[]{0.8, 0.2}); multinomial_multinomialParentsC0.getMultinomial(3).setProbabilities(new double[]{0.2, 0.8}); // TIME T Assignment assignment = new HashMapAssignment(3); assignment.setValue(a, 1); multinomial_multinomialParentsCT.getMultinomial(assignment); multinomial_multinomialParentsCT.getMultinomial(0).setProbabilities(new double[]{0.1, 0.9}); multinomial_multinomialParentsCT.getMultinomial(1).setProbabilities(new double[]{0.2, 0.8}); multinomial_multinomialParentsCT.getMultinomial(2).setProbabilities(new double[]{0.3, 0.7}); multinomial_multinomialParentsCT.getMultinomial(3).setProbabilities(new double[]{0.4, 0.6}); multinomial_multinomialParentsCT.getMultinomial(4).setProbabilities(new double[]{0.5, 0.5}); multinomial_multinomialParentsCT.getMultinomial(5).setProbabilities(new double[]{0.6, 0.4}); multinomial_multinomialParentsCT.getMultinomial(6).setProbabilities(new double[]{0.7, 0.3}); multinomial_multinomialParentsCT.getMultinomial(7).setProbabilities(new double[]{0.8, 0.2}); correctDBN = dbn; } /** * Comparing the structure and data of both DynamicBayesianNetwork */ @Test public void testDBNAdapter() { assertEquals(correctDBN.toString(), generatedDBN.toString()); } @Test public void testVirtualEvidences() { b = new ValueNode(b, new double[][]{{0.8, 0.2}}); List<Node> nodeList = new ArrayList<>(); nodeList.add(a); nodeList.add(b); nodeList.add(c); testGraph = new Graph(0, "testGraph", 5, nodeList); AmidstGraphAdapter amidstGraphAdapter = new AmidstGraphAdapter(testGraph); generatedDBN = amidstGraphAdapter.getDbn(); //----------------generating correct DBN-------------------- DynamicVariables dynamicVariables = new DynamicVariables(); Variable a = dynamicVariables.newMultinomialDynamicVariable("A", 2); Variable b = dynamicVariables.newMultinomialDynamicVariable("B", 2); Variable tempChildB = dynamicVariables.newMultinomialDynamicVariable("tempChildB", 2); Variable c = dynamicVariables.newMultinomialDynamicVariable("C", 2); Variable c_interface = c.getInterfaceVariable(); DynamicDAG dynamicDAG = new DynamicDAG(dynamicVariables); dynamicDAG.getParentSetTime0(c).addParent(b); dynamicDAG.getParentSetTime0(c).addParent(a); dynamicDAG.getParentSetTime0(tempChildB).addParent(b); dynamicDAG.getParentSetTimeT(c).addParent(c_interface); dynamicDAG.getParentSetTimeT(c).addParent(b); dynamicDAG.getParentSetTimeT(c).addParent(a); dynamicDAG.getParentSetTimeT(tempChildB).addParent(b); DynamicBayesianNetwork dbn = new DynamicBayesianNetwork(dynamicDAG); //SET PROBABILITIES AT TIME 0 Multinomial multinomialA = dbn.getConditionalDistributionTime0(a); Multinomial multinomialB = dbn.getConditionalDistributionTime0(b); Multinomial multinomialAT = dbn.getConditionalDistributionTimeT(a); Multinomial multinomialBT = dbn.getConditionalDistributionTimeT(b); Multinomial_MultinomialParents multinomial_multinomialParentsC0 = dbn.getConditionalDistributionTime0(c); Multinomial_MultinomialParents multinomial_multinomialParentsCT = dbn.getConditionalDistributionTimeT(c); Multinomial_MultinomialParents multinomial_multinomialParentsTemp0 = dbn.getConditionalDistributionTime0(tempChildB); Multinomial_MultinomialParents multinomial_multinomialParentsTempT = dbn.getConditionalDistributionTimeT(tempChildB); // TIME 0 multinomialA.setProbabilities(new double[]{0.3, 0.7}); multinomialB.setProbabilities(new double[]{0.2, 0.8}); multinomialAT.setProbabilities(new double[]{0.3, 0.7}); multinomialBT.setProbabilities(new double[]{0.2, 0.8}); multinomial_multinomialParentsC0.getMultinomial(0).setProbabilities(new double[]{0.999, 0.001}); multinomial_multinomialParentsC0.getMultinomial(1).setProbabilities(new double[]{0.6, 0.4}); multinomial_multinomialParentsC0.getMultinomial(2).setProbabilities(new double[]{0.8, 0.2}); multinomial_multinomialParentsC0.getMultinomial(3).setProbabilities(new double[]{0.2, 0.8}); multinomial_multinomialParentsTemp0.getMultinomial(0).setProbabilities(new double[]{0.8, 0.2}); multinomial_multinomialParentsTemp0.getMultinomial(1).setProbabilities(new double[]{0.2, 0.8}); // TIME T Assignment assignment = new HashMapAssignment(3); assignment.setValue(a, 1); multinomial_multinomialParentsCT.getMultinomial(assignment); multinomial_multinomialParentsCT.getMultinomial(0).setProbabilities(new double[]{0.1, 0.9}); multinomial_multinomialParentsCT.getMultinomial(1).setProbabilities(new double[]{0.2, 0.8}); multinomial_multinomialParentsCT.getMultinomial(2).setProbabilities(new double[]{0.3, 0.7}); multinomial_multinomialParentsCT.getMultinomial(3).setProbabilities(new double[]{0.4, 0.6}); multinomial_multinomialParentsCT.getMultinomial(4).setProbabilities(new double[]{0.5, 0.5}); multinomial_multinomialParentsCT.getMultinomial(5).setProbabilities(new double[]{0.6, 0.4}); multinomial_multinomialParentsCT.getMultinomial(6).setProbabilities(new double[]{0.7, 0.3}); multinomial_multinomialParentsCT.getMultinomial(7).setProbabilities(new double[]{0.8, 0.2}); multinomial_multinomialParentsTempT.getMultinomial(0).setProbabilities(new double[]{0.8, 0.2}); multinomial_multinomialParentsTempT.getMultinomial(1).setProbabilities(new double[]{0.2, 0.8}); correctDBN = dbn; assertEquals(correctDBN.toString(), generatedDBN.toString()); } }
package com.example.administrator.cookman.model.entity.CookEntity; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * Created by Administrator on 2017/2/19. */ public class CookDetail implements Parcelable { private ArrayList<String> ctgIds;//ๅˆ†็ฑปID private String ctgTitles; private String menuId; private String name; private CookRecipe recipe; private String thumbnail; public CookDetail(){ } public ArrayList<String> getCtgIds() { return ctgIds; } public void setCtgIds(ArrayList<String> ctgIds) { this.ctgIds = ctgIds; } public String getCtgTitles() { return ctgTitles; } public void setCtgTitles(String ctgTitles) { this.ctgTitles = ctgTitles; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMenuId() { return menuId; } public void setMenuId(String menuId) { this.menuId = menuId; } public CookRecipe getRecipe() { return recipe; } public void setRecipe(CookRecipe recipe) { this.recipe = recipe; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringList(this.ctgIds); dest.writeString(this.ctgTitles); dest.writeString(this.menuId); dest.writeString(this.name); dest.writeParcelable(this.recipe, flags); dest.writeString(this.thumbnail); } protected CookDetail(Parcel in) { this.ctgIds = in.createStringArrayList(); this.ctgTitles = in.readString(); this.menuId = in.readString(); this.name = in.readString(); this.recipe = in.readParcelable(CookRecipe.class.getClassLoader()); this.thumbnail = in.readString(); } public static final Parcelable.Creator<CookDetail> CREATOR = new Parcelable.Creator<CookDetail>() { @Override public CookDetail createFromParcel(Parcel source) { return new CookDetail(source); } @Override public CookDetail[] newArray(int size) { return new CookDetail[size]; } }; }
package com.example.biblioteca.Adapters; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.biblioteca.R; import java.io.IOException; import java.net.URL; import java.util.ArrayList; public class nubeAdapter extends BaseAdapter { private final Activity context; private final ArrayList<String> imagenes; private final ArrayList<String> texto; /** * * @param context * @param imagenes * @param texto */ public nubeAdapter(Activity context, ArrayList<String> imagenes, ArrayList<String> texto) { this.context = context; this.imagenes = imagenes; this.texto = texto; } @Override public int getCount() { return imagenes.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return i; } public View getView(int position, View view, ViewGroup viewGroup) { view = context.getLayoutInflater().inflate(R.layout.custom_grid_view_nube, null); ImageView imageView = (ImageView) view.findViewById(R.id.imageView); TextView textView = (TextView) view.findViewById(R.id.textView); try { URL url = new URL(imagenes.get(position)); RequestOptions options = new RequestOptions() .centerCrop() .placeholder(R.drawable.ic_download) .error(R.drawable.ic_download_error); Glide.with(context).load(url).apply(options).override(imageView.getWidth(),imageView.getHeight()).into(imageView); textView.setText(texto.get(position)); } catch(IOException e) { System.out.println(e); } return view; } }
package structural.facade; public class SubA { public void doA1(){ System.out.println("SubA:doA1"); } public void doA2(){ System.out.println("SubA:doA2"); } }
package com.cdkj.fastdfs.service.impl; import com.cdkj.fastdfs.model.pojo.FastDfsFile; import com.cdkj.fastdfs.FileManager; import org.apache.commons.codec.binary.Base64; import java.io.*; /** * Created by Administrator on 2016-05-13. */ public class FastDfsServiceImpl { /** * @param fileUrl ๆ–‡ไปถ็ปๅฏน่ทฏๅพ„ * @param fileName ๆ–‡ไปถๅ็งฐ * @param fileExt ๆ–‡ไปถๅŽ็ผ€ * @return ๆœๅŠกๅ™จๆ–‡ไปถ่ทฏๅพ„ * @throws Exception */ public static String upFile(String fileUrl, String fileName, String fileExt) throws Exception { FileInputStream fis = new FileInputStream(fileUrl); byte[] file_buff = null; if (fis != null) { int len = fis.available(); file_buff = new byte[len]; fis.read(file_buff); } FastDfsFile file = new FastDfsFile(fileName, file_buff, fileExt); String fileAbsolutePath = FileManager.upload(file); fis.close(); return fileAbsolutePath; } /** * @param in InputStream * @param fileName ๆ–‡ไปถๅ็งฐ * @param fileExt ๆ–‡ไปถๅŽ็ผ€ * @return ๆœๅŠกๅ™จๆ–‡ไปถ่ทฏๅพ„ * @throws Exception */ public static String upFile(InputStream in, String fileName, String fileExt) throws Exception { byte[] file_buff = input2byte(in); FastDfsFile file = new FastDfsFile(fileName, file_buff, fileExt); String fileAbsolutePath = FileManager.upload(file); return fileAbsolutePath; } /** * @param in InputStream * @param fileName ๆ–‡ไปถๅ็งฐ * @param fileExt ๆ–‡ไปถๅŽ็ผ€ * @return ๆœๅŠกๅ™จๆ–‡ไปถ่ทฏๅพ„ * @throws Exception */ public static String upFile(InputStream in, String fileName, String fileExt, String groupName) throws Exception { byte[] file_buff = input2byte(in); FastDfsFile file = new FastDfsFile(fileName, file_buff, fileExt); String fileAbsolutePath = FileManager.upload(file, groupName); return fileAbsolutePath; } /** * @param fileName ๆ–‡ไปถๅ็งฐ * @param fileExt ๆ–‡ไปถๅŽ็ผ€ * @return ๆœๅŠกๅ™จๆ–‡ไปถ่ทฏๅพ„ * @throws Exception */ public static String upFileByByteArray(String byteArrayStr, String fileName, String fileExt) throws Exception { byte[] file_buff = Base64.decodeBase64(byteArrayStr); FastDfsFile file = new FastDfsFile(fileName, file_buff, fileExt); String fileAbsolutePath = FileManager.upload(file); return fileAbsolutePath; } /** * InputStream ่ฝฌ byte[] * * @param buf * @return */ public static final InputStream byte2Input(byte[] buf) { return new ByteArrayInputStream(buf); } /** * byte[] ่ฝฌ InputStream * * @param inStream * @return * @throws IOException */ public static final byte[] input2byte(InputStream inStream) throws IOException { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = inStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } byte[] in2b = swapStream.toByteArray(); swapStream.close(); return in2b; } public static int deleteFile(String url) { // String a = "http://114.55.42.56:8080/group1/M00/0A/1C/cjcqOFc-s6eAXWIcAAEOFgxyE2Q442.jpg"; int i = -1001; url = url == null ? "" : url; if (url.startsWith("http")) { //http://114.55.42.56:8080 String temp = url.substring(0, url.lastIndexOf(":") + 5); //group1/M00/0A/1C/cjcqOFc-s6eAXWIcAAEOFgxyE2Q442.jpg String tempb = url.substring(url.lastIndexOf(":") + 6, url.length()); //group1 String group = tempb.substring(0, tempb.indexOf("/")); //M00/0A/1C/cjcqOFc-s6eAXWIcAAEOFgxyE2Q442.jpg String filePath = tempb.substring(tempb.indexOf("/") + 1, tempb.length()); try { i = FileManager.deleteFile(group, filePath); } catch (Exception e) { e.printStackTrace(); i = -1; } } return i; } }
import java.io.*; import java.util.*; class reversevowel { public static void main(String[] args) { Scanner kb= new Scanner(System.in); int n=kb.nextInt(); if(n>0&&n<100001) { String str=kb.next(); for(int i=n-1;i>=0;i--) { char ch=str.charAt(i); if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'|| ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') { } else { System.out.print(ch); } } System.out.println(); } } }
package com.coordinatorpattern; import android.content.Context; public interface CoordinatorDelegate { void start(Context ctx); }
package org.exist.xquery.modules.mpeg7.transformation; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.ErrorListener; import javax.xml.transform.Source; import javax.xml.transform.SourceLocator; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.FileUtils; import org.exist.xquery.modules.mpeg7.validation.Validator; import org.apache.log4j.Logger; import org.exist.xquery.modules.mpeg7.storage.helpers.X3DResourceDetail; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; /** * * @author Patti Spala <pd.spala@gmail.com> */ public class MP7Generator { private static final Logger logger = Logger.getLogger(MP7Generator.class); protected X3DResourceDetail x3dResource; protected String outputPath; protected HashMap<String, String> extrusionParamMap, ifsParamMap, ilsParamMap, histograms, scalableColors, surfeatures; protected Transformer transformer; protected TransformerFactory factory; protected Source xslStream; public MP7Generator(X3DResourceDetail x3dResource, String outputPath, HashMap<String, String> ilsParamMap, HashMap<String, String> ifsParamMap, HashMap<String, String> extrusionParamMap, HashMap<String, String> histograms, HashMap<String, String> scalableColors, HashMap<String, String> surfeatures, String xslSource) throws IOException { this.x3dResource = x3dResource; this.extrusionParamMap = extrusionParamMap; this.ifsParamMap = ifsParamMap; this.ilsParamMap = ilsParamMap; this.histograms = histograms; this.scalableColors = scalableColors; this.surfeatures = surfeatures; this.factory = TransformerFactory.newInstance(); this.xslStream = new StreamSource(MP7Generator.class.getResourceAsStream("/org/exist/xquery/modules/mpeg7/transformation/xsl/" + xslSource)); this.outputPath = outputPath; //this.xslStream = new StreamSource(new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(xslSource)))); } public X3DResourceDetail getX3dResource() { return x3dResource; } public void setX3dResource(X3DResourceDetail x3dResource) { this.x3dResource = x3dResource; } public TransformerFactory getFactory() { return factory; } public Transformer getTransformer() { return transformer; } public void setFactory(TransformerFactory factory) { this.factory = factory; } public void setTransformer(Transformer transformer) { this.transformer = transformer; } public Source getXslStream() { return xslStream; } public void setXslStream(Source xslStream) { this.xslStream = xslStream; } public HashMap<String, String> getHistograms() { return histograms; } public void setHistograms(HashMap<String, String> histograms) { this.histograms = histograms; } public void setScalableColors(HashMap<String, String> scalableColors) { this.scalableColors = scalableColors; } public void generateDescription() { try { //Get X3D source File x3dSource = new File(x3dResource.parentPath + x3dResource.resourceFileName); StreamSource x3dInput = new StreamSource(new ByteArrayInputStream(FileUtils.readFileToByteArray(x3dSource))); //Where to write MPEG-7 file File mp7File; if (this.outputPath.length() > 0){ mp7File = new File(this.outputPath + x3dResource.resourceName + ".mp7"); } else{ mp7File = new File(x3dResource.resourceName + ".mp7"); } //Setup transformer options this.transformer = this.factory.newTransformer(this.xslStream); this.transformer.setErrorListener(new TransformationErrorListener()); setTranformerParameters(); StreamResult sr = new StreamResult(mp7File); this.transformer.transform(x3dInput, sr); Validator mpeg7Validator = new Validator(mp7File); Boolean isValid = mpeg7Validator.isValid(); // if (isValid) { //System.out.println("File: " + mp7Output + "is valid: "+ isValid); //} } catch (TransformerException ex) { System.out.println("TransformerException: " + ex); } catch (IllegalArgumentException ex) { System.out.println("IllegalArgumentException: " + ex); } catch (IOException ex) { System.out.println("IOException: " + ex); } } private void setTranformerParameters() { this.transformer.setParameter("filename", this.x3dResource.parentPath + "/" + this.x3dResource.resourceFileName); if (!this.extrusionParamMap.isEmpty()) { for (Map.Entry me : this.extrusionParamMap.entrySet()) { this.transformer.setParameter(me.getKey().toString(), me.getValue().toString()); } } if (!this.ifsParamMap.isEmpty()) { for (Map.Entry me : this.ifsParamMap.entrySet()) { this.transformer.setParameter(me.getKey().toString(), me.getValue().toString()); } } if (!this.ilsParamMap.isEmpty()) { for (Map.Entry me : this.ilsParamMap.entrySet()) { this.transformer.setParameter(me.getKey().toString(), me.getValue().toString()); } } if (!this.histograms.isEmpty()) { for (Map.Entry entry : this.histograms.entrySet()) { this.transformer.setParameter(entry.getKey().toString(), entry.getValue().toString()); } } if (!this.scalableColors.isEmpty()) { for (Map.Entry entry : this.scalableColors.entrySet()) { this.transformer.setParameter(entry.getKey().toString(), entry.getValue().toString()); } } if (!this.surfeatures.isEmpty()) { for (Map.Entry entry : this.surfeatures.entrySet()) { this.transformer.setParameter(entry.getKey().toString(), entry.getValue().toString()); } } } } class TransformationErrorListener implements ErrorListener { // private static final Logger logger = Logger.getLogger(TransformationErrorListener.class); @Override public void warning(TransformerException e) throws TransformerException { System.out.println("TransformerException: "+ e); report(e); } @Override public void error(TransformerException e) throws TransformerException { System.out.println("TransformerException: "+ e); report(e); } @Override public void fatalError(TransformerException e) throws TransformerException { System.out.println("TransformerException: "+ e); report(e); } private void report(TransformerException e) { try { SourceLocator loc = e.getLocator(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); String docSource = "transformErrors.xml"; File f = new File(docSource); Document doc; Element root; if (f.exists()) { doc = builder.parse(f); root = doc.getDocumentElement(); } else { doc = builder.newDocument(); // root element root = doc.createElement("errors"); doc.appendChild(root); root.appendChild(root); } Element error = doc.createElement("error"); error.setAttribute("line", (loc != null) ? String.valueOf(loc.getLineNumber()) : "N/A"); error.setAttribute("column", (loc != null) ? String.valueOf(loc.getColumnNumber()) : "N/A"); error.setAttribute("publicId", (loc != null) ? loc.getPublicId() : "N/A"); error.setAttribute("systemId", (loc != null) ? loc.getSystemId() : "N/A"); Element message = doc.createElement("message"); message.appendChild(doc.createTextNode(e.getMessageAndLocation())); error.appendChild(message); Element location = doc.createElement("location"); location.appendChild(doc.createTextNode(e.getLocationAsString())); error.appendChild(location); Element exception = doc.createElement("exception"); exception.appendChild(doc.createTextNode(e.getException().getMessage())); error.appendChild(exception); Element cause = doc.createElement("cause"); cause.appendChild(doc.createTextNode(e.getCause().getMessage())); error.appendChild(cause); root.appendChild(error); // create the xml file //transform the DOM Object to an XML File TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(doc); StreamResult streamResult = new StreamResult(f); transformer.transform(domSource, streamResult); } catch (ParserConfigurationException ex) { System.out.println("ParserConfigurationException: "+ ex); } catch (SAXException ex) { System.out.println("SAXException: "+ ex); } catch (IOException ex) { System.out.println("IOException: "+ ex); } catch (TransformerConfigurationException ex) { System.out.println("TransformerConfigurationException: "+ ex); } catch (TransformerException ex) { System.out.println("TransformerException: "+ ex); } } }
package org.elasticsearch.plugin.zentity; import com.fasterxml.jackson.databind.JsonNode; import io.zentity.common.Json; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.rest.RestStatus; import org.junit.Test; import static io.zentity.devtools.JsonTestUtil.assertUnorderedEquals; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.fail; public class ModelsActionIT extends AbstractActionITCase { @Test public void testGetUnknownModel() throws Exception { Response response = client.performRequest(new Request("GET", "_zentity/models/unknown")); assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode()); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); assertTrue("_id field present", json.has("_id")); assertEquals("unknown", json.get("_id").textValue()); assertTrue("_type field present", json.has("_type")); assertEquals("doc", json.get("_type").textValue()); assertTrue("found field present", json.has("found")); assertFalse(json.get("found").booleanValue()); } @Test public void testListModels() throws Exception { prepareTestEntityModelA(); prepareTestEntityModelB(); try { Response response = client.performRequest(new Request("GET", "_zentity/models")); assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode()); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); assertTrue("took field present", json.has("took")); assertTrue("_shards field present", json.has("_shards")); assertTrue("timed_out field present", json.has("timed_out")); assertFalse("timed_out is false", json.get("timed_out").booleanValue()); assertTrue("hits field present", json.has("hits")); JsonNode hitsWrapper = json.get("hits"); assertTrue("hits.hits field present", hitsWrapper.has("hits")); JsonNode hits = hitsWrapper.get("hits"); assertTrue(hits.isArray()); assertEquals(2, hits.size()); } finally { destroyTestEntityModelA(); destroyTestEntityModelB(); } } @Test public void testGetKnownModel() throws Exception { JsonNode expectedModel = Json.ORDERED_MAPPER.readTree(getTestEntityModelAJson()); int testResourceSet = TEST_RESOURCES_A; prepareTestResources(testResourceSet); try { Response response = client.performRequest(new Request("GET", "_zentity/models/zentity_test_entity_a")); assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode()); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); assertTrue("_id field present", json.has("_id")); assertEquals("zentity_test_entity_a", json.get("_id").textValue()); assertTrue("_type field present", json.has("_type")); assertEquals("doc", json.get("_type").textValue()); assertTrue("found field present", json.has("found")); assertTrue(json.get("found").booleanValue()); assertTrue("_source field present", json.has("_source")); assertUnorderedEquals(expectedModel, json.get("_source")); } finally { destroyTestResources(testResourceSet); } } @Test public void testDeleteUnknown() throws Exception { Response response = client.performRequest(new Request("DELETE", "_zentity/models/zentity_test_entity_a")); assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode()); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); assertTrue("_id field present", json.has("_id")); assertEquals("zentity_test_entity_a", json.get("_id").textValue()); assertTrue("_type field present", json.has("_type")); assertEquals("doc", json.get("_type").textValue()); assertTrue("result field present", json.has("result")); assertEquals("not_found", json.get("result").textValue()); } @Test public void testDeleteModel() throws Exception { int testResourceSet = TEST_RESOURCES_A; prepareTestResources(testResourceSet); try { Response response = client.performRequest(new Request("DELETE", "_zentity/models/zentity_test_entity_a")); assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode()); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); assertTrue("_id field present", json.has("_id")); assertEquals("zentity_test_entity_a", json.get("_id").textValue()); assertTrue("_type field present", json.has("_type")); assertEquals("doc", json.get("_type").textValue()); assertTrue("result field present", json.has("result")); assertEquals("deleted", json.get("result").textValue()); } finally { destroyTestResources(testResourceSet); } } @Test public void testCannotCreateInvalidEntityType() throws Exception { ByteArrayEntity testEntityModelA = new ByteArrayEntity(getTestEntityModelAJson(), ContentType.APPLICATION_JSON); Request request = new Request("POST", "_zentity/models/_anInvalidType"); request.setEntity(testEntityModelA); try { client.performRequest(request); fail("expected failure"); } catch (ResponseException ex) { Response response = ex.getResponse(); assertEquals(400, response.getStatusLine().getStatusCode()); JsonNode json = Json.MAPPER.readTree(response.getEntity().getContent()); assertEquals(400, json.get("status").asInt()); assertTrue("response has error field", json.has("error")); JsonNode errorJson = json.get("error"); assertTrue("error has type field", errorJson.has("type")); assertEquals("validation_exception", errorJson.get("type").textValue()); assertTrue("error has reason field", errorJson.has("reason")); assertTrue(errorJson.get("reason").textValue().contains("Invalid entity type [_anInvalidType]")); } } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ package org.webtop.x3d.widget; import org.sdl.gui.numberbox.*; import org.webtop.x3d.widget.PlanarWidget; import org.sdl.math.Function; /** * <p>Title: X3DWebTOP</p> * * <p>Description: The X3D version of The Optics Project for the Web * (WebTOP)</p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: MSU Department of Physics and Astronomy</p> * * @author Paul Cleveland, Peter Gilbert * @version 0.0 */ public class PlanarCoupler extends Coupler implements NumberBox.Listener, PlanarWidget.Listener { public static class Converter { public Function.TwoD toWidget,toFB; public Converter(Function.TwoD towidget, Function.TwoD tofb) { toWidget = towidget; toFB = tofb; } } //Random idea: would an array of (all 2) FloatBoxes work better? private final FloatBox xfield, yfield; private final PlanarWidget widget; private final Converter converter; public PlanarCoupler(PlanarWidget pw, FloatBox fbx, FloatBox fby, int digs) { this(pw, fbx, fby, digs, null); } public PlanarCoupler(PlanarWidget pw, FloatBox fbx, FloatBox fby, int digs, Converter con) { super(digs); xfield = fbx; yfield = fby; widget = pw; converter = con; fbx.addNumberListener(this); fby.addNumberListener(this); pw.addListener(this); } //These should be used instead of the FloatBoxes' corresponding methods! public void setXMax(float max_x) { xfield.setMax(max_x); widget.setMax(max_x, yfield.getMax()); } public void setYMax(float max_y) { yfield.setMax(max_y); widget.setMax(xfield.getMax(), max_y); } public void setMax(float max_x, float max_y) { xfield.setMax(max_x); yfield.setMax(max_y); widget.setMax(max_x, max_y); } public void setXMin(float min_x) { xfield.setMin(min_x); widget.setMin(min_x, yfield.getMin()); } public void setYMin(float min_y) { yfield.setMin(min_y); widget.setMin(xfield.getMin(), min_y); } public void setMin(float min_x, float min_y) { xfield.setMin(min_x); yfield.setMin(min_y); widget.setMin(min_x, min_y); } public void release() { xfield.removeNumberListener(this); yfield.removeNumberListener(this); widget.removeListener(this); } //======EVENT HANDLING CODE======\\ public void valueChanged(PlanarWidget src, float valuex, float valuey) { if (src == widget) { if (widget.isActive()) { if (converter != null) { double[] value = converter.toFB.eval(valuex, valuey); valuex = (float) value[0]; valuey = (float) value[1]; } if (isFixed()) { xfield.setFixValue(valuex, getDigits()); yfield.setFixValue(valuey, getDigits()); } else { xfield.setSigValue(valuex, getDigits()); yfield.setSigValue(valuey, getDigits()); } } } else System.err.println( "PlanarCoupler: unexpected valueChanged() from " + src); } public void numChanged(NumberBox source, Number newVal) { float x, y; if (source == xfield) { x = newVal.floatValue(); y = yfield.getValue(); } else if (source == yfield) { x = xfield.getValue(); y = newVal.floatValue(); } else { System.err.println("PlanarCoupler: unexpected numChanged() from " + source); return; } if (converter != null) { double[] value = converter.toWidget.eval(x, y); x = (float) value[0]; y = (float) value[1]; } if (!widget.isActive()) widget.setValue(x, y); } //No action needed here; just check that it's from whom it should be public void boundsForcedChange(NumberBox source, Number oldVal) { if (source != xfield && source != yfield) System.err.println( "PlanarCoupler: unexpected boundsForcedChange() from " + source); } //Similarly no action needed; just check that it's from whom it should be public void invalidEntry(NumberBox source, Number badVal) { if (source == xfield || source == yfield) { if (widget.isActive()) System.err.println( "PlanarCoupler: invalid input from widget"); } else System.err.println( "PlanarCoupler: unexpected invalidEntry() from " + source); } }
package com.kedong.immweb.controller; import com.nariit.pi6000.ua.session.HttpSessionManager; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * * * @author wankang * @date 2019/06/18 */ @Scope("prototype") @Controller @RequestMapping("/userCheckController") public class UesrCheckController { @RequestMapping("/userSearch") public void userSearch(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String app = request.getParameter("app"); System.out.println("app = " + app); System.out.println("++++++++userName++++++++:"+session.getAttribute("userName")); if (app !=null&&!"null".equals(app)&&app.length()>0&&!"".equals(app)){ if("web".equals(app)){ System.out.println("ๆญฃ่ทณ่ฝฌๅˆฐweb็ซฏๅณๆ—ถ้€š่ฎฏ..."); request.getRequestDispatcher("/login.jsp").forward(request,response); }else if("pc".equals(app)){ System.out.println("ๆญฃ่ทณ่ฝฌๅˆฐpc็ซฏๅณๆ—ถ้€š่ฎฏ..."); response.sendRedirect("KedongIM://username="+session.getAttribute("userName")); } }else{ System.out.println("้ป˜่ฎค่ทณ่ฝฌๅˆฐweb็ซฏๅณๆ—ถ้€š่ฎฏ..."); request.getRequestDispatcher("/login.jsp").forward(request,response); } } }
package com.thonline.DO; public class DPPeribadiDO extends BaseDO{ private String AGRZCD; private String AGBFTX; private String AGBGTX; private String AGBHTX; private String AGBKCD; private String AGFBCD; private String AGBCCD; private String AGBECD; private String AGBACD; private String AGBMCD; public String getAGRZCD() { return AGRZCD; } public void setAGRZCD(String aGRZCD) { AGRZCD = aGRZCD; } public String getAGBFTX() { return AGBFTX; } public void setAGBFTX(String aGBFTX) { AGBFTX = aGBFTX; } public String getAGBGTX() { return AGBGTX; } public void setAGBGTX(String aGBGTX) { AGBGTX = aGBGTX; } public String getAGBHTX() { return AGBHTX; } public void setAGBHTX(String aGBHTX) { AGBHTX = aGBHTX; } public String getAGBKCD() { return AGBKCD; } public void setAGBKCD(String aGBKCD) { AGBKCD = aGBKCD; } public String getAGFBCD() { return AGFBCD; } public void setAGFBCD(String aGFBCD) { AGFBCD = aGFBCD; } public String getAGBCCD() { return AGBCCD; } public void setAGBCCD(String aGBCCD) { AGBCCD = aGBCCD; } public String getAGBECD() { return AGBECD; } public void setAGBECD(String aGBECD) { AGBECD = aGBECD; } public String getAGBACD() { return AGBACD; } public void setAGBACD(String aGBACD) { AGBACD = aGBACD; } public String getAGBMCD() { return AGBMCD; } public void setAGBMCD(String aGBMCD) { AGBMCD = aGBMCD; } }
/* * 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 entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Gebruiker */ @Entity @Table(name = "messagecomment") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Messagecomment.findAll", query = "SELECT m FROM Messagecomment m"), @NamedQuery(name = "Messagecomment.findByMessagecommentid", query = "SELECT m FROM Messagecomment m WHERE m.messagecommentid = :messagecommentid"), @NamedQuery(name = "Messagecomment.findByCommenttype", query = "SELECT m FROM Messagecomment m WHERE m.commenttype = :commenttype"), @NamedQuery(name = "Messagecomment.findByCreatedon", query = "SELECT m FROM Messagecomment m WHERE m.createdon = :createdon"), @NamedQuery(name = "Messagecomment.findByDate", query = "SELECT m FROM Messagecomment m WHERE m.date = :date"), @NamedQuery(name = "Messagecomment.findByTags", query = "SELECT m FROM Messagecomment m WHERE m.tags = :tags"), @NamedQuery(name = "Messagecomment.findByText", query = "SELECT m FROM Messagecomment m WHERE m.text = :text")}) public class Messagecomment implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "messagecommentid") private Long messagecommentid; @Size(max = 255) @Column(name = "commenttype") private String commenttype; @Column(name = "createdon") @Temporal(TemporalType.TIMESTAMP) private Date createdon; @Column(name = "date") @Temporal(TemporalType.DATE) private Date date; @Size(max = 255) @Column(name = "tags") private String tags; @Size(max = 255) @Column(name = "text") private String text; @JoinColumn(name = "memberid", referencedColumnName = "id") @ManyToOne private Member1 memberid; @JoinColumn(name = "messageid", referencedColumnName = "messageid") @ManyToOne private Message messageid; public Messagecomment() { } public Messagecomment(Long messagecommentid) { this.messagecommentid = messagecommentid; } public Long getMessagecommentid() { return messagecommentid; } public void setMessagecommentid(Long messagecommentid) { this.messagecommentid = messagecommentid; } public String getCommenttype() { return commenttype; } public void setCommenttype(String commenttype) { this.commenttype = commenttype; } public Date getCreatedon() { return createdon; } public void setCreatedon(Date createdon) { this.createdon = createdon; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Member1 getMemberid() { return memberid; } public void setMemberid(Member1 memberid) { this.memberid = memberid; } public Message getMessageid() { return messageid; } public void setMessageid(Message messageid) { this.messageid = messageid; } @Override public int hashCode() { int hash = 0; hash += (messagecommentid != null ? messagecommentid.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Messagecomment)) { return false; } Messagecomment other = (Messagecomment) object; if ((this.messagecommentid == null && other.messagecommentid != null) || (this.messagecommentid != null && !this.messagecommentid.equals(other.messagecommentid))) { return false; } return true; } @Override public String toString() { return "entities.Messagecomment[ messagecommentid=" + messagecommentid + " ]"; } }
package com.mycompany.collectorservice.service; import com.mycompany.collectorservice.model.News; import com.mycompany.collectorservice.repository.NewsRepository; import org.springframework.stereotype.Service; @Service public class NewsServiceImpl implements NewsService { private final NewsRepository newsRepository; public NewsServiceImpl(NewsRepository newsRepository) { this.newsRepository = newsRepository; } @Override public News createNews(News news) { return newsRepository.save(news); } }
package com.sparshik.yogicapple.model; /** * data structure for user chat profile */ public class UserChatProfile { private String nickName; private String chatProfilePicUrl; public UserChatProfile() { } public UserChatProfile(String nickName, String chatProfilePicUrl) { this.nickName = nickName; this.chatProfilePicUrl = chatProfilePicUrl; } public String getNickName() { return nickName; } public String getChatProfilePicUrl() { return chatProfilePicUrl; } }
package com.szhrnet.taoqiapp.view.home; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.szhrnet.taoqiapp.R; import com.szhrnet.taoqiapp.base.BaseFragment; import com.szhrnet.taoqiapp.mvp.contract.ExampleContract; import com.szhrnet.taoqiapp.mvp.model.LoginModel; import com.szhrnet.taoqiapp.mvp.presenter.ExamplePresenter; //import butterknife.BindView; /** * <pre> * author: Zou Juequn * desc : ้ฆ–้กตFragment * email:15695947865@139.com */ public class HomeFragment extends BaseFragment implements ExampleContract.View { // @BindView(R.id.textview) private TextView mTextView; private ExampleContract.Presenter mPresenter; @Override public int bindLayout() { return R.layout.fragment_home; } @Override public void initView(View parentView) { mTextView = parentView.findViewById(R.id.textview2); mPresenter = new ExamplePresenter(this); mPresenter.doLogin(); } @Override protected void initWidget(Bundle savedInstanceState) { } @Override public void widgetClick(View v) { } @Override public void showError(String str) { } @Override public void showLoading() { } @Override public void setPresenter(ExampleContract.Presenter presenter) { this.mPresenter = presenter; } @Override public void onDoLoginSuccessful(LoginModel model) { mTextView.setText(model.getUserarr().getUser_nick()); } }
package org.giddap.dreamfactory.leetcode.onlinejudge; /** * http://oj.leetcode.com/problems/container-with-most-water/ * <p/> * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, * ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, * which together with x-axis forms a container, such that the container contains the most water. * <p/> * Links: * http://n00tc0d3r.blogspot.com/2013/02/container-with-most-water.html?q=Container+with+most+water */ public interface ContainerWithMostWater { int maxArea(int[] height); }
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.cms.dao; import java.util.Date; import java.util.List; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.cms.entity.Article; import com.thinkgem.jeesite.modules.cms.entity.Category; /** * ๆ–‡็ซ DAOๆŽฅๅฃ * * @author ThinkGem * @version 2013-8-23 */ @MyBatisDao public interface ArticleDao extends CrudDao<Article> { public long findCount(Article article); public List<Article> findByIdIn(String[] ids); public int updateHitsAddOne(String id); public int updateExpiredWeight(Article article); public List<Category> findStats(Category category); void insertCategoryArticle(Article article); void deleteCategoryArticle(Article article); //SQLๆœ็ดข List<Article> searchList(Article article); long searchCount(Article article); List<Article> findLastAndNextOne(Article article); List<Article> findTopList(Date updatedate, String isImage, int size); List<Article> findTopImageList(Date updatedate, String isImage, int size); List<Article> findPreList(Article article); List<Article> findNextList(Article article); public Long countArticle(Article article); public List<Integer> getNewsNfF(Article article); }
import javax.swing.JFrame; import javax.swing.JLabel; public class ScoreScreen extends JFrame{ public ScoreScreen(String s){ super("GAMEOVER"); setBounds(100, 100, 250, 100); JLabel gameOver = new JLabel("test"); JLabel score = new JLabel("TEST"); score.setText("Score: "+s); score.setLocation(100,100); add(score); setLocationRelativeTo(null); setResizable(true); setVisible(true); } }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package dk.sidereal.lumm.ui; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.resolvers.ClasspathFileHandleResolver; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.math.Vector2; import dk.sidereal.lumm.architecture.Lumm; import dk.sidereal.lumm.architecture.LummObject; import dk.sidereal.lumm.architecture.LummScene; import dk.sidereal.lumm.architecture.concrete.ConcreteLummObject; import dk.sidereal.lumm.architecture.listeners.OnDisposeListener; /** * Abstract object used for drawing text on the screen. Supports customisation * for different font, font colors, scale, transparency; * * @author Claudiu Bele */ public class TextBuilder extends ConcreteLummObject { // region static /** * Gets the Blocks4 font made by Claudiu Bele, which can be already found in * the framework and doesn't require creating additional files. * * @return */ public static BitmapFont getFont(String fontDataPath) { return new BitmapFont(Lumm.assets.get(fontDataPath, BitmapFont.class, ClasspathFileHandleResolver.class).getData().getFontFile()); } // endregion static // region fields public enum Allign { Left, Center, Right } ; public enum Anchor { Top, Middle, Bottom } public static class Paragraph { public String text; public Color color; public Paragraph(String text, Color color) { this.text = text; this.color = color; } } public Color color; public String text; private BitmapFont font; private GlyphLayout glyphLayout; public float alpha; public float scale; public Vector2 bounds; private boolean wrapText; private float lineSpacing; public float windowSize; private Allign allignment; private Anchor anchor; private ArrayList<Paragraph> rawParagraphs; private ArrayList<Paragraph> paraGraphsToWrite; // endregion fields // region Constructors public TextBuilder(LummScene scene, boolean wrap) { this(scene, wrap, Lumm.assets.frameworkAssetsFolder + "Blocks.fnt"); } public TextBuilder(LummScene scene, boolean wrap, String fontDataPath) { super(scene); font = getFont(fontDataPath); this.glyphLayout = new GlyphLayout(); this.color = Color.WHITE; this.bounds = new Vector2(); rawParagraphs = new ArrayList<TextBuilder.Paragraph>(); paraGraphsToWrite = new ArrayList<TextBuilder.Paragraph>(); windowSize = Gdx.graphics.getDisplayMode().width; setAlpha(-1); setScale(1f); position.setRelative(0, 0, 5); lineSpacing = 5f; windowSize = 600; this.wrapText = wrap; allignment = Allign.Center; anchor = Anchor.Middle; onDisposeListener = new OnDisposeListener<LummObject>() { @Override public void onDispose(LummObject caller) { paraGraphsToWrite = null; rawParagraphs = null; bounds = null; color = null; font = null; } }; generateBounds(); } // endregion // region methods public final ArrayList<Paragraph> wrapText(String data, Color color) { ArrayList<Paragraph> resultingLines = new ArrayList<Paragraph>(); if (!wrapText) { resultingLines.add(new Paragraph(data, color)); return resultingLines; } // splitting the string into lines String[] lines = data.split("\n"); for (int i = 0; i < lines.length; i++) { String[] words = lines[i].split(" "); String currText = ""; for (int j = 0; j < words.length; j++) { // curr text + new word exceeds line limit, cut it glyphLayout.setText(font, currText); if (glyphLayout.width > windowSize) { // trim line currText = currText.trim(); if (currText == null) currText = ""; // this is a one word line, if (currText.equals("")) { resultingLines.add(new Paragraph(words[j], color)); } // not a one word line else { resultingLines.add(new Paragraph(currText, color)); currText = ""; j--; } } else { // append curr word to the string currText += words[j] + " "; } } currText = currText.trim(); resultingLines.add(new Paragraph(currText, color)); } glyphLayout.setText(font, "X"); bounds.set(windowSize, glyphLayout.height * resultingLines.size() + (resultingLines.size()) * lineSpacing); return resultingLines; } // region adding and setting text public final void addText(String data, Color lineColor) { rawParagraphs.add(new Paragraph(data, lineColor)); paraGraphsToWrite.addAll(wrapText(data, lineColor)); if (text == "") text = data; else text += "\n " + data; generateBounds(); } public final void addText(ArrayList<String> data, ArrayList<Color> paragraphColors) { for (int i = 0; i < data.size(); i++) { if (paragraphColors == null || paragraphColors.size() != data.size() || paragraphColors.get(i) == null) addText(data.get(i), Color.WHITE); else addText(data.get(i), paragraphColors.get(i)); } } public void setText(String data, Color targetColor) { if (text != null && text.equals(data)) return; text = data; paraGraphsToWrite.clear(); if (wrapText) { paraGraphsToWrite = wrapText(data, targetColor); } else { paraGraphsToWrite.add(new Paragraph(data, targetColor)); } rawParagraphs.clear(); rawParagraphs.add(new Paragraph(data, targetColor)); setColor(targetColor); generateBounds(); } // endregion // region getters and setters public void setWindowSize(float size) { this.windowSize = size; paraGraphsToWrite.clear(); for (int i = 0; i < rawParagraphs.size(); i++) { paraGraphsToWrite.addAll(wrapText(rawParagraphs.get(i).text, rawParagraphs.get(i).color)); } generateBounds(); } public final void clearText() { paraGraphsToWrite.clear(); rawParagraphs.clear(); generateBounds(); } public final void setAllign(Allign allignment) { this.allignment = allignment; } public final void setAnchor(Anchor anchor) { this.anchor = anchor; } public final void setFont(BitmapFont font) { this.font = font; generateBounds(); } public final void setFont(String fontPath) { font = getFont(fontPath); } public final BitmapFont getFont() { return font; } public final void setAlpha(float alpha) { if (font.getColor().a == alpha && this.alpha == alpha) return; if (alpha != -1) { alpha = Math.max(0, Math.min(1, alpha)); color.a = alpha; font.setColor(color); } this.alpha = alpha; } public final void setScale(float scale) { this.scale = Math.max(0.1f, Math.min(10, scale)); font.getData().setScale(this.scale); generateBounds(); } public final void setColor(Color color) { if (alpha != -1) color.a = alpha; this.color = color; font.setColor(color); } // endregion @Override public void onRender() { float newX, newY; float currLineOffset = 0; if (paraGraphsToWrite == null) return; for (int i = 0; i < paraGraphsToWrite.size(); i++) { glyphLayout.setText(font, paraGraphsToWrite.get(i).text); if (allignment.equals(Allign.Center)) { newX = position.getX() - glyphLayout.width / 2; } else if (allignment.equals(Allign.Left)) { newX = position.getX(); } else { newX = position.getX() - glyphLayout.width; } if (anchor.equals(Anchor.Top)) { newY = position.getY(); newY -= currLineOffset; currLineOffset += glyphLayout.height; currLineOffset += lineSpacing; } else if (anchor.equals(Anchor.Middle)) { newY = position.getY() + glyphLayout.height / 2; if (paraGraphsToWrite.size() != 0) { glyphLayout.setText(font, "X"); newY += (((paraGraphsToWrite.size() - 1) / 2f) - i) * (glyphLayout.height + lineSpacing); } } else { newY = position.getY() + glyphLayout.height / 2; newY += currLineOffset; currLineOffset += glyphLayout.height; currLineOffset += lineSpacing; } setColor(paraGraphsToWrite.get(i).color); if (alpha != -1) color.a = alpha; glyphLayout.setText(font, paraGraphsToWrite.get(i).text); font.draw(getSceneLayer().spriteBatch, glyphLayout, (int) newX, (int) newY); } generateBounds(); } public void generateBounds() { glyphLayout.setText(font, "X"); if (paraGraphsToWrite == null) paraGraphsToWrite = new ArrayList<TextBuilder.Paragraph>(); bounds.set(windowSize, glyphLayout.height * paraGraphsToWrite.size() + (paraGraphsToWrite.size()) * lineSpacing); } public void setLineSpacing(float lineSpacing) { this.lineSpacing = lineSpacing; generateBounds(); } // endregion methods }
package Thread; import java.util.concurrent.atomic.AtomicInteger; public class Counter { static int counter = 0; public static void main(String[] _){ for(int i = 0; i < 100000; i++) inc(); System.out.println(counter); for(int i = 0; i < 1000000; i++) counter2.incrementAndGet(); System.out.println(counter2); } static synchronized void inc(){ counter += 1; } static AtomicInteger counter2 = new AtomicInteger(0); }
package com.sparshik.yogicapple.ui.current; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.sparshik.yogicapple.R; import com.sparshik.yogicapple.views.CircleProgressBar; /** * View Holder for apples */ public class CurrentPackApplesViewHolder extends RecyclerView.ViewHolder { RelativeLayout mContainer; TextView mSeqNumberText, mDownloadText; CircleProgressBar mProgressBar; View mLineView; ImageView mAppleState; public CurrentPackApplesViewHolder(View itemView) { super(itemView); mContainer = (RelativeLayout) itemView.findViewById(R.id.container_list_item); mSeqNumberText = (TextView) itemView.findViewById(R.id.apple_number); mProgressBar = (CircleProgressBar) itemView.findViewById(R.id.apple_progress_circle); mLineView = itemView.findViewById(R.id.current_line); mAppleState = (ImageView) itemView.findViewById(R.id.apple_locked); mDownloadText = (TextView) itemView.findViewById(R.id.download_text); } }
package DesignPatterns.SimpleFectoryPattern; public abstract class Product { public void print() { System.out.println("SFP abstract Product"); } public abstract void ppp(); }
package com.xwolf.eop.system.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class Citys implements Serializable{ private static final long serialVersionUID = 7072513495209422317L; private Integer cid; private String bcode; private String ccode; private String cname; private String pcode; private Date ctime; private int cstatus; }
package pt.tooyummytogo; import java.util.HashMap; import java.util.Optional; public class catUtilizadores{ public HashMap<String,Utilizador> mapaUtilizadores; public catUtilizadores() { mapaUtilizadores = new HashMap<String,Utilizador>(); } public void registaUtilizador(String username, String pw) { if(!mapaUtilizadores.containsKey(username)) { mapaUtilizadores.put(username, new Utilizador(username, pw)); }else { System.out.println("Username already taken"); } } public Optional<Utilizador> tentaAutenticar(String username, String pw){ Optional<Utilizador> autenticado = Optional.ofNullable(mapaUtilizadores.get(username)); if(!autenticado.isEmpty() && mapaUtilizadores.get(username).temPassword(pw)) { return autenticado; }else { return Optional.empty(); } } }
package pro.likada.bean.model; import pro.likada.model.FinancialItem; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import java.io.Serializable; import java.util.List; /** * Created by bumur on 28.02.2017. */ @Named @SessionScoped public class FinancialItemModelBean implements Serializable{ private List<FinancialItem> financialItems; public List<FinancialItem> getFinancialItems() { return financialItems; } public void setFinancialItems(List<FinancialItem> financialItems) { this.financialItems = financialItems; } }
package example.model; import java.io.Serializable; import javax.annotation.Generated; /** * * This class was generated by MyBatis Generator. * This class corresponds to the database table demo_employee_role */ public class EmployeeRole implements Serializable { /** * Database Column Remarks: * ไธป้”ฎ */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.811+08:00", comments="Source field: demo_employee_role.id") private String id; /** * Database Column Remarks: * ็”จๆˆทid */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.employee_id") private String employeeId; /** * Database Column Remarks: * ่ง’่‰ฒid */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.role_id") private String roleId; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") private static final long serialVersionUID = 1L; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.id") public String getId() { return id; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") public EmployeeRole withId(String id) { this.setId(id); return this; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.id") public void setId(String id) { this.id = id; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.employee_id") public String getEmployeeId() { return employeeId; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") public EmployeeRole withEmployeeId(String employeeId) { this.setEmployeeId(employeeId); return this; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.employee_id") public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.role_id") public String getRoleId() { return roleId; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") public EmployeeRole withRoleId(String roleId) { this.setRoleId(roleId); return this; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source field: demo_employee_role.role_id") public void setRoleId(String roleId) { this.roleId = roleId; } @Override @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } EmployeeRole other = (EmployeeRole) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getEmployeeId() == null ? other.getEmployeeId() == null : this.getEmployeeId().equals(other.getEmployeeId())) && (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId())); } @Override @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getEmployeeId() == null) ? 0 : getEmployeeId().hashCode()); result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode()); return result; } @Override @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.812+08:00", comments="Source Table: demo_employee_role") public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", employeeId=").append(employeeId); sb.append(", roleId=").append(roleId); sb.append("]"); return sb.toString(); } }
/* * 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 Kalkulator; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; /** * * @author gokpraz */ public class Calculator extends UnicastRemoteObject implements CalculatorInterface { public Calculator() throws RemoteException {} @Override public double penjumlahan(double nilai1, double nilai2) throws RemoteException { double jumlah = nilai1 + nilai2; return jumlah; } @Override public double pengurangan(double nilai1, double nilai2) throws RemoteException { double kurang = nilai1 - nilai2; return kurang; } @Override public double perkalian(double nilai1, double nilai2) throws RemoteException { double kali = nilai1 * nilai2; return kali; } @Override public double pembagian(double nilai1, double nilai2) throws RemoteException { double bagi = nilai1 / nilai2; return bagi; } }
package utils; import task.*; import date.*; import java.io.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; import java.io.File; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class ConstructorsForXML{ private static ConstructorsForXML fileXMLCInstance = null; public synchronized static ConstructorsForXML getInstance() { if (fileXMLCInstance == null) fileXMLCInstance = new ConstructorsForXML(); return fileXMLCInstance; } public void ParamLangXML() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } DocumentBuilder builder; /** * @param filename file for writing. * @param taskList a list of tasks that must be saved * @throws TransformerException when error during the transformation process. * @throws IOException */ public void WriteParamXML(String filename, TaskList list) throws TransformerException, IOException { Document doc=builder.newDocument(); Element RootElement=doc.createElement("tasklist"); for(int i=0;i<list.size();i++){ Element NameElementTask=doc.createElement("task"); Element NameElementId=doc.createElement("id"); NameElementId.appendChild(doc.createTextNode(list.get(i).getId())); NameElementTask.appendChild(NameElementId); Element NameElementDate=doc.createElement("date"); NameElementDate.appendChild(doc.createTextNode(WorkWithDate.getInstance().dateToString(list.get(i).getDate()))); NameElementTask.appendChild(NameElementDate); Element NameElementDiscr=doc.createElement("description"); NameElementDiscr.appendChild(doc.createTextNode(list.get(i).getDescription())); NameElementTask.appendChild(NameElementDiscr); Element NameElementContact=doc.createElement("contacts"); NameElementContact.appendChild(doc.createTextNode(list.get(i).getContacts())); NameElementTask.appendChild(NameElementContact); Element NameElementActiv=doc.createElement("activity"); if (list.get(i).getActivity()==true){ NameElementActiv.appendChild(doc.createTextNode("true")); }else{ NameElementActiv.appendChild(doc.createTextNode("false")); } NameElementTask.appendChild(NameElementActiv); RootElement.appendChild(NameElementTask); } doc.appendChild(RootElement); Transformer t=TransformerFactory.newInstance().newTransformer(); t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(filename))); } /** * @param filename file for reading * @throws SAXParseException when XML parse error or warning. * @throws SAXException when occurred SAX error or warning. * @throws Throwable */ public TaskMaker ReadParamXML(String filename) throws SAXParseException,SAXException,Throwable { Document doc = builder.parse (new File(filename)); doc.getDocumentElement ().normalize(); NodeList listOfTasks = doc.getElementsByTagName("task"); TaskMaker taskList = new TaskMaker(); for(int s=0; s<listOfTasks.getLength(); s++){ Node firstTaskNode = listOfTasks.item(s); if(firstTaskNode.getNodeType() == Node.ELEMENT_NODE){ Element firstTaskElement = (Element)firstTaskNode; //------- NodeList idList = firstTaskElement.getElementsByTagName("id"); Element idElement = (Element)idList.item(0); NodeList textIdList = idElement.getChildNodes(); String id = textIdList.item(0).getNodeValue().trim(); //------- NodeList dateList = firstTaskElement.getElementsByTagName("date"); Element dateElement = (Element)dateList.item(0); NodeList textDateList = dateElement.getChildNodes(); Date date = WorkWithDate.getInstance().stringToDate(textDateList.item(0).getNodeValue().trim()); //------- NodeList diskList = firstTaskElement.getElementsByTagName("description"); Element diskElement = (Element)diskList.item(0); NodeList textDiskList = diskElement.getChildNodes(); String disk = textDiskList.item(0).getNodeValue().trim(); //---- NodeList contactList = firstTaskElement.getElementsByTagName("contacts"); Element contactElement = (Element)contactList.item(0); NodeList textContactList = contactElement.getChildNodes(); String contact = textContactList.item(0).getNodeValue().trim(); //------ NodeList activList = firstTaskElement.getElementsByTagName("activity"); Element activElement = (Element)activList.item(0); NodeList textActivList = activElement.getChildNodes(); boolean activity = Boolean.parseBoolean(textActivList.item(0).getNodeValue().trim()); taskList.addTask(new Task(id,date,disk,contact,activity)); } } return taskList; } }
package cn.com.signheart.common.util; import cn.com.signheart.common.reflation.ClassType; import cn.com.signheart.common.reflation.ObjectUtil; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WebUtil { public static HashMap contentTypeMap = new HashMap(); public static HashMap charMap = new HashMap(); public WebUtil() { } public static String outSelected(String str1, String str2) { return !AssertUtil.isEmpty(str1) && !AssertUtil.isEmpty(str2)?(str1.equals(str2)?" selected ":""):""; } public static String getParm(HttpServletRequest _request, String _parmName, String _defaultValue) { Object rs = _request.getParameter(_parmName); if(AssertUtil.isEmpty(rs)) { rs = _request.getAttribute(_parmName); } return AssertUtil.isEmpty(rs)?_defaultValue:rs.toString(); } public static String[] getParms(HttpServletRequest _request, String _parmName, String[] _defaultValue) { Object rs = _request.getParameter(_parmName); if(AssertUtil.isEmpty(rs)) { rs = _request.getAttribute(_parmName); } return AssertUtil.isEmpty(rs)?_defaultValue:(String[])((String[])rs); } public static String outChecked(String str1, String str2) { return !AssertUtil.isEmpty(str1) && !AssertUtil.isEmpty(str2)?(str1.equals(str2)?" checked ":""):""; } public static boolean ParmIsNull(String str) { return AssertUtil.isEmpty(str) || str.equalsIgnoreCase("null"); } public static String outString(Object str) { if(AssertUtil.isEmpty(str)) { return "&nbsp;"; } else { Set keySet = charMap.keySet(); String value = str.toString(); Iterator ri = keySet.iterator(); while(ri.hasNext()) { String key = (String)ri.next(); if(str.getClass().equals(ClassType.sqlTimeType)) { value = value.substring(0, 19); } if(str.getClass().equals(ClassType.dateType)) { value = value.substring(0, 10); } else { value = StringUtil.replace(value, key, charMap.get(key).toString()); } } return value; } } public static String outNull(Object str) { if(AssertUtil.isEmpty(str)) { return ""; } else { Set keySet = charMap.keySet(); String value = str.toString(); Iterator ri = keySet.iterator(); while(ri.hasNext()) { String key = (String)ri.next(); if(str.getClass().equals(ClassType.sqlTimeType)) { value = value.substring(0, 19); } if(str.getClass().equals(ClassType.dateType)) { value = value.substring(0, 10); } else { value = StringUtil.replace(value, key, charMap.get(key).toString()); } } return value; } } public static String outString(Object str, int size) { String rStr = "&nbsp"; if(AssertUtil.isEmpty(str)) { return rStr; } else { try { String e = (String)str; if(e.length() > size) { str = e.substring(0, size) + "...."; } } catch (Exception var4) { var4.printStackTrace(); } return str.toString(); } } public static String outString(int length, int number, int mode) { char[] eachNumb = new char[length]; String numStr = Integer.toString(number); char[] tempChar = numStr.toCharArray(); int i; if(tempChar.length > length) { for(i = 0; i < length; ++i) { if(mode == 0) { eachNumb[i] = tempChar[tempChar.length - length + i]; } if(mode == 1) { eachNumb[i] = tempChar[i]; } } } else { for(i = 0; i < length; ++i) { if(i < length - tempChar.length) { eachNumb[i] = 48; } else { eachNumb[i] = tempChar[tempChar.length - (length - i)]; } } } return new String(eachNumb); } public static String outNull(Object obj, String MethName) throws Exception { return outNull(ObjectUtil.invokMeth(obj, MethName)); } public static String outString(Object obj, String MethName) throws Exception { return outString(ObjectUtil.invokMeth(obj, MethName)); } public static String getReadyOnly() { return " style=\'width:100%;background-color:#cccccc\' readonly=\'true\'"; } public static String getContentNameByFileExtendName(String _extendName) throws Exception { if(AssertUtil.isEmpty(_extendName)) { throw new Exception("้”™่ฏฏ๏ผŒๆ นๆฎๆ–‡ไปถๆ‰ฉๅฑ•ๅๅ–ContextTypeๆ—ถๅ‘็”Ÿ้”™่ฏฏ๏ผšๆœชไผ ๅ…ฅๆ–‡ไปถๆ‰ฉๅฑ•ๅ๏ผ"); } else { return (String)contentTypeMap.get(StringUtil.CnvSmallChr(_extendName)); } } public static String getWebChar(String _chr) { Object temp = charMap.get(_chr); return temp == null?_chr:temp.toString(); } public static String transferAllParm(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); Enumeration parmList = request.getParameterNames(); while(parmList.hasMoreElements()) { String parmName = parmList.nextElement().toString(); if(!parmName.equals("_aido_currentPage")) { sb.append("<input type=hidden name="); sb.append(parmName); sb.append(" value=\""); sb.append(getWebChar(request.getParameter(parmName))); sb.append("\">"); } } return sb.toString(); } public static String transferPageParm(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); Enumeration parmList = request.getParameterNames(); while(parmList.hasMoreElements()) { String parmName = parmList.nextElement().toString(); sb.append("<input type=hidden name="); sb.append(parmName); sb.append(" value=\""); sb.append(getWebChar(request.getParameter(parmName))); sb.append("\">"); } return sb.toString(); } public static String getTxtWithoutHTMLElement(String element, String regx) { if(null != element && !"".equals(element.trim())) { regx = "(<" + regx + "[^<|^>]*>|</" + regx + ">)"; Pattern pattern = Pattern.compile(regx); Matcher matcher = pattern.matcher(element); StringBuffer txt = new StringBuffer(); while(matcher.find()) { String group = matcher.group(); if(group.matches("<[\\s]*>")) { matcher.appendReplacement(txt, group); } else { matcher.appendReplacement(txt, ""); } } matcher.appendTail(txt); return txt.toString(); } else { return element; } } public static <T> T getFromRequestAttr(HttpServletRequest request, String key, Class<T> pagerClass) { Object tempObj = request.getAttribute(key); if(tempObj == null) { tempObj = request.getParameter(key); } if(tempObj == null) { tempObj = request.getSession().getAttribute(key); } if(tempObj == null) { tempObj = request.getSession().getAttribute(key); } Object obj = null; if(tempObj != null) { obj = tempObj; } return (T) obj; } static { contentTypeMap.put("gif", "image/gif"); contentTypeMap.put("jpg", "image/jpeg"); contentTypeMap.put("jpeg", "image/jpeg"); contentTypeMap.put("png", "image/png"); contentTypeMap.put("tif", "image/tiff"); contentTypeMap.put("tiff", "image/tiff"); contentTypeMap.put("xbm", "image/x-xbitmap"); contentTypeMap.put("xpm", "image/x-xpixmap"); contentTypeMap.put("xls", "application/vnd.ms-excel"); contentTypeMap.put("doc", "application/msword"); charMap.put(">", "&gt;"); charMap.put("<", "&lt;"); charMap.put(">=", "&gt;="); charMap.put("<=", "&lt;="); charMap.put("<>", "&lt;&gt;"); charMap.put("\"", "&#34;"); charMap.put("\'", "&#39;"); } }
package com.swimmi.common; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import android.util.Log; /** * ๆ•ฐๆฎๅบ“ๅค„็† * @author zhoubin02 * */ public class DBHelper { //ๆ•ฐๆฎๅบ“ๅ public static final String DATA_BASE = "windnote_zb.db"; //่Žทๅ–ๆ•ฐๆฎๅบ“่ฟžๆŽฅๅฏน่ฑก public SQLiteDatabase Database(int raw_id, Activity activity) { try { int BUFFER_SIZE = 100000; String DB_NAME = DBHelper.DATA_BASE;//"windnote.db"; String PACKAGE_NAME = "com.swimmi.windnote"; String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME+"/databases/"; File destDir = new File(DB_PATH); if (!destDir.exists()) { destDir.mkdirs(); } String file=DB_PATH+DB_NAME; if (!(new File(file).exists())) { InputStream is = activity.getResources().openRawResource( raw_id); FileOutputStream fos = new FileOutputStream(file); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file,null); return db; } catch (FileNotFoundException e) { Log.e("Database", "File not found"); e.printStackTrace(); } catch (IOException e) { Log.e("Database", "IO exception"); e.printStackTrace(); } return null; } }
package com.activities; import java.util.ArrayList; import objects.Joueur; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.custom.HelperCouleur; import com.custom.Liste_Couleur; import com.custom.ServiceReseau; import com.custom.ServiceReseau.ReseauBinder; import com.game.InterfaceLOTR; import com.lotr_risk.R; public class StartUpActivity extends Activity implements InterfaceLOTR { Dialog dialog; Button BT_Connexion, BT_Nb_Joueurs, BT_Envoi_Joueurs; EditText ET_addrServ, ET_numPort; Context context; ProgressDialog progressDialog; HelperCouleur helperCouleur; View [] tabLigneJoueur; ArrayList<Joueur> listJoueurs; ServiceReseau serviceReseau; boolean connexionActive = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_up); context = StartUpActivity.this; helperCouleur = new HelperCouleur(context); dialog = new Dialog(context); BT_Connexion = (Button) findViewById(R.id.BT_Connexion); ET_addrServ = (EditText) findViewById(R.id.ET_nomJoueur); ET_numPort = (EditText) findViewById(R.id.ET_portServeur); BT_Connexion.setOnClickListener(loggerListener); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(StartUpActivity.this, ServiceReseau.class); startService(intent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private void connexion_Serveur() { //String addresse = ET_addrServ.getText().toString(); //String numPort = ET_numPort.getText().toString(); /* VALEURS ARBITRAIRES D'ADRESSE POUR RAPIDITE DE TEST */ if (!connexionActive) { Toast.makeText(context, "Service rรฉseau non initialisรฉ, veuillez relancer ou patienter...", Toast.LENGTH_SHORT).show(); return; } if (serviceReseau.connexionServeur()) { dialog.setTitle("Paramรจtres de jeu"); dialog.setContentView(R.layout.layout_nombre_joueurs); BT_Nb_Joueurs = (Button) dialog.findViewById(R.id.BT_NB_Joueurs); BT_Nb_Joueurs.setOnClickListener(nb_JoueursListener); dialog.show(); } } private OnClickListener nb_JoueursListener = new OnClickListener() { @Override public void onClick(View v) { Integer nb_Joueurs; EditText entreeNb_Joueurs = (EditText) dialog.findViewById(R.id.ET_NB_Joueurs); nb_Joueurs = Integer.parseInt(entreeNb_Joueurs.getText().toString()); if (nb_Joueurs < 2 || nb_Joueurs > 4) Toast.makeText(context, "Veuillez entrer un nombre entre 2 et 4", Toast.LENGTH_SHORT).show(); else remplir_entree_joueurs(nb_Joueurs.intValue()); } }; @SuppressLint("InflateParams") private void remplir_entree_joueurs(int nbJoueurs) { //Initialisation des paramรจtres et des variables liรฉ au layout principal LinearLayout layoutPrincipal = new LinearLayout(context); layoutPrincipal.setOrientation(LinearLayout.VERTICAL); Liste_Couleur couleurAdapter = new Liste_Couleur(context, android.R.layout.simple_spinner_item, helperCouleur.getListCouleur()); dialog.setTitle("Paramรจtres des joueurs"); dialog.setContentView(layoutPrincipal); //Crรฉation et enregistrement des lignes de saisies joueurs tabLigneJoueur = new View[nbJoueurs]; //Initialisation du tableau enregistrant les saisies joueur LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); for (int i = 0; i < nbJoueurs; i++) { View ligneJoueur = inflater.inflate(R.layout.ligne_entree_joueur, null); //FIX THIS TODO tabLigneJoueur[i] = ligneJoueur; Spinner spin = (Spinner) ligneJoueur.findViewById(R.id.listCouleurs); spin.setAdapter(couleurAdapter); //Remplissage de la liste avec les valeurs des couleurs layoutPrincipal.addView(ligneJoueur); } //Crรฉation du bouton d'envoi, ajout du listener et affichage Button BT_Envoi = new Button(context); BT_Envoi.setText("Envoyer"); BT_Envoi.setOnClickListener(envoiJoueursListener); layoutPrincipal.addView(BT_Envoi); dialog.show(); } private OnClickListener envoiJoueursListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); listJoueurs = new ArrayList<Joueur>(tabLigneJoueur.length); String selectionCouleur; EditText ET_nomJoueur; Spinner listeCouleurs; for (int i = 0; i < tabLigneJoueur.length; i++) { ET_nomJoueur = (EditText) tabLigneJoueur[i].findViewById(R.id.ET_nomJoueur); listeCouleurs = (Spinner) tabLigneJoueur[i].findViewById(R.id.listCouleurs); selectionCouleur = helperCouleur.getRGBFromColorName(listeCouleurs.getSelectedItem().toString()); listJoueurs.add(new Joueur(ET_nomJoueur.getText().toString(), selectionCouleur)); } envoi_Joueurs_Serveur(); //Envoi de la liste construite au serveur } }; private void envoi_Joueurs_Serveur() { setProgressDialog("Crรฉation des joueurs", "Envoi au serveur...", false); listJoueurs = serviceReseau.envoyerTraitementServeur(listJoueurs, CREATION_JOUEURS); if (listJoueurs == null) Toast.makeText(context, "Erreur lors de la rรฉception des joueurs", Toast.LENGTH_SHORT).show(); else reception_Joueurs_Cree(); } private void reception_Joueurs_Cree() { setProgressDialog("Crรฉation des joueurs", "Rรฉception des joueurs crรฉes...", false); listJoueurs = serviceReseau.envoyerTraitementServeur(listJoueurs, SERVEUR_ENVOI_JOUEURS); if (listJoueurs == null) Toast.makeText(context, "Erreur lors de la rรฉception des joueurs", Toast.LENGTH_SHORT).show(); else { Intent intent = new Intent(this, InitGameActivity.class); intent.putExtra("listJoueurs", listJoueurs); startActivity(intent); } setProgressDialog("", "", true); } private OnClickListener loggerListener = new OnClickListener() { @Override public void onClick(View v) { connexion_Serveur(); } }; /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { ReseauBinder binder = (ReseauBinder) service; serviceReseau = binder.getService(); if (serviceReseau != null) connexionActive = true; } @Override public void onServiceDisconnected(ComponentName arg0) { connexionActive = false; } }; public void setProgressDialog(final String titre, final String message, boolean close) { if (progressDialog == null) progressDialog = new ProgressDialog(context); else if (close && progressDialog.isShowing()) { progressDialog.dismiss(); return; } runOnUiThread(new Runnable() { @Override public void run() { if (!isFinishing()) { progressDialog.setTitle(titre); progressDialog.setMessage(message); progressDialog.show(); } } }); } }
package com.tvm.enums; /** * * Enums are declared as Class and Interface.Enums helps to define the * constants that are used in the programs. Enums help in enforcing the type * safety when using constants All the constants declared in enums are * implicitly static and final. * * If we declare a constructor in enum it has to be private else will get a * compilation error. Instances of enums cannot be created using new keyword. * * * Enums has a static method values() which return an array of all the methods.It will return the singleton objects of all the enums * */ public enum EnumsExample { }
package com.epam.hadoop; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import lombok.Data; import org.apache.hadoop.io.Writable; @Data public class CustomValue implements Writable { private long sum; private double mean; public CustomValue() { } public CustomValue(long sum, double mean) { this.sum = sum; this.mean = mean; } public void write(DataOutput out) throws IOException { out.writeLong(sum); out.writeDouble(mean); } public void readFields(DataInput in) throws IOException { sum = in.readLong(); mean = in.readDouble(); } }
package utils; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; public class TicketBookingUtils { public static WebDriver driver; public void openBrowser() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get(TicketBookingConstant.url); driver.manage().window().maximize(); implicitWaitUtilInSeconds(driver,3); driver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div/div[1]/a")).click(); } public void openVirginAtlanticBrowser() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get(TicketBookingConstant.virginATURL); driver.manage().window().maximize(); implicitWaitUtilInSeconds(driver,3); } public void closeBrowser() { driver.close(); } public static void implicitWaitUtilInSeconds(WebDriver driver, int maxTimeOut) { driver.manage().timeouts().implicitlyWait(maxTimeOut, TimeUnit.SECONDS); } public static void explicitWaitTime(WebDriver driver, int maxTimeout, WebElement element) { WebDriverWait wait = new WebDriverWait(driver,10); wait.until(ExpectedConditions.visibilityOf(element)); } public static void scrollBar(WebDriver driver, int maxScroll) { JavascriptExecutor js = (JavascriptExecutor) driver; String actionStr = "window.scrollBy(0," + maxScroll + ")"; js.executeScript(actionStr); } }
package com.delaroystudios.alarmreminder; public @interface NotNull { }
/* Given a collection of numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. */ public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> path = new ArrayList<Integer>(); boolean[] visited = new boolean[nums.length]; /*for (int i=0;i<nums.length;i++){ visited[i]=false; }*/ if (nums==null || nums.length==0) return res; Arrays.sort(nums); helper(nums, path, res, visited); return res; } private void helper(int[] nums, List<Integer> path, List<List<Integer>> res, boolean[] visited){ if (path.size()==nums.length){ res.add(new ArrayList<Integer>(path)); return; } for (int i=0;i<nums.length;i++){ if (!visited[i]){ path.add(nums[i]); visited[i]=true; helper(nums, path, res,visited); path.remove(path.size()-1); visited[i]=false; } } }
import java.sql.DatabaseMetaData; /** * * ActorRole Class * */ public class ActorRole { private int actorID; private int titleID; private String aRole; /********** Constructors **********/ public ActorRole(int aid, int tid) { actorID = aid; titleID = tid; } public ActorRole(int aid, int tid, String role) { actorID = aid; titleID = tid; aRole = role; } /********** Getters **********/ public int getAID() { return actorID; } public int getTID() { return titleID; } public String getRole() { return aRole; } /********** Setters **********/ public void setAID(int aid) { actorID = aid; } public void setTID(int tid) { titleID = tid; } public void setRole(String role) { aRole = role; } /********** Output Methods **********/ public String toString() { return "(AID: " + String.valueOf(actorID) + " TID: " + String.valueOf(titleID) + ") Role: " + aRole; } public String toViewHTML() { return "<tr><td>" + String.valueOf(actorID) + "</td><td>" + String.valueOf(titleID) + "</td><td>" + aRole + "</td><td></tr>"; } public String toEditHTML() { return "<tr><td><input type=\"text\" name=\"AID\" />" + String.valueOf(actorID) + "</td><td><input type=\"password\" name=\"TID\" />" + String.valueOf(titleID) + "</td><td><input type=\"text\" name=\"role\" />" + aRole + "</td><td></tr>"; } }
package com.housesline.bean; /** * ๅ‘จๆŠฅๆœˆๆŠฅๅญฃๆŠฅๅฏน่ฑก * @author cdh 2017-09-11 * */ public class ReportResult { //ๅ‘จๆŠฅๅ็งฐ๏ผˆExcelๆ ‡้ข˜๏ผ‰ private String reportName; //้กน็›ฎid private String projectId; //้กน็›ฎๅ็งฐ private String projectName; //ๅผ€ๅง‹ๆ—ถ้—ด private String startTime; //็ป“ๆŸๆ—ถ้—ด private String endTime; //ๆŽฅ่ฎฟๆ€ปๆ•ฐ private Integer visitCount; //ๆœ‰ๆ•ˆๆŽฅ่ฎฟ็އ private String validVisitRate; //้ฆ–่ฎฟๆœ‰ๆ•ˆ็އ private String validNewCuVisitRate; //่€ๅฎขๆˆทๆŽฅ่ฎฟๅ ๆฏ” private String oldCuVisitRate; //ๆ–ฐๅขžๅ‚จๅฎข private Integer newCuCount; // ็ดฏ่ฎก่€ๅฎขๆˆท private Integer totalOldCuCount; // ็ดฏ่ฎกๆ€ปๅ‚จๅฎข private Integer totalCuCount; // ๆœฌๅญฃๆ–ฐๅขžๆ–ฐๅขž่ฎค่ดญๅฅ—ๆ•ฐ private Integer subscribeHouseCount; // ่ฎค่ดญๅฅ—ๆ•ฐๆฏ”่พƒไธŠๅญฃๅบฆ็š„ๅขž้•ฟ/ๅ‡ๅฐ‘ private String subscribeHouseRate; // ๆœฌๅญฃๆ–ฐๅขž่ฎค่ดญ้‡‘้ข private Long subscribeMoney; // ่ฎค่ดญ้‡‘้ขๆฏ”่พƒไธŠๅญฃๅบฆ็š„ๅขž้•ฟ/ๅ‡ๅฐ‘ private String subscribeMoneyRate; // ๆœฌๅญฃ็ญพ็บฆๅฅ—ๆ•ฐ private Integer signCount; // ๆœฌๅญฃ็ญพ็บฆๅฅ—ๆ•ฐๆฏ”่พƒไธŠๅญฃๅบฆๅขž้•ฟ/ๅ‡ๅฐ‘ private String signRate; // ๆœฌๅญฃๅบฆ็ญพ็บฆ้‡‘้ข private Long signHouseMoney; // ๆœฌๅญฃๅบฆ็ญพ็บฆ้‡‘้ขๆฏ”่พƒไธŠๅญฃๅบฆ็š„ๅขž้•ฟ/ๅ‡ๅฐ‘ private String signHouseMoneyRate; // ๆœฌๅญฃๅบฆๆ–ฐๅฎขๆˆทๆŽฅ่ฎฟ็ญพ็บฆ็އ private String newCustomerSignedRate; // ๅ‚จๅฎข็ญพ็บฆ็އ private String momeryCustomerSignedRate; // ่€ๅฎขๆˆท็ญพ็บฆ็އ private String oldCustomerSignedRate; // ่ฎค่ดญๅฎขๆˆท็ญพ็บฆ็އ private String contratCuSignedRate; public String getReportName() { return reportName; } public void setReportName(String reportName) { this.reportName = reportName; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public Integer getVisitCount() { return visitCount; } public void setVisitCount(Integer visitCount) { this.visitCount = visitCount; } public String getValidVisitRate() { return validVisitRate; } public void setValidVisitRate(String validVisitRate) { this.validVisitRate = validVisitRate; } public String getValidNewCuVisitRate() { return validNewCuVisitRate; } public void setValidNewCuVisitRate(String validNewCuVisitRate) { this.validNewCuVisitRate = validNewCuVisitRate; } public String getOldCuVisitRate() { return oldCuVisitRate; } public void setOldCuVisitRate(String oldCuVisitRate) { this.oldCuVisitRate = oldCuVisitRate; } public Integer getNewCuCount() { return newCuCount; } public void setNewCuCount(Integer newCuCount) { this.newCuCount = newCuCount; } public Integer getTotalOldCuCount() { return totalOldCuCount; } public void setTotalOldCuCount(Integer totalOldCuCount) { this.totalOldCuCount = totalOldCuCount; } public Integer getTotalCuCount() { return totalCuCount; } public void setTotalCuCount(Integer totalCuCount) { this.totalCuCount = totalCuCount; } public Integer getSubscribeHouseCount() { return subscribeHouseCount; } public void setSubscribeHouseCount(Integer subscribeHouseCount) { this.subscribeHouseCount = subscribeHouseCount; } public String getSubscribeHouseRate() { return subscribeHouseRate; } public void setSubscribeHouseRate(String subscribeHouseRate) { this.subscribeHouseRate = subscribeHouseRate; } public Long getSubscribeMoney() { return subscribeMoney; } public void setSubscribeMoney(Long subscribeMoney) { this.subscribeMoney = subscribeMoney; } public String getSubscribeMoneyRate() { return subscribeMoneyRate; } public void setSubscribeMoneyRate(String subscribeMoneyRate) { this.subscribeMoneyRate = subscribeMoneyRate; } public Integer getSignCount() { return signCount; } public void setSignCount(Integer signCount) { this.signCount = signCount; } public String getSignRate() { return signRate; } public void setSignRate(String signRate) { this.signRate = signRate; } public Long getSignHouseMoney() { return signHouseMoney; } public void setSignHouseMoney(Long signHouseMoney) { this.signHouseMoney = signHouseMoney; } public String getSignHouseMoneyRate() { return signHouseMoneyRate; } public void setSignHouseMoneyRate(String signHouseMoneyRate) { this.signHouseMoneyRate = signHouseMoneyRate; } public String getNewCustomerSignedRate() { return newCustomerSignedRate; } public void setNewCustomerSignedRate(String newCustomerSignedRate) { this.newCustomerSignedRate = newCustomerSignedRate; } public String getMomeryCustomerSignedRate() { return momeryCustomerSignedRate; } public void setMomeryCustomerSignedRate(String momeryCustomerSignedRate) { this.momeryCustomerSignedRate = momeryCustomerSignedRate; } public String getOldCustomerSignedRate() { return oldCustomerSignedRate; } public void setOldCustomerSignedRate(String oldCustomerSignedRate) { this.oldCustomerSignedRate = oldCustomerSignedRate; } public String getContratCuSignedRate() { return contratCuSignedRate; } public void setContratCuSignedRate(String contratCuSignedRate) { this.contratCuSignedRate = contratCuSignedRate; } @Override public String toString() { return "ReportResult [projectName=" + projectName + ", startTime=" + startTime + ", endTime=" + endTime + ", visitCount=" + visitCount + ", validVisitRate=" + validVisitRate + ", validNewCuVisitRate=" + validNewCuVisitRate + ", oldCuVisitRate=" + oldCuVisitRate + ", newCuCount=" + newCuCount + ", totalOldCuCount=" + totalOldCuCount + ", totalCuCount=" + totalCuCount + ", subscribeHouseCount=" + subscribeHouseCount + ", subscribeHouseRate=" + subscribeHouseRate + ", subscribeMoney=" + subscribeMoney + ", subscribeMoneyRate=" + subscribeMoneyRate + ", signCount=" + signCount + ", signRate=" + signRate + ", signHouseMoney=" + signHouseMoney + ", signHouseMoneyRate=" + signHouseMoneyRate + ", newCustomerSignedRate=" + newCustomerSignedRate + ", momeryCustomerSignedRate=" + momeryCustomerSignedRate + ", oldCustomerSignedRate=" + oldCustomerSignedRate + ", contratCuSignedRate=" + contratCuSignedRate + "]"; } }
package teste; import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.Cipher; public class teste { static String IV = "AAAAAAAAAAAAAAAA"; static String textopuro = "admin"; static String chaveencriptacao = "0123456789abcdef"; public static void main(String [] args) { try { System.out.println("Texto Puro: " + textopuro); byte[] textoencriptado = encrypt(textopuro, chaveencriptacao); System.out.print("Texto Encriptado:"); for (int i=0; i<textoencriptado.length; i++) System.out.print(new Integer(textoencriptado[i])); System.out.println(""); String textodecriptado = decrypt(textoencriptado, chaveencriptacao); System.out.println("Texto Decriptado: " + textodecriptado); } catch (Exception e) { e.printStackTrace(); } } public static byte[] encrypt(String textopuro, String chaveencriptacao) throws Exception { Cipher encripta = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(chaveencriptacao.getBytes("UTF-8"), "AES"); encripta.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8"))); return encripta.doFinal(textopuro.getBytes("UTF-8")); } public static String decrypt(byte[] textoencriptado, String chaveencriptacao) throws Exception{ Cipher decripta = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(chaveencriptacao.getBytes("UTF-8"), "AES"); decripta.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8"))); return new String(decripta.doFinal(textoencriptado),"UTF-8"); } }
package com.beike.core.service.trx.partner.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.beike.core.service.trx.partner.PartnerBindVoucherService; import com.beike.dao.trx.partner.PartnerBindVoucherDao; import com.beike.entity.partner.PartnerBindVoucher; /** * @title: PartnerBindVoucherServiceImpl.java * @package com.beike.core.service.trx.partner.impl * @description: * @author wangweijie * @date 2012-9-6 ไธ‹ๅˆ08:24:35 * @version v1.0 */ @Service("partnerBindVoucherService") public class PartnerBindVoucherServiceImpl implements PartnerBindVoucherService { @Autowired private PartnerBindVoucherDao partnerBindVoucherDao; @Override public void savePartnerVouchers(List<PartnerBindVoucher> pbvList) { if(null == pbvList || pbvList.size() == 0){ return; } for(PartnerBindVoucher pbv : pbvList){ partnerBindVoucherDao.addPartnerVoucher(pbv); } } public Map<String,Object> queryVoucherMap(String partnerNo,String outRequestId){ return partnerBindVoucherDao.queryVoucherBothSides(partnerNo, outRequestId); } @Override public List<PartnerBindVoucher> preQryInWtDBByPartnerBindVoucherList(String partherNo, String outRequestId) { return partnerBindVoucherDao.queryPartnerBindVoucherList(partherNo, outRequestId); } @Override public PartnerBindVoucher queryPartnerBindVoucher(String partnerNo,Long voucherId) { return partnerBindVoucherDao.queryPartnerBindVoucher(partnerNo, voucherId); } }
package com.fajar.employeedataapi.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.fajar.employeedataapi.model.SubBreed; import com.fajar.employeedataapi.service.DogService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.extern.slf4j.Slf4j; @Slf4j @RestController public class DogController { @Autowired private DogService dogService; @ApiOperation(value = "Get All dogs from dog.ceo api") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved list"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 500, message = "Server Error"), } ) @GetMapping("/dogs") public List<SubBreed> allBreeds(){ return dogService.getAllBreeds(); } @ApiOperation(value = "Get specific dog details. details included are sub breed and images of the dog", response = SubBreed.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved list"), @ApiResponse(code = 400, message = "Bad Request"), @ApiResponse(code = 500, message = "Server Error"), } ) @GetMapping("/dogs/{breed}") public SubBreed getSubBreed(@PathVariable(name="breed") String breed){ return dogService.getSubBreed(breed); } }
package com.metoo.foundation.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.metoo.core.dao.IGenericDAO; import com.metoo.foundation.domain.SearchKeyword; import com.metoo.foundation.service.ISearchKeywordService; @Service @Transactional public class SearchKeywordServiceImpl implements ISearchKeywordService{ @Resource(name = "searchKeywordDAO") private IGenericDAO<SearchKeyword> searchKeyword; @Override public boolean save(SearchKeyword instance) { // TODO Auto-generated method stub try { this.searchKeyword.save(instance); return true; } catch (Exception e) { // TODO Auto-generated catch block return false; } } @Override public boolean update(SearchKeyword intance) { // TODO Auto-generated method stub try { this.update(intance); return true; } catch (Exception e) { // TODO Auto-generated catch block return false; } } @Override public List<SearchKeyword> query(String query, Map params, int begin, int max) { // TODO Auto-generated method stub return this.searchKeyword.query(query, params, begin, max); } }
package com.ppm.project.web; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ppm.project.domain.Project; import com.ppm.project.service.MapValidationErrorService; import com.ppm.project.service.ProjectService; @RestController @RequestMapping("/api/project") public class ProjectController { @Autowired ProjectService service; @Autowired MapValidationErrorService mapValidationErrorService; @PostMapping("") public ResponseEntity<?> createNewProject(@Valid @RequestBody Project project, BindingResult result){ ResponseEntity<?> validationErrorResponse = mapValidationErrorService.getValidationErrorMap(result); if(validationErrorResponse != null) return validationErrorResponse; Project project1 = service.saveOrUpdateProject(project); return new ResponseEntity<Project>(project1, HttpStatus.CREATED); } @GetMapping("/{projectId}") public ResponseEntity<?> getProjectByIdentifier(@PathVariable String projectId){ Project project = service.findProjectByIdentifier(projectId); return new ResponseEntity<Project>(project, HttpStatus.OK); } @GetMapping("/all") public Iterable<Project> findAllProject(){ return service.findAllProject(); } @DeleteMapping("/{projectId}") public ResponseEntity<?> deleteProject(@PathVariable String projectId){ service.deleteProjectByIdentifier(projectId); return new ResponseEntity<String>("Project with Id "+projectId+ " Deleted successfully",HttpStatus.OK); } }
package com.example.pagination_task.Fragments; import android.content.Context; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.pagination_task.MainActivity; import com.example.pagination_task.R; import com.example.pagination_task.Result; import java.util.Objects; public class Movie_Details_Fragment extends Fragment { Result result; private static final String BASE_URL_IMG = "https://image.tmdb.org/t/p/w200"; public static final String TAG = "Movie_Details_Fragment"; private onMovieDetailsListener mListener; ImageView imageView; TextView title, desc; Toolbar toolbar; public Movie_Details_Fragment() { } public static Movie_Details_Fragment newInstance(Result resultData) { Movie_Details_Fragment fragment = new Movie_Details_Fragment(); Bundle args = new Bundle(); args.putParcelable(TAG, resultData); fragment.setArguments(args); Log.d(TAG, "newInstance: " + fragment.getArguments()); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { result = getArguments().getParcelable(TAG); } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_movie__details_, container, false); imageView = view.findViewById(R.id.movie_poster_img); MainActivity activity = (MainActivity) getActivity(); toolbar = view.findViewById(R.id.toolbar); toolbar.setTitle(result.getTitle()); title = view.findViewById(R.id.movie_title_txt); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary, null)); } Objects.requireNonNull(activity).setSupportActionBar(toolbar); Objects.requireNonNull(activity.getSupportActionBar()).setDisplayHomeAsUpEnabled(true); activity. getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back); activity.getSupportActionBar().setHomeButtonEnabled(true); toolbar.setNavigationOnClickListener(v -> { activity.onBackPressed(); }); desc = view.findViewById(R.id.movie_desc_txt); setMovieData(); return view; } private void setMovieData() { if (result != null) { Glide.with(Objects.requireNonNull(getContext())).load(BASE_URL_IMG + result.getPosterPath()).into(imageView); title.setText(result.getTitle()); desc.setText(result.getOverview()); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof onMovieDetailsListener) { mListener = (onMovieDetailsListener) context; } else { throw new RuntimeException(context.toString() + " must implement onMovieDetailsListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface onMovieDetailsListener { void onFragmentInteraction(Uri uri); } }
package com.atmecs.employeedatabase.entity; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "employeee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int emp_id; private String employee_name; private String email; @OneToOne(cascade = CascadeType.ALL) private EmployeeDetails employeedetails; @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "emp_id") private Set<Skills> skills; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "employee_projects", joinColumns = { @JoinColumn(referencedColumnName = "emp_id") }) private Set<Projects> projects; public Employee() { super(); } public Employee(int emp_id, String employee_name, String email) { super(); this.emp_id = emp_id; this.employee_name = employee_name; this.email = email; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmployee_name() { return employee_name; } public void setEmployee_name(String employee_name) { this.employee_name = employee_name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public EmployeeDetails getEmployeedetails() { return employeedetails; } public void setEmployeedetails(EmployeeDetails employeedetails) { this.employeedetails = employeedetails; } public Set<Skills> getSkills() { return skills; } public void setSkills(Set<Skills> skills) { this.skills = skills; } public Set<Projects> getProjects() { return projects; } public void setProjects(Set<Projects> projects) { this.projects = projects; } }
package com.indictrans.Dao; import java.io.Serializable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.indictrans.model.Agent; @Repository public interface AgentDao extends JpaRepository<Agent, Serializable> { public Agent findById(Long id); }
package com.ssi; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Demo { public static void main(String[] args) { //creating our object not taking help of IoC container //Test t=new Test(); //t.show(); //now we want spring container to create and manage objects //creating an object of IoC Container BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("spring.xml")); //ask IoC container to provide you an object. Test obj=(Test)beanFactory.getBean("testObj"); obj.show(); } }
package kr.co.magiclms.mypage.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; 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; import com.google.gson.Gson; import kr.co.magiclms.common.db.MyAppSqlConfig; import kr.co.magiclms.domain.Announcement; import kr.co.magiclms.domain.Login; import kr.co.magiclms.mapper.AnnouncementMapper; @WebServlet("/mypage/annDeleteAjax") public class DeleteAnnouncementAjaxController extends HttpServlet{ @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AnnouncementMapper mapper = MyAppSqlConfig.getSqlSession().getMapper(AnnouncementMapper.class); HttpSession session = request.getSession(); Login login = (Login)session.getAttribute("user"); int profNo = login.getProfessorNo(); Announcement announcement = new Announcement(); announcement.setProfessorNo(profNo); // announcement.setProfessorNo(20185000); announcement.setAnnNo(Integer.parseInt(request.getParameter("annNo"))); mapper.updateAnnouncementViewCnt(announcement); mapper.deleteAnnouncement(announcement); response.setContentType("application/json; charset=utf-8"); PrintWriter out = response.getWriter(); out.println(new Gson().toJson(announcement)); out.close(); // List<Announcement> annList = mapper.selectAnnouncement(profNo); // (session์—์„œ ๊ต์ˆ˜๋ฒˆํ˜ธ ๊ฐ€์ ธ์˜ค๊ธฐ) // List<Announcement> annList = mapper.selectAnnouncement(20185000); // (session์—์„œ ๊ต์ˆ˜๋ฒˆํ˜ธ ๊ฐ€์ ธ์˜ค๊ธฐ) // response.setContentType("application/json; charset=utf-8"); // PrintWriter out = response.getWriter(); // out.println(new Gson().toJson(announcement)); } }
package com.wxt.designpattern.observer.test02.order; /** * @Author: weixiaotao * @ClassName CheckAccount * @Date: 2018/11/27 10:27 * @Description: */ public class CheckAccount implements Order { private Integer checkAccountId; private Integer payId; public CheckAccount(Integer checkAccountId) { this.checkAccountId = checkAccountId; } @Override public void update(Integer payId) { this.setPayId(payId); System.out.println("mq to 105 :" + this.toString()); } public Integer getPayId() { return payId; } public void setPayId(Integer payId) { this.payId = payId; } public Integer getCheckAccountId() { return checkAccountId; } public void setCheckAccountId(Integer checkAccountId) { this.checkAccountId = checkAccountId; } @Override public String toString() { return "CheckAccount{" + "checkAccountId=" + checkAccountId + ", payId=" + payId + '}'; } }
package cn.ztuo.bitrade.service; import cn.ztuo.bitrade.component.CoinExchangeRate; import cn.ztuo.bitrade.entity.CoinThumb; import cn.ztuo.bitrade.entity.ExchangeCoin; import cn.ztuo.bitrade.entity.HuoBiTickers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import java.util.List; /** * @author: eiven * @date: 2019/6/11 19:07 */ @Service public class HuoBiTickersService { @Autowired private MongoTemplate mongoTemplate; /** * ่Žทๅ–ๆœ€ๆ–ฐ่šๅˆ่กŒๆƒ… * */ private String DETAIL_MERGED = "https://api.huobi.pro/market/detail/merged?symbol="; /** * ๅญ˜ๅ‚จ่กŒๆƒ… * @param huoBiTickers */ public void handleTickers(HuoBiTickers huoBiTickers) { Query query = new Query(); query.addCriteria(Criteria.where("symbol").is(huoBiTickers.getSymbol())); Update update = new Update(); update.set("open", huoBiTickers.getOpen()); update.set("close", huoBiTickers.getClose()); update.set("low", huoBiTickers.getLow()); update.set("high", huoBiTickers.getHigh()); update.set("amount", huoBiTickers.getAmount()); update.set("count", huoBiTickers.getCount()); update.set("vol", huoBiTickers.getVol()); mongoTemplate.upsert(query, update, HuoBiTickers.class); } /** * ่กŒๆƒ…ๅˆ—่กจๆ•ฐๆฎ */ public List<HuoBiTickers> tickers() { return mongoTemplate.findAll(HuoBiTickers.class); } }
/* * 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 exceptionprograms; /** * * @author waxxan */ public class ClassCastExceptionTest { public static void main( String[] args ) { Object o = new Object(); String s = (String)o;//ClassCastException } }
public class CounterStatic { static int counter; static{ counter = 1; } void counterInc(){ counter++; } void display(){ System.out.println("Value of counter: " + counter); } public static void main(String[] args) { // TODO Auto-generated method stub CounterStatic ob1 = new CounterStatic(); CounterStatic ob2 = new CounterStatic(); //ob1.display(); ob1.counterInc(); ob1.counterInc(); ob1.display(); ob2.display(); ob2.counterInc(); ob2.counterInc(); ob2.display(); ob1.display(); } }
package com.example.gamedb.db.dao; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import com.example.gamedb.db.entity.Screenshot; @Dao public interface ScreenshotDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(Screenshot... screenshots); @Update void update(Screenshot... screenshots); @Query("DELETE FROM Screenshot WHERE expiryDate > :date") void deleteAll(Long date); }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow 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 3 of the License, or any later version. * * * * Data Crow 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, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.wizards.item; import java.util.ArrayList; import java.util.List; import javax.swing.SwingUtilities; import net.datacrow.console.windows.ItemTypeDialog; import net.datacrow.console.windows.SelectItemDialog; import net.datacrow.console.wizards.IWizardPanel; import net.datacrow.console.wizards.Wizard; import net.datacrow.console.wizards.WizardException; import net.datacrow.core.DcRepository; import net.datacrow.core.modules.DcModules; import net.datacrow.core.objects.DcObject; import net.datacrow.core.objects.ValidationException; import net.datacrow.core.resources.DcResources; import net.datacrow.core.wf.requests.CloseWindowRequest; import net.datacrow.settings.DcSettings; import net.datacrow.util.DcSwingUtilities; public class ItemWizard extends Wizard { private DcObject dco; private DcObject container; public ItemWizard() { super(); if (!closed) { setTitle(DcResources.getText("lblItemWizard")); setHelpIndex("dc.items.wizard"); setSize(DcSettings.getDimension(DcRepository.Settings.stItemWizardFormSize)); setCenteredLocation(); } } @Override protected void initialize() { if (getModule().isAbstract()) { ItemTypeDialog dialog = new ItemTypeDialog(DcResources.getText("lblSelectModuleHelp")); dialog.setVisible(true); if (dialog.getSelectedModule() < 0) { closed = true; close(); } else { moduleIdx = DcModules.get(dialog.getSelectedModule()).getIndex(); } } if (getModule().getIndex() == DcModules._ITEM && DcModules.get(DcSettings.getInt(DcRepository.Settings.stModule)).getIndex() == DcModules._CONTAINER) { SelectItemDialog dlg = new SelectItemDialog(DcModules.get(DcModules._CONTAINER), "Select a container"); dlg.setVisible(true); container = dlg.getItem(); } if (getModule() != null) dco = getModule().getItem(); } @Override protected List<IWizardPanel> getWizardPanels() { List<IWizardPanel> panels = new ArrayList<IWizardPanel>(); if (getModule().deliversOnlineService()) panels.add(new InternetWizardPanel(this, getModule())); panels.add(new ItemDetailsWizardPanel(dco)); return panels; } @Override public void setVisible(boolean b) { super.setVisible(b && !closed); if (!closed && b && getCurrent() instanceof InternetWizardPanel) ((InternetWizardPanel) getCurrent()).setFocus(); } @Override protected void saveSettings() { DcSettings.set(DcRepository.Settings.stItemWizardFormSize, getSize()); } @Override public void finish() throws WizardException { dco = (DcObject) getCurrent().apply(); dco.addRequest(new CloseWindowRequest(this)); try { dco.saveNew(true); } catch (ValidationException ve) { throw new WizardException(ve.getMessage()); } } @Override public void next() { new Thread( new Runnable() { @Override public void run() { try { dco = (DcObject) getCurrent().apply(); if (container != null && dco.getModule().isContainerManaged()) dco.setValue(DcObject._SYS_CONTAINER, container); SwingUtilities.invokeLater( new Thread(new Runnable() { @Override public void run() { current += 1; if (current <= getStepCount()) { ItemWizardPanel panel; for (int i = 0; i < getStepCount(); i++) { panel = (ItemWizardPanel) getWizardPanel(i); panel.setObject(dco); panel.setVisible(i == current); } } else { current -= 1; } applyPanel(); } })); } catch (WizardException wzexp) { if (wzexp.getMessage().length() > 1) DcSwingUtilities.displayWarningMessage(wzexp.getMessage()); } } }).start(); } @Override public void close() { dco = null; super.close(); } @Override protected String getWizardName() { return DcResources.getText("msgNewItemWizard", new String[] {dco.getModule().getObjectName(), String.valueOf(current + 1), String.valueOf(getStepCount())}); } @Override protected void restart() { try { finish(); saveSettings(); ItemWizard wizard = new ItemWizard(); wizard.setVisible(true); } catch (WizardException exp) { DcSwingUtilities.displayWarningMessage(exp.getMessage()); } } }
package com.team3.bra; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.Collections; import java.util.Vector; /** * This class is for an object representing an item Category. * */ public class Category implements Comparable<Category> { protected static ArrayList<Category> categories = new ArrayList<>(); private int id; private String name; private float vat; private String description; private boolean food; private ArrayList<Item> items = new ArrayList<Item>(); /** * The constructor of the Category object. It reads a vector that was * returned from JDBC in order to construct the object as it is on the * database. * * @param vec * a vector that is returned from JDBC */ public Category(Vector<Object> vec) { this.id = (int) vec.get(0); this.name = (String) vec.get(1); this.vat = Float.parseFloat(vec.get(2).toString()); this.description = (String) vec.get(3); this.food = (boolean) vec.get(4); } /** * Getter for the Category id. * * @return the Category id. */ public int getId() { return id; } /** * Getter for the Category name. * * @return the Category name. */ public String getName() { return name; } /** * Getter for the list of items in the category. * * @return the list of items in the category. */ public ArrayList<Item> getItems() { return items; } /** * Getter for the VAT of the Category. * * @return the VAT of the Category. */ public float getVat() { return vat; } /** * Getter for the description of the Category. * @return the description of the Category. */ public String getDescription() { return description; } /** * Finds all the categories of the DB using a JDBC call and stores them in a * static arraylist. */ public static void findCategories() { categories = new ArrayList<Category>(); String a[] = { "0" }; Vector<Vector<Object>> vec = JDBC.callProcedure("FindCategory", a); for (int i = 0; i < vec.size(); i++) { Category c = new Category(vec.get(i)); categories.add(c); } } /** * Fills the current order with items using a JDBC call. */ public void fillCategory() { this.items = new ArrayList<Item>(); String a[] = { "-1", this.getId() + "" }; Vector<Vector<Object>> vec = JDBC.callProcedure("FindItem", a); for (int i = 0; i < vec.size(); i++) { this.items.add(new Item(vec.get(i))); } } /** * Returns if the category is food. * * @return if the category is food. */ public int isFood() { if (food == true) return 1; return 0; } @Override public String toString() { return this.name; } @Override public int compareTo(@NonNull Category category) { return this.name.compareTo(category.name); } }
package com.lenovohit.ssm.treat.manager.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.lenovohit.ssm.treat.dao.FrontendRestDao; import com.lenovohit.ssm.treat.manager.HisOutpatientManager; import com.lenovohit.ssm.treat.model.MedicalRecord; import com.lenovohit.ssm.treat.model.Patient; public class HisOutpatientManagerImpl implements HisOutpatientManager{ @Autowired private FrontendRestDao frontendRestDao; @Override public List<MedicalRecord> getMedicalRecordPage(Patient patient) { List<MedicalRecord> medicalRecord = frontendRestDao.getForList("outpatient/medicalRecord/page", MedicalRecord.class); return medicalRecord; } @Override public List<MedicalRecord> getMedicalRecord(String id) { List<MedicalRecord> medicalDetail = frontendRestDao.getForList("outpatient/medicalRecord/"+id, MedicalRecord.class); return medicalDetail; } @Override public MedicalRecord medicalRecordPrint(MedicalRecord record) { return null; } }
package ์—ฐ์Šต์žฅ; import java.util.Arrays; import java.util.Random; public class ์ด์ค‘๋ฐฐ์—ด { public static void main(String[] args) { int arr[][] = new int[5][5]; Random r = new Random(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { int randNum = r.nextInt(100); arr[i][j] = randNum; } System.out.println(Arrays.toString(arr[i])); } } }
package com.brainacad.oop.diplom; /** * Created by ะะดะผะธะฝะธัั‚ั€ะฐั‚ะพั€ on 31.01.2016. */ public class GradeBook { private Integer rating; }
package MinMax; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MinMaxCiclomatica { private MinMax mima; @Before //se aplica antes de cada test (creacion minmax) public void setUp(){ MinMax mima = new MinMax(); } @After //se aplica despues de cada test(eliminacion minmax) public void tearDown(){ mima=null; } @Test public void camino1() { int Datos[]=null; assertEquals(null, mima.minMax(Datos)); } @Test public void camino2() { //no se puede implementar //porque pasa por el primer if pero no termina el bucle } @Test public void camino3() { int Datos[]={1,2,3}; assertEquals(1, mima.minMax(Datos)[0]); assertEquals(3, mima.minMax(Datos)[1]); } @Test public void camino4(){ int Datos[]={3,2,1}; assertEquals(1, mima.minMax(Datos)[0]); assertEquals(3, mima.minMax(Datos)[1]); } @Test public void camino5() { int Datos[]={1,1,1}; assertEquals(1, mima.minMax(Datos)[0]); assertEquals(1, mima.minMax(Datos)[1]); } }
package seedu.project.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.project.model.Model.PREDICATE_SHOW_ALL_PROJECTS; import static seedu.project.model.Model.PREDICATE_SHOW_ALL_TASKS; import seedu.project.logic.CommandHistory; import seedu.project.logic.LogicManager; import seedu.project.model.Model; /** * Lists all tasks in the project to the user. */ public class ListCommand extends Command { public static final String COMMAND_WORD = "list"; public static final String COMMAND_ALIAS = "l"; public static final String MESSAGE_SUCCESS_PROJECT = "Listed all projects"; public static final String MESSAGE_SUCCESS_TASK = "Listed all tasks"; @Override public CommandResult execute(Model model, CommandHistory history) { requireNonNull(model); if (!LogicManager.getState()) { model.updateFilteredProjectList(PREDICATE_SHOW_ALL_PROJECTS); return new CommandResult(MESSAGE_SUCCESS_PROJECT); } else { model.updateFilteredTaskList(PREDICATE_SHOW_ALL_TASKS); return new CommandResult(MESSAGE_SUCCESS_TASK); } } }
/** * */ package com.sirma.itt.javacourse.networkingAndGui.task1.calculator; import static org.junit.Assert.*; import java.awt.event.ActionEvent; import javax.swing.JTextField; import org.junit.Before; import org.junit.Test; import com.sirma.itt.javacourse.desingpatterns.task7.calculator.commands.AddCommand; import com.sirma.itt.javacourse.desingpatterns.task7.calculator.commands.Command; import com.sirma.itt.javacourse.networkingAndGui.task1.calculatorGui.listeners.OperationListener; /** * @author siliev * */ public class TestOperationListener { private OperationListener listener; private JTextField textFiled; private Command command; private String firstNumber; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { textFiled = new JTextField("5+6"); command = new AddCommand(); firstNumber = "5"; listener = new OperationListener(textFiled, command, firstNumber); } /** * Test method for * {@link com.sirma.itt.javacourse.networkingAndGui.task1.calculatorGui.listeners.OperationListener#actionPerformed(java.awt.event.ActionEvent)} * . */ @Test public void testActionPerformed() { listener.actionPerformed(new ActionEvent(textFiled, 0, "+")); assertTrue(textFiled.getText().contains("11.0")); } }
package mc.kurunegala.bop.model; import org.springframework.web.multipart.MultipartFile; public class UploadWrapper { private MultipartFile fileData; private NeedDoc needDoc; private String bopNo; public MultipartFile getFileData() { return fileData; } public void setFileData(MultipartFile fileData) { this.fileData = fileData; } public NeedDoc getNeedDoc() { return needDoc; } public void setNeedDoc(NeedDoc needDoc) { this.needDoc = needDoc; } public String getBopNo() { return bopNo; } public void setBopNo(String bopNo) { this.bopNo = bopNo; } }
package biz.dreamaker.workreport.account.domain; import java.util.Arrays; import java.util.NoSuchElementException; import lombok.Getter; @Getter public enum UserRole { USER("ROLE_USER"), PERSONAL("ROLE_PERSONAL"), COMPANY("ROLE_COMPANY"); private String roleName; UserRole(String roleName) { this.roleName = roleName; } public static UserRole getRoleByName(String roleName) { return Arrays.stream(UserRole.values()) .filter(r -> r.isCorrectName(roleName)).findFirst() .orElseThrow(() -> new NoSuchElementException("๊ฒ€์ƒ‰๋œ ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค.")); } private boolean isCorrectName(String roleName) { return roleName.equalsIgnoreCase(this.roleName); } }
package io.ceph.rgw.client.model; /** * Created by zhuangshuo on 2020/3/17. */ public class GetBucketLocationResponse implements BucketResponse { private final String location; public GetBucketLocationResponse(String location) { this.location = location; } public String getLocation() { return location; } @Override public String toString() { return "GetBucketLocationResponse{" + "location='" + location + '\'' + '}'; } }
package de.dotwee.rgb.canteen.presenter; import android.support.annotation.Nullable; import de.dotwee.rgb.canteen.model.api.specs.Item; /** * Created by lukas on 09.02.17. */ public interface IngredientsPresenter { String TAG = IngredientsPresenter.class.getSimpleName(); void onItemChange(@Nullable Item item); }
package com.algorithm.trie; import java.util.TreeMap; public class Trie { private class Node { //ๆ˜ฏๅฆๆ˜ฏไธ€ไธชๅ•่ฏ private boolean isWord; //ๅญ—ๅ…ธๆ ‘ไธญ๏ผŒไธ€ไธช่Š‚็‚นๅฏนๅบ”ๅคšไธช่Š‚็‚น private TreeMap<Character, Node> next; public Node(boolean isWord) { this.isWord = isWord; next = new TreeMap<Character, Node>(); } //ๅคง้ƒจๅˆ†่Š‚็‚น public Node() { this(false); } } private Node root; private int size; public Trie() { root = new Node(); size = 0; } //่Žทๅ–ๅญ—ๅ…ธๆ ‘ไธญ็š„ๅ•่ฏๆ•ฐ้‡ public int getSize() { return size; } //ๅพ€trieๆ ‘ไธญๆทปๅŠ ไธ€ไธชๅ•่ฏ,้ž้€’ๅฝ’ๅ†™ๆณ• public void add(String word) { Node cur = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (cur.next.get(c) == null) { cur.next.put(c, new Node()); } cur = cur.next.get(c); } if (!cur.isWord) { cur.isWord = true; size++; } } //ๆŸฅ่ฏขtrieๆ ‘ไธญๆ˜ฏๅฆๅŒ…ๅซๅ•่ฏword public boolean contains(String word){ Node cur = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if(cur.next.get(c) != null){ cur = cur.next.get(c); }else { return false; } } return cur.isWord; } //ๆŸฅ็œ‹ๅ•่ฏๆ˜ฏๅฆๆ˜ฏtrieๆ ‘ไธญ็š„ๅ‰็ผ€ public boolean isPrefix(String word){ Node cur = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if(cur.next.get(c) == null){ return false; }else { cur = cur.next.get(c); } } return true; } public static void main(String[] args) { Trie trie = new Trie(); trie.add("Hello"); trie.add("Help"); trie.contains("Help"); System.out.println(trie.toString()); } }
package com.egreat.adlauncher.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import android.R; import android.content.Context; import android.content.SharedPreferences; import android.provider.Settings; import android.util.Log; public class SettingUtils { public static Boolean getApp01DefaultValue(Context mContext) { SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); return mSharedPreferences.getBoolean("default_add_1", true); } public static Boolean getApp02DefaultValue(Context mContext) { SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); return mSharedPreferences.getBoolean("default_add_2", true); } public static void setApp01DefaultValue(Context mContext, boolean defaultAdd) { SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); mSharedPreferences.edit().putBoolean("default_add_1", defaultAdd).commit(); } public static void setApp02DefaultValue(Context mContext, boolean defaultAdd) { SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); mSharedPreferences.edit().putBoolean("default_add_2", defaultAdd).commit(); } public static String getApp01PackageName(Context mContext) { String ret = ""; SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); ret = mSharedPreferences.getString("app_01", ""); return ret; } public static void setApp01PackageName(Context mContext, String name) { SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); mSharedPreferences.edit().putString("app_01", name).commit(); } public static String getApp02PackageName(Context mContext) { String ret = ""; SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); ret = mSharedPreferences.getString("app_02", ""); return ret; } public static void setApp02PackageName(Context mContext, String name) { SharedPreferences mSharedPreferences = mContext.getSharedPreferences("Config", Context.MODE_PRIVATE); mSharedPreferences.edit().putString("app_02", name).commit(); } }
package com.just4fun.service; import com.just4fun.dao.UserDao; /** * Created by sdt14096 on 2017/4/13. */ public class UserServiceImpl implements UserService{ private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void addUser(String user) { userDao.add(user); } }
package Marble; import java.util.Arrays; class Player { static int cnt=0; // ํ”Œ๋ ˆ์ด์–ด ์ˆ˜ String name; int balance; int loc; Player(){ this.name=Integer.toString(++cnt); this.balance=5000; this.loc=0; } } class City { String name; String owner; int price; String[] room; City(String n){ this.name=n; this.owner="empty"; this.price=300; this.room=new String[Player.cnt]; Arrays.fill(room,""); } } class Game { City[] city; int dice; static int pay=0; String[] cityname = {"START","Seoul","Tokyo","Sydney","LA","Cairo","Phuket","New delhi","Hanoi","Paris"}; Game() { this.city=new City[10]; this.dice=0; } void cityinput(){ for(int i=0; i<10; i++) city[i] = new City(cityname[i]); this.city[0].owner="None"; } void move(Player p){ for (int i=0;i<2;i++) // ์ฃผ์‚ฌ์œ„๋ฅผ ๊ตด๋ ค ์ด๋™ํ•˜๋ฏ€๋กค city์— ์žˆ๋Š”๊ฑฐ ์ œ๊ฑฐ if (city[p.loc].room[i].equals(p.name)) city[p.loc].room[i]=""; dice=(int)(Math.random()*6+1); // 1~6๊นŒ์ง€์˜ ์ˆ˜ ๋žœ๋ค System.out.println("Player "+p.name+" got "+dice); p.loc+=dice; if (p.loc>=10) p.loc-=10; System.out.println(city[p.loc].name+"("+city[p.loc].owner+")"); for (int i=0;i<2;i++) if (city[p.loc].room[i].equals("")) { city[p.loc].room[i] = p.name; break; } } void bulid(Player p) { if (pay!=0) { p.balance += pay; pay=0; } if (city[p.loc].owner.equals("empty")) { if (p.balance>=300) { city[p.loc].owner = p.name; System.out.println("Player "+p.name+" buys "+city[p.loc].name); p.balance-=city[p.loc].price; System.out.println("Player "+p.name+"'s balance is "+p.balance); } else { System.out.println("Can't buy "+city[p.loc].name); System.out.println("Player "+p.name+"'s balance is "+p.balance); } } else if (city[p.loc].owner.equals(p.name)) System.out.println("Player "+p.name+"'s balance is "+p.balance); else if (city[p.loc].owner.equals("None")) System.out.println("Player "+p.name+"'s balance is "+p.balance); else { // ๋‚ด ๋•…์ด ์•„๋‹ˆ๋ฉด ํ†ตํ–‰๋ฃŒ ์ง€๋ถˆ toll(p); } } void toll(Player p){ System.out.println("LUCKY! Opponent get 600 MONEY!!"); p.balance-=600; pay=600; if (p.balance<0) { System.out.println("Player "+p.name+" bankruptcy!"); System.out.println("GAME OVER"); System.exit(0); } else System.out.println("Player "+p.name+"'s balance is "+p.balance); } } public class Marble { public static void main(String[] args) { Player p1 = new Player(); Player p2 = new Player(); Game g = new Game(); g.cityinput(); int turn = 30; for (int i=0;i<turn;i++) { for (int j=0;j<15;j++) System.out.print("-"); System.out.print("Turn "+(i+1)); for (int j=0;j<15;j++) System.out.print("-"); System.out.println(); g.move(p1); g.bulid(p1); System.out.println(); g.move(p2); g.bulid(p2); System.out.println(); } if (p1.balance>p2.balance) System.out.println("Winner is Player 1!"); else if (p1.balance<p2.balance) System.out.println("Winner is Player 2!"); else System.out.println("DRAW"); System.out.println("GAME OVER"); } }
//Java Program to find the sum of each row and each column of a matrix import java.util.Scanner; public class q34 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; n = sc.nextInt(); int a[][] = new int[n][n]; System.out.println("Enter the elements of matrix A"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } int r = 0; int c = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { r += a[i][j]; c += a[j][i]; } System.out.println("Sum of row " + i + " is " + r); System.out.println("Sum of column " + i + " is " + c); r=0; c=0; } sc.close(); } }
package com.examples.io.designpatterns.di; /** * The 4 roles in dependency injection * If you want to use this technique, you need classes that fulfill four basic roles. These are: * * The service you want to use. * The client that uses the service. * An interface thatโ€™s used by the client and implemented by the service. * The injector which creates a service instance and injects it into the client. * * https://www.codejava.net/coding/what-is-dependency-injection-with-java-code-example */ public class Injector { public static void main(String[] args) { Area area = new CircleArea(); Shape shape = new Circle(area); shape.draw(); } }
package net.sduhsd.royr6099.unit7; //ยฉ A+ Computer Science - www.apluscompsci.com //Name - //Date - //Class - //Lab - import static java.lang.System.*; public class TriangleThree { private int size; private String letter; public TriangleThree() { setTriangle("#", 3); } public TriangleThree(int count, String let) { setTriangle(let, count); } public void setTriangle(String let, int sz) { letter = let; size = sz; } public String getLetter() { return "#"; } public String toString() { String output = ""; for (int i = 1; i <= size; i++) { for (int j = size - 1; j >= i; j--) { output += " "; } for (int j = i - 1; j >= 0; j--) { output += letter; } output += "\n"; } return output + "\n"; } }
package com.igs.qhrzlc.view.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.igs.qhrzlc.utils.IntentUtils; import com.igs.qhrzlc.utils.view.RoundProgressBar; import com.igs.qhrzlc.view.activity.CaoPanListActivity; import com.igs.qhrzlc.view.activity.MainActivity; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import qhrzzx.igs.com.igs_mvp.R; /** * @author heliang * @version V1.0 * @Description: ไธป้กตfragment * @Date 2015-5-25 ไธŠๅˆ10:59:19 */ public class HomeFragment extends BaseFragment { @InjectView(R.id.roundProgressBar2) RoundProgressBar roundProgressBar2; @InjectView(R.id.ll_home_rq) LinearLayout llHomeRq; @InjectView(R.id.ll_home_cs) LinearLayout llHomeCs; @InjectView(R.id.ll_home_wj) LinearLayout llHomeWj; @InjectView(R.id.ll_more) LinearLayout ll_more; private View layout; int progress = 0; public static final String KEY_CAO_PAN_TYPE = "CAO_PAN_TYPE"; public static final String CAO_PAN_TYPE_RQ = "1"; public static final String CAO_PAN_TYPE_CS = "2"; public static final String CAO_PAN_TYPE_WJ = "3"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ButterKnife.inject(this, initLayout(inflater, container)); View view = initLayout(inflater, container); roundProgressBar2 = (RoundProgressBar) view.findViewById(R.id.roundProgressBar2); roundProgressBar2.setProgress(87); return view; } private View initLayout(LayoutInflater inflater, ViewGroup container) { layout = inflater.inflate(R.layout.fragment_home, container, false); ButterKnife.inject(this, layout); return layout; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.reset(this); } @OnClick({R.id.ll_home_rq, R.id.ll_home_wj, R.id.ll_home_cs,R.id.ll_more}) public void onclick(View view) { switch (view.getId()) { case R.id.ll_home_rq: IntentUtils.goIntent(getActivity(), CaoPanListActivity.class,KEY_CAO_PAN_TYPE,CAO_PAN_TYPE_RQ); break; case R.id.ll_home_wj: IntentUtils.goIntent(getActivity(), CaoPanListActivity.class,KEY_CAO_PAN_TYPE,CAO_PAN_TYPE_WJ); break; case R.id.ll_home_cs: IntentUtils.goIntent(getActivity(), CaoPanListActivity.class,KEY_CAO_PAN_TYPE,CAO_PAN_TYPE_CS); break; case R.id.ll_more: IntentUtils.goIntent(getActivity(), MainActivity.class,MainActivity.KEY_SEL_FRAGMENT,MainActivity.SEL_ORDER); break; } } }