text
stringlengths
10
2.72M
package com.wmc.aofstudymap; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.GestureDetectorCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.GestureDetector; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; public class SinArticleActivity extends AppCompatActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { private final String TAG = SinArticleActivity.class.getSimpleName(); private GestureDetectorCompat mDetector; ImageButton mPreviousButton; ImageButton mNextButton; ImageButton mReplayButton; ImageButton mPlayPauseButton; ImageButton mHomeButton; ImageButton mMoreInfoButton; ImageView mSinImageView; boolean isPaused; boolean mBound; MediaPlayer mPlayer; TextView mCaptionTextView; final Handler menu_handler = new Handler(); boolean buttons_visible = false; private void hideButtons() { buttons_visible = false; Animation animation = AnimationUtils.loadAnimation(this, R.anim.hide_buttons); animation.reset(); mHomeButton.startAnimation(animation); mHomeButton.setVisibility(View.INVISIBLE); mPlayPauseButton.startAnimation(animation); mPlayPauseButton.setVisibility(View.INVISIBLE); mReplayButton.startAnimation(animation); mReplayButton.setVisibility(View.INVISIBLE); mNextButton.startAnimation(animation); mNextButton.setVisibility(View.INVISIBLE); mPreviousButton.startAnimation(animation); mPreviousButton.setVisibility(View.INVISIBLE); mMoreInfoButton.startAnimation(animation); mMoreInfoButton.setVisibility(View.INVISIBLE); } private void displayButtons() { buttons_visible = true; Animation animation = AnimationUtils.loadAnimation(this, R.anim.show_buttons); animation.reset(); mHomeButton.clearAnimation(); mHomeButton.startAnimation(animation); mHomeButton.setVisibility(View.VISIBLE); mPlayPauseButton.clearAnimation(); mPlayPauseButton.startAnimation(animation); mPlayPauseButton.setVisibility(View.VISIBLE); mReplayButton.clearAnimation(); mReplayButton.startAnimation(animation); mReplayButton.setVisibility(View.VISIBLE); mNextButton.clearAnimation(); mNextButton.startAnimation(animation); mNextButton.setVisibility(View.VISIBLE); mPreviousButton.clearAnimation(); mPreviousButton.startAnimation(animation); mPreviousButton.setVisibility(View.VISIBLE); mMoreInfoButton.clearAnimation(); mMoreInfoButton.startAnimation(animation); mMoreInfoButton.setVisibility(View.VISIBLE); } Runnable button_hide_thread = new Runnable() { public void run() { hideButtons(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sin_article); try { mSinImageView = (ImageView) findViewById(R.id.sinImageView); mDetector = new GestureDetectorCompat(this, this); mDetector.setOnDoubleTapListener(this); // More Info Button mMoreInfoButton = (ImageButton) findViewById(R.id.btnMoreInfo); mMoreInfoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // TODO Transfer this to an XML file AlertDialog.Builder builder = new AlertDialog.Builder(SinArticleActivity.this); TextView title = new TextView(SinArticleActivity.this); title.setText("V. Sin, Original and Personal"); title.setBackgroundColor(Color.DKGRAY); title.setPadding(10, 10, 10, 10); title.setGravity(Gravity.CENTER); title.setTextColor(Color.WHITE); title.setTextSize(20); builder.setCustomTitle(title); TextView message = new TextView(SinArticleActivity.this); message.setText(R.string.sinInfo); message.setVerticalScrollBarEnabled(true); message.setMovementMethod(ScrollingMovementMethod.getInstance()); message.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET); message.setPadding(5, 15, 5, 15); message.setGravity(Gravity.CENTER_HORIZONTAL); builder.setView(message); builder.setCancelable(true); AlertDialog alertDialog = builder.create(); alertDialog.show(); if (mPlayer.isPlaying() && !isPaused) { mPlayer.pause(); isPaused = true; mPlayPauseButton.setImageResource(R.drawable.ic_play_arrow_black_36dp); } alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { try { mPlayer.start(); isPaused = false; mPlayPauseButton.setImageResource(R.drawable.ic_pause_black_36dp); } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } }); mMoreInfoButton.setVisibility(View.INVISIBLE); // Home Button mHomeButton = (ImageButton) findViewById(R.id.btnHome); mHomeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SinArticleActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); mHomeButton.setVisibility(View.INVISIBLE); // Play Button mPlayPauseButton = (ImageButton) findViewById(R.id.btnPlay); mPlayPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if (mPlayer.isPlaying() && !isPaused) { mPlayer.pause(); isPaused = true; mPlayPauseButton.setImageResource(R.drawable.ic_play_arrow_black_36dp); } else { mPlayer.start(); isPaused = false; mPlayPauseButton.setImageResource(R.drawable.ic_pause_black_36dp); } } catch (Exception e) { e.printStackTrace(); } } }); mPlayPauseButton.setVisibility(View.INVISIBLE); // Replay Button mReplayButton = (ImageButton) findViewById(R.id.btnReplay); mReplayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Log.v(TAG, "Player is currently playing: " + mPlayer.isPlaying()); mPlayPauseButton.setImageResource(R.drawable.ic_pause_black_36dp); mPlayer.stop(); mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sin); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mPlayer.stop(); mPlayPauseButton.setImageResource(R.drawable.ic_play_arrow_black_36dp); } }); mPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } }); mReplayButton.setVisibility(View.INVISIBLE); mCaptionTextView = (TextView) findViewById(R.id.txtViewSinArticleContent); mCaptionTextView.setMovementMethod(new ScrollingMovementMethod()); mPreviousButton = (ImageButton) findViewById(R.id.btnLeftArrow); mPreviousButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), ArticleFiveToTenActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }); mPreviousButton.setVisibility(View.INVISIBLE); mNextButton = (ImageButton) findViewById(R.id.btnRightArrow); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), AtonementArticleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); mNextButton.setVisibility(View.INVISIBLE); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onTouchEvent(MotionEvent event) { this.mDetector.onTouchEvent(event); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_sin_article, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPause() { super.onPause(); try { mPlayer.stop(); mPlayer.release(); if(AppUtility.isApplicationSentToBackground(getApplicationContext())) { AppController.getInstance().stopService(getApplicationContext()); mBound = false; } Log.v(TAG, "onPause: Service running? " + AppUtility.isMyServiceRunning(BackgroundMusicService.class, getApplicationContext()) + " Bound: " + mBound + " isFinishing: " + isFinishing() + " this.isFinishing: " + this.isFinishing() + " Sent to background: " + AppUtility.isApplicationSentToBackground(getApplicationContext())); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); try { Animation fade = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade); mSinImageView.startAnimation(fade); mPlayer = MediaPlayer.create(this, R.raw.sin); mPlayer.setVolume(1.0f, 1.0f); mPlayer.start(); isPaused = false; mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { try { mPlayPauseButton.setImageResource(R.drawable.ic_play_arrow_black_36dp); } catch (Exception e) { e.printStackTrace(); } } }); mPlayPauseButton.setImageResource(R.drawable.ic_pause_black_36dp); if (!mBound) { AppController.getInstance().startService(getApplicationContext()); mBound = true; } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { try { if (this.isFinishing() || isFinishing()) { if(mPlayer != null) mPlayer.release(); mBound = false; } Log.v(TAG, "onDestroy: Service running? " + AppUtility.isMyServiceRunning(BackgroundMusicService.class, getApplicationContext()) + " Bound: " + mBound + " isFinishing: " + isFinishing() + " this.isFinishing: " + this.isFinishing() + " Sent to background: " + AppUtility.isApplicationSentToBackground(getApplicationContext())); } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } @Override protected void onStop() { super.onStop(); try { if(this.isFinishing() || isFinishing()) { mBound = false; if(mPlayer != null) mPlayer.release(); } if(AppUtility.isApplicationSentToBackground(getApplicationContext())) { AppController.getInstance().stopService(getApplicationContext()); mBound = false; } Log.v(TAG, "onStop: Service running? " + AppUtility.isMyServiceRunning(BackgroundMusicService.class, getApplicationContext()) + " Bound: " + mBound + " isFinishing: " + isFinishing() + " this.isFinishing: " + this.isFinishing() + " Sent to background: " + AppUtility.isApplicationSentToBackground(getApplicationContext())); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onSingleTapConfirmed(MotionEvent e) { Log.d(TAG, "onSingleTapUp: " + e.toString()); return true; } @Override public boolean onDoubleTap(MotionEvent e) { Intent intent = new Intent(getApplicationContext(), AllArticlesActivity.class); startActivity(intent); Log.d(TAG, "onDoubleTap: " + e.toString()); return true; } @Override public boolean onDoubleTapEvent(MotionEvent e) { Log.d(TAG, "onDoubleTapEvent: " + e.toString()); return true; } @Override public boolean onDown(MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_DOWN) { if (!buttons_visible) displayButtons(); menu_handler.postDelayed(button_hide_thread, 5000); } else { menu_handler.removeCallbacks(button_hide_thread); menu_handler.postDelayed(button_hide_thread, 5000); } Log.d(TAG, "onDown: " + e.toString()); return true; } @Override public void onShowPress(MotionEvent e) { Log.d(TAG, "onShowPress: " + e.toString()); } @Override public boolean onSingleTapUp(MotionEvent e) { Log.d(TAG, "onSingleTapUp: " + e.toString()); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Log.d(TAG, "onScroll: " + e1.toString() + e2.toString()); return true; } @Override public void onLongPress(MotionEvent e) { Log.d(TAG, "onLongPress: " + e.toString()); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "onFling: " + e1.toString() + e2.toString()); return true; } }
package com.service.processor; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.service.cache.CacheManager; import com.service.db.dao.DaoWrapper; @Service public class CommonProcessorImpl implements ICommonProcessor{ @Autowired CacheManager cachemanager; @Autowired DaoWrapper dao; public Object processGetCountryByCode(String code) { return cachemanager.getCountryDataByCode(code); } @Override public List<Map<String,Object>> noOfAirportsPerCountry(Map<String, String> criteriaMap){ return dao.noOfAirportsPerCountry(criteriaMap); } @Override public List<Map<String,Object>> processRequestForQuery(String entity, Map<String, String> criteriaMap) { List<Map<String,Object>> list=null; if(entity.equals("country")) { list= dao.processCustomObjectByCriteria(entity, criteriaMap); } return list; } @Override public List<Map<String,Object>> topCommonUncommonRunwayAttribute(Map<String, String> criteriaMap){ List<Map<String,Object>> list=null; list= dao.topCommonUncommonRunwayAttribute(criteriaMap); return list; } @Override public List<Map<String,Object>> getRunwayTypesPerCountry(String country){ List<Map<String,Object>> list=null; list= dao.getRunwayTypesPerCountry(country); return list; } }
/** * Copyright 2013-present febit.org (support@febit.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.febit.web.component; import org.febit.lang.ConcurrentIdentityMap; import org.febit.util.ClassUtil; import org.febit.util.Petite; import org.febit.web.ActionRequest; import org.febit.web.meta.RenderWith; import org.febit.web.render.Render; import org.febit.web.util.MatchTypes; /** * * @author zqq90 */ @SuppressWarnings("unchecked") public class RenderManager implements Component { protected final ConcurrentIdentityMap<Class, Render> renderCache; protected Render[] renders; protected Render defaultRender; protected Petite petite; public RenderManager() { this.renderCache = new ConcurrentIdentityMap<>(); } @Petite.Init public void init() { if (renders != null) { for (Render render : renders) { if (render instanceof MatchTypes) { for (Class type : ((MatchTypes) render).matchTypes()) { renderCache.put(type, render); } } renderCache.put(render.getClass(), render); } } } protected Render resolveRender(final ActionRequest actionRequest, final Object result) { Render render = null; for (Class<?> type : ClassUtil.impls(result.getClass())) { render = renderCache.get(type); if (render != null) { break; } RenderWith anno = type.getAnnotation(RenderWith.class); if (anno != null) { Class renderClass = anno.value(); render = renderCache.get(renderClass); if (render != null) { break; } render = (Render) petite.get(renderClass); if (render != null) { render = renderCache.putIfAbsent(renderClass, render); break; } } } if (render == null) { render = defaultRender; } return renderCache.putIfAbsent(result.getClass(), render); } public void render(final ActionRequest actionRequest, Object result) throws Exception { if (result != null) { int count = 0; do { count++; Render render = renderCache.get(result.getClass()); if (render == null) { render = resolveRender(actionRequest, result); } result = render.render(actionRequest, result); } while (result != null && count < 100); } else { defaultRender.render(actionRequest, result); } } }
/* * FileName: ExcelComponent.java * Description: Excel单元对象 * Company: 南宁超创信息工程有限公司 * Copyright: ChaoChuang (c) 2005 * History: 2005-6-6 (LLM) 1.0 Create */ package com.spower.basesystem.excel.command; import jxl.write.WritableCellFormat; /** * The <code>ExcelNode</code> class * Excel单元对象 * @author LLM * @version 1.0, 2005-6-6 */ public class ExcelNode { /** 单元格的类型为字符 */ public static final String CELL_STRING = "string"; /** 单元格的类型为数值 */ public static final String CELL_NUMBER = "number"; /** 单元格的内容 */ private String cellContent; /** 单元格的类型 */ private String cellType; /** 单元格的合并范围 */ private MergeRange mergeRange; /** 单元格的格式 **/ private WritableCellFormat cellFormat; /**空构造类 */ public ExcelNode() { // TODO Auto-generated method stub } /** * 带有单元内容和单元类型的构造函数 * @param cellContent 单元内容 * @param cellType 单元类型 */ public ExcelNode(String cellContent, String cellType) { this.cellContent = cellContent; this.cellType = cellType; } /** * 只有单元内容的构造函数(单元类型默认为字符) * @param cellContent 单元内容 */ public ExcelNode(String cellContent) { this.cellContent = cellContent; this.cellType = CELL_STRING; } /** * 带有单元内容和单元合并范围的构造函数 * @param cellContent 单元内容 * @param mergeRange 单元合并范围 */ public ExcelNode(String cellContent, MergeRange mergeRange) { this.cellContent = cellContent; this.mergeRange = mergeRange; this.cellType = CELL_STRING; } /** 带有单元内容和格式的构造函数 * @param cellContent 单元内容 * @param cellFormat 格式 */ public ExcelNode(String cellContent, WritableCellFormat cellFormat) { this.cellContent = cellContent; this.cellFormat = cellFormat; this.cellType = CELL_STRING; } /** 带有单元内容和格式的构造函数 * @param cellContent 单元内容 * @param cellType 类型 * @param cellFormat 格式 */ public ExcelNode(String cellContent, String cellType, WritableCellFormat cellFormat) { this.cellContent = cellContent; this.cellFormat = cellFormat; this.cellType = cellType; } /**带有单元内容和单元合并范围以及格式的构造函数 * @param cellContent 单元内容 * @param mergeRange 单元合并范围 * @param cellFormat 格式 */ public ExcelNode(String cellContent, MergeRange mergeRange, WritableCellFormat cellFormat) { this.cellContent = cellContent; this.mergeRange = mergeRange; this.cellFormat = cellFormat; this.cellType = CELL_STRING; } /**带有单元内容和单元合并范围以及格式的构造函数 * @param cellContent 单元内容 * @param cellType 单元类型 * @param mergeRange 单元合并范围 * @param cellFormat 格式 */ public ExcelNode(String cellContent, String cellType, MergeRange mergeRange, WritableCellFormat cellFormat) { this.cellContent = cellContent; this.mergeRange = mergeRange; this.cellFormat = cellFormat; this.cellType = cellType; } /** * 带有单元内容,单元类型和单元合并范围的构造函数 * @param cellContent 单元内容 * @param cellType 单元类型 * @param mergeRange 单元合并范围 */ public ExcelNode(String cellContent, String cellType, MergeRange mergeRange) { this.cellContent = cellContent; this.cellType = cellType; this.mergeRange = mergeRange; } /** * @return Returns the mergeRange. */ public MergeRange getMergeRange() { return mergeRange; } /** * @param mergeRange The mergeRange to set. */ public void setMergeRange(MergeRange mergeRange) { this.mergeRange = mergeRange; } /** * @return Returns the cellContent. */ public String getCellContent() { return cellContent; } /** * @param cellContent The cellContent to set. */ public void setCellContent(String cellContent) { this.cellContent = cellContent; } /** * @return Returns the cellType. */ public String getCellType() { return cellType; } /** * @param cellType The cellType to set. */ public void setCellType(String cellType) { this.cellType = cellType; } /** * @see java.lang.Object#toString() */ public String toString() { return this.cellContent; } /** * @return Returns the cellFormat. */ public WritableCellFormat getCellFormat() { return cellFormat; } /** * @param cellFormat The cellFormat to set. */ public void setCellFormat(WritableCellFormat cellFormat) { this.cellFormat = cellFormat; } }
package com.perfectorial.dao; import com.perfectorial.entity.Category; import org.springframework.stereotype.Service; /** * @author Reza Safarpour (rsafarpour1991@gmail.com) on 9/25/2015 */ @Service public class CategoryDao extends AbstractGenericDao<Category> { }
package com.example.java.collections.map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.Data; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import static java.util.stream.Collectors.*; /** */ public class MapJava8ApiDemo { Map<String, List<Block>> map = Maps.newHashMap(); List<Block> list = Lists.newArrayList(); @Data private class Block { private String shap; private String name; public Block(String shap, String name) { this.shap = shap; this.name = name; } } @Before public void init() { list.clear(); map.clear(); list.add(new Block("长方体", "g1")); list.add(new Block("圆柱", "g2")); list.add(new Block("圆柱", "g3")); list.add(new Block("长方体", "g4")); list.add(new Block("圆柱", "g5")); list.add(new Block("梯形", "g6")); list.add(new Block("梯形", "g7")); } /** * 对一堆积木进行分类处理, * 根据积木形状,最终形成一个Map<String, List<Block>> * key为形状 value为这种形状的所有积木 */ @Test public void testClassify() { /*使用遍历的方式*/ for (Block block : list) { List<Block> bs = map.get(block.getShap()); if (bs == null) { bs = Lists.newArrayList(); map.put(block.getShap(), bs); } bs.add(block); } System.out.println(map); init(); //使用java8的Stream 更简洁的完成 Map<String, List<Block>> collect = list.stream().collect(groupingBy(Block::getShap)); System.out.println(collect); } @Test public void compute() { /* * 使用compute: * 首先从map中get出来对应的旧值,然后根据指定的remapping函数进行获取新值替换 * 如果新值为null 旧值不为null 则直接remove掉元素 */ map.compute("a1", (key, value) -> { if (value == null) { value = Lists.newArrayList(); } value.addAll(list); return value; }); System.out.println("compute-->" + map); init(); /*如果key 对应的值为null 就将function中返回的值put进去*/ map.computeIfAbsent("a3", (key) -> { return list; }); System.out.println("computeIfAbsent-->" + map); init(); /*与compute方式类似,不过是只有对应key的value 不为null才执行BiFunction 去替换新值*/ map.computeIfPresent("a4", (key, value) -> { return list; }); System.out.println("computeIfPresent-->" + map); } }
package de.semanticservices.praktikum.JarHEaD; import com.fluidops.iwb.api.EndpointImpl; import com.fluidops.iwb.api.ReadDataManager; import com.fluidops.iwb.api.query.QueryBuilder; import com.fluidops.iwb.annotation.CallableFromWidget; import java.lang.*; import java.util.*; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.RepositoryException; import org.openrdf.model.impl.ValueFactoryImpl; public class test2 { @CallableFromWidget public static String fakultaet(String o){ int i = Integer.parseInt(o); int fak = 1; for (int x = 1; x <= i; ++x) { fak = fak * x; } String finish="Fakultät von "+i+" ist : " + fak; return finish; } @CallableFromWidget public static String fakultaet2(int o){ int fak = 1; for (int x = 1; x <= o; ++x) { fak = fak * x; } String finish="Fakultät von "+o+" ist : " + fak; return finish; } @CallableFromWidget public static void ausgabe (String i){ System.out.println(i); } @CallableFromWidget public static int ausgabe2(String i ){ int x=Integer.parseInt(i); int b=x+x; return b; } @CallableFromWidget public static String distance(URI left,URI right){ /*left=Längen-, right=Breitengrad * berechne Abstand zwischen links und rechts/längen und * schreibe den Abstand in die Datenbank (DataProvider) * gebe String zurück"Der abstand ist : XXX Km" */ //String SPARQL="Select ?x ?y where{<"+left.toString()+"> :Länge ?x.<"+left.toString()+"> :Breite ?y}"; //String SPARQL="Select ?x ?y where{<http://www.fluidops.com/resource/test> :Länge ?x.<http://www.fluidops.com/resource/test> :Breite ?y}"; String SPARQL="Select ?x ?y where{?? :Länge ?x.?? :Breite ?y}"; System.out.println(SPARQL); String rechtsString=query(right, SPARQL); String linksString=query(left,SPARQL); double links[]=StringToDouble(linksString); double rechts[]=StringToDouble(rechtsString); System.out.println("Länge ist :"+links[0]+" Breite ist :"+links[1]); System.out.println("Länge ist :"+rechts[0]+" Breite ist :"+rechts[1]); double x=berechneDistance(rechts,links); String distance="Der Abstand beträgt "+x+" Km"; return distance; } public static double berechneDistance(double rechts[],double links[]){ double lat=(rechts[1]+links[1])/2*0.01745; double dx=111.3*Math.cos(lat)*(rechts[0]-links[0]); double dy=111.3*(rechts[1]-links[1]); double distance=Math.sqrt(dx*dx+dy*dy); return distance; } public static double [] StringToDouble(String o){ double[] rechts=new double [2]; int indexEnde=0; char c; int indexKomma=0; for (int y =1;y<o.length();y++){ c=o.charAt(y); if(c=='"'){ indexEnde=y; y=o.length(); } } for (int y =1;y<o.length();y++){ c=o.charAt(y); if(c==','){ indexKomma=y; y=o.length(); } } String rechtsString=o.substring(1,indexKomma)+"."+o.substring(indexKomma+1, indexEnde); rechts[0]=Double.parseDouble(rechtsString); for (int y =indexEnde;y<o.length();y++){ c=o.charAt(y); if(c==','){ indexKomma=y; y=o.length(); } } String linksString=o.substring(indexEnde+2,indexKomma)+"."+o.substring(indexKomma+1, o.length()-1); System.out.println(linksString); rechts[1]=Double.parseDouble(linksString); return rechts; } @CallableFromWidget public static String query(URI current, String SPARQL) { ReadDataManager dm = EndpointImpl.api().getDataManager(); ValueFactory vf = ValueFactoryImpl.getInstance(); // setting URI context for ?? in the query //URI valueContext = vf.createURI(current); System.err.println(SPARQL); URI valueContext= current; QueryBuilder<TupleQuery> queryBuilder = QueryBuilder .createTupleQuery(SPARQL).resolveValue(valueContext) .infer(false); String out=null; TupleQuery query = null; try { query = queryBuilder.build(dm); } catch (MalformedQueryException | RepositoryException e) { System.err.println(e); } TupleQueryResult iterator = null; try { iterator = query.evaluate(); while (iterator.hasNext()) { BindingSet bindingSet = null; try { bindingSet = iterator.next(); } catch (QueryEvaluationException e) { System.err.println(e); } out= bindingSet.getValue("x").toString(); out+=bindingSet.getValue("y").toString(); } } catch (QueryEvaluationException e) { System.err.println(e); } return out; } }
package com.csc214.rebeccavandyke.socialnetworkingproject2.model; /* * Rebecca Van Dyke * rvandyke@u.rochester.edu * CSC 214 Project 2 * TA: Julian Weiss */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.UUID; public class User implements Comparable<User>{ private UUID mId; private String mUsername; private String mPassword; private String mEmail; private String mFullName; private Date mBirthdate; private String mHometown; private String mBio; private String mPhoto; private List<String> mUsersFavorited; public User() { this(UUID.randomUUID()); } public User(UUID id){ mId = id; mBirthdate = new Date(); mUsername = ""; mPassword = ""; mFullName = ""; mPhoto = ""; mBio = ""; mEmail = ""; mHometown = ""; mUsersFavorited = new ArrayList<>(); mUsersFavorited.add("Admin"); } //User() public int compareTo(User other){ return mUsername.compareTo(other.getUsername()); } //compareTo() public UUID getId() { return mId; } public void setId(UUID mId) { this.mId = mId; } public String getUsername() { return mUsername; } public void setUsername(String mUsername) { this.mUsername = mUsername; } public String getPassword() { return mPassword; } public void setPassword(String mPassword) { this.mPassword = mPassword; } public void setFullName(String mFullName) { this.mFullName = mFullName; } public String getFullName(){ return mFullName; } public String getEmail() { return mEmail; } public void setEmail(String mEmail) { this.mEmail = mEmail; } public Date getBirthdate() { return mBirthdate; } public String getStringBirthdate() { SimpleDateFormat df = new SimpleDateFormat("MM/dd/yy"); return df.format(mBirthdate); } public void setBirthdate(Date mBirthdate) { this.mBirthdate = mBirthdate; } public void setStringBirthdate(String birthdate) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("MM/dd/yy"); Date stringDate = df.parse(birthdate); } public String getHometown() { return mHometown; } public void setHometown(String mHometown) { this.mHometown = mHometown; } public String getBio() { return mBio; } public void setBio(String mBio) { this.mBio = mBio; } public String getPhoto() { return mPhoto; } public void setPhoto(String mPhoto) { this.mPhoto = mPhoto; } public List<String> getUsersFavorited() { return mUsersFavorited; } public void setUsersFavorited(List<String> usersFavorited){ mUsersFavorited = usersFavorited; } public String getFavoriteUserString(){ String userList = ""; for(String s: mUsersFavorited){ userList += s + ","; } return userList; } //getFavoriteUserString() public void setUsersFavorited(String usersFavorited){ mUsersFavorited = new ArrayList<String>(Arrays.asList(usersFavorited.split(","))); } //setUsersFavorited() } //end class
package com.sinotao.business.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; import com.sinotao.business.dao.entity.ClinicarCheckResult; public interface ClinicarCheckResultDao extends Mapper<ClinicarCheckResult> { public String selectLastCheckNumber(@Param("suffix") String suffix, @Param("itemCode") List<String> itemCode); public Integer selectLastCheckItemId(@Param("suffix") String suffix, @Param("dptCode") String dptCode); }
package com.example.retail.services.customerorders; import com.example.retail.models.customerorders.CustomerOrders; import com.example.retail.models.customerorders.CustomerOrdersHelper; import com.example.retail.repository.customerorders.CustomerOrdersRepository; import com.example.retail.models.discounts.CustomerOrdersDiscount; import com.example.retail.services.discounts.CustomerOrdersDiscountServices; import com.example.retail.users.profiles.UsersProfile; import com.example.retail.users.profiles.UsersProfileService; import com.example.retail.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; @Service public class CustomerOrderServices { @Autowired CustomerOrdersRepository customerOrdersRepository; @Autowired JWTDetails jwtDetails; @Autowired UsersProfileService usersProfileService; @Autowired CreateResponse createResponse; @Autowired Validations validations; @Autowired Utils utils; @Autowired CustomerOrdersDiscountServices customerOrdersDiscountServices; @Autowired CustomerOrdersHelper customerOrdersHelper; // TODO: validate product-sub-id public ResponseEntity<Object> createCustomerOrder(HttpServletRequest request, CustomerOrders customerOrders) { try { /* Validate the order */ ValidationResponse validationRes = validations.validateCustomerOrder(customerOrders); int validationResStatusCode = validationRes.getStatusCode(); if(validationResStatusCode != validations.validationSuccessCode) { return ResponseEntity.status(validationResStatusCode).body( createResponse.createErrorResponse(validationResStatusCode, validationRes.getStatusMessage(), validationRes.getAdditionalInfo()) ); } String orderCreatedBy = jwtDetails.userName(request); Optional<UsersProfile> userDetails = usersProfileService.findByUserName(orderCreatedBy); AtomicReference<Float> totalAmountBeforeDiscountAndTax = new AtomicReference<>(0F); Float totalAmountAfterSpecialDiscount = 0F; Optional<CustomerOrdersDiscount> customerOrdersDiscount = Optional.empty(); /* If returned Object from validation is not null cast returned object to CustomerOrdersDiscount */ if (!validationRes.getAdditionalObjectsReturned().equals(Optional.empty())) { customerOrdersDiscount = (Optional<CustomerOrdersDiscount>) validationRes.getAdditionalObjectsReturned(); } customerOrders.getCustomerOrdersItemsList().forEach(eachItem -> { /* Calculate the total amount before discount and taxes * */ totalAmountBeforeDiscountAndTax.set(totalAmountBeforeDiscountAndTax.get() + eachItem.getProductDiscountedPrice()); }); if(!customerOrdersDiscount.equals(Optional.empty())) { /* calculate the price after discount */ totalAmountAfterSpecialDiscount = totalAmountBeforeDiscountAndTax.get() - customerOrdersHelper.calcSpecialDiscount(totalAmountBeforeDiscountAndTax.get(), customerOrdersDiscount.get().getDiscountPercentage()); } /* If loyalty discount is requested calculate the loayalty discount */ // TODO: check if special discount and loyalty discount ( && customerOrders.getSpeacialDiscountName().equals("loyaltyDiscount")) both can be applied together if (customerOrders.getSpeacialDiscountName() != null && customerOrders.getSpeacialDiscountName().equals("loyaltyDiscount")) { totalAmountAfterSpecialDiscount = totalAmountBeforeDiscountAndTax.get() - customerOrdersHelper.calcLoyaltyDiscount(orderCreatedBy); } Float deliveryCharges = 0F; Float paybleAmountAfterTax = totalAmountBeforeDiscountAndTax.get() - customerOrdersHelper.calcTax(totalAmountAfterSpecialDiscount, customerOrders.getTaxCategory()); customerOrders.setUserTableId(userDetails.get().getUserProfile_TableId()); customerOrders.setUserName(userDetails.get().getUserName()); customerOrders.setUserGivenName(userDetails.get().getUserProfile_GivenName()); customerOrders.setUserPhoneNumber(userDetails.get().getUserProfile_PhoneNumber()); customerOrders.setUserAddress(userDetails.get().getUserProfile_Address()); if (customerOrders.getDeliveryAddress() != null) { customerOrders.setDeliveryAddress(customerOrders.getDeliveryAddress()); } else { customerOrders.setDeliveryAddress(userDetails.get().getUserProfile_Address()); } customerOrders.setDeliveryCharges(deliveryCharges); customerOrders.setSpeacialDiscountValue(totalAmountBeforeDiscountAndTax.get() - totalAmountAfterSpecialDiscount); customerOrders.setAmountBeforeDiscount(totalAmountBeforeDiscountAndTax.get()); customerOrders.setAmountAfterDiscount(totalAmountAfterSpecialDiscount); customerOrders.setAmountBeforeTax(totalAmountAfterSpecialDiscount + deliveryCharges); customerOrders.setOrdersPaybleamount(paybleAmountAfterTax); customerOrders.setOrderDelivered(false); customerOrders.setPurchaseDate(LocalDate.now()); customerOrders.setPurchaseTime(LocalTime.now()); CustomerOrders res = customerOrdersRepository.save(customerOrders); List<Object> finalRes = new ArrayList<>(); finalRes.add(res); return ResponseEntity.status(201).body( createResponse.createSuccessResponse(201, "Created", finalRes) ); } catch (Exception e) { return ResponseEntity.status(500).body( createResponse.createErrorResponse(500, e.getMessage(), "NA") ); } } }
package in.hocg.defaults.base; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; /** * Created by hocgin on 16-12-19. * 用于持有ApplicationContext,可以使用SBeanUtilsAware.getBean('xxxx')的静态方法得到spring bean对象 */ @Component @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext APPLICATION_CONTEXT; /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return APPLICATION_CONTEXT; } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) APPLICATION_CONTEXT.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return (T) APPLICATION_CONTEXT.getBeansOfType(clazz); } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { APPLICATION_CONTEXT = null; } private static void checkApplicationContext() { if (APPLICATION_CONTEXT == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { /** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ SpringContextHolder.APPLICATION_CONTEXT = applicationContext; // NOSONAR } @Override public void destroy() throws Exception { SpringContextHolder.APPLICATION_CONTEXT = null; } }
package zy.fool.app; import zy.fool.view.FoolAdapter; import zy.fool.view.MyFoolView; import zy.fool.widget.FoolAbsView.OnPullOutListener; import zy.fool.widget.FoolListView; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; public class MainActivity extends Activity implements OnPullOutListener{ FoolAdapter mFoolAdapter ; FoolListView mView ; String [] mStrings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); View emptyView = findViewById(android.R.id.empty); mView = (FoolListView)findViewById(R.id.foolview); mFoolAdapter = new FoolAdapter(this); mView.setEmptyView(emptyView); //mView.setOnPullListener(this); //mFoolView.setAdapter(mFoolAdapter); mView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, GENRES)); //mView.setPullation(2); } @Override public boolean onPullOut() { // TODO Auto-generated method stub return true; } private static final String[] GENRES = new String[] { "-----0-----", "-----1-----", "-----2-----", "-----3-----", "-----4-----", "-----5-----", "-----6-----", "-----7-----", "-----8-----", "-----9-----", "-----10-----", "-----11-----", "-----13-----", "-----14-----", "-----15-----", "-----16-----", }; }
package questions.KthSmallestElementInAbst_0230; import java.util.ArrayDeque; import java.util.Deque; import java.util.Stack; import questions.common.TreeNode; /* * @lc app=leetcode.cn id=230 lang=java * * [230] 二叉搜索树中第K小的元素 * * https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/description/ * * algorithms * Medium (70.51%) * Likes: 231 * Dislikes: 0 * Total Accepted: 56.8K * Total Submissions: 80.3K * Testcase Example: '[3,1,4,null,2]\n1' * * 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。 * * 说明: * 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。 * * 示例 1: * * 输入: root = [3,1,4,null,2], k = 1 * ⁠ 3 * ⁠ / \ * ⁠1 4 * ⁠ \ * 2 * 输出: 1 * * 示例 2: * * 输入: root = [5,3,6,2,4,null,null,1], k = 3 * ⁠ 5 * ⁠ / \ * ⁠ 3 6 * ⁠ / \ * ⁠ 2 4 * ⁠ / * ⁠1 * 输出: 3 * * 进阶: * 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数? * */ // @lc code=start /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode * left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left * = left; this.right = right; } } */ class Solution { public int kthSmallest(TreeNode root, int k) { Deque<TreeNode> stack = new ArrayDeque<>(); inorderLeft(root, stack); int i = 0; while(i < k - 1) { TreeNode n = stack.pop(); if (n.right != null) { inorderLeft(n.right, stack); } i++; } return stack.pop().val; } private void inorderLeft(TreeNode node, Deque<TreeNode> stack) { while (node != null) { stack.push(node); node = node.left; } } } // @lc code=end
package pl.rogalik.environ1.game_map; import pl.rogalik.environ1.game_map.map_providers.persistence.FromFileMapReader; import pl.rogalik.environ1.game_map.map_providers.MapProviding; import pl.rogalik.environ1.game_map.map_objects.entities.Entity; import pl.rogalik.environ1.game_map.map_objects.tiles.Tile; import pl.rogalik.environ1.game_map.map_objects.entities.EntityType; import java.io.Serializable; import java.util.List; import java.util.Optional; public class GameMap implements Serializable { private static final long serialVersionUID = 1L; private List<Entity> entities; private Tile[][] map; private Tile heroPosition; private static MapFabric fabric = new MapFabric(); public GameMap(){ this(fabric.getGenerator()); } public GameMap(GameMap gameMap){ this(gameMap.getEntities(), gameMap.getMap()); } public GameMap(MapProviding mapGenerator){ this(mapGenerator.getEntities(), mapGenerator.getMap()); } public GameMap(FromFileMapReader f){ this(f.getEntities(), f.getMap()); } private GameMap(List<Entity> entities, Tile[][] map) { this.entities = entities; this.map = map; for (Entity entity : this.entities){ entity.setGameMap(this); if (entity.getType() == EntityType.HERO){ this.setHeroPosition(entity.getxPosition(), entity.getyPosition()); } } } public List<Entity> getEntities(){ return this.entities; } public Tile[][] getMap(){ return this.map; } /***** Na potrzeby testowania *****/ @Override public String toString(){ StringBuilder s = new StringBuilder(); for (int i = 0; i < map.length; i++){ for (int j = 0; j < map[0].length; j++){ s.append(map[i][j].toString()); } s.append("\n"); } return s.toString(); } /*** Funkcje dla Logiki ***/ public Optional<Tile> getObjectAt(int x, int y){ Tile tile; try{ tile = map[x][y]; } catch (ArrayIndexOutOfBoundsException e){ tile = null; } return Optional.ofNullable(tile); } /** Zwraca obszar włącznie z polami o współrzędnych (x1, y1) oraz (x2, y2) **/ public Optional<Tile>[][] getArea (int x1, int y1, int x2, int y2){ Optional<Tile>[][] area = new Optional[Math.abs(x2-x1)+1][Math.abs(y2-y1)+1]; for(int i = ((x1 < x2) ? x1 : x2); i <= ((x1 > x2) ? x1 : x2); i++){ for (int j = ((y1 < y2) ? y1 : y2); j <= ((y1 > y2) ? y1 : y2); j++) { area[i - ((x1 < x2) ? x1 : x2)][j - ((y1 < y2) ? y1 : y2)] = this.getObjectAt(i, j); } } return area; } public Tile getHeroPosition(){ return this.heroPosition; } public void setHeroPosition(int x, int y){ this.heroPosition = this.getObjectAt(x, y).get(); } public void getNewMap(){ MapProviding mapGen = fabric.getGenerator(); this.entities = mapGen.getEntities(); this.map = mapGen.getMap(); for (Entity entity : this.entities){ entity.setGameMap(this); if (entity.getType() == EntityType.HERO){ this.setHeroPosition(entity.getxPosition(), entity.getyPosition()); } } } }
package com.suning.alarm.client; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; public class AlarmApp { public static String randomHost() { Random r = new Random(); return "主机" + String.valueOf(r.nextInt(100)); } public static String randomValue() { Random r = new Random(); return String.valueOf(r.nextFloat()); } public static String randomIP() { try { Random r = new Random(); InetAddress addr = InetAddress.getByAddress(new byte[] { (byte) r.nextInt(), (byte) r.nextInt(), (byte) r.nextInt(), (byte) r.nextInt() }); return addr.getHostAddress(); } catch (UnknownHostException e) { return "127.0.0.1"; } } public static String alarm(String sysName, String hostName, String hostIP, String alarmType, String alarmValue, String grpStr) { String recvType = "ALL"; int delayMin = 5; String resp = alarm(sysName, hostName, hostIP, alarmType, alarmValue, null, grpStr, delayMin, recvType); return resp; } public static String alarm(String sysName, String hostName, String hostIP, String alarmType, String alarmValue, String recvStr, String grpStr) { String recvType = "ALL"; int delayMin = 5; String resp = alarm(sysName, hostName, hostIP, alarmType, alarmValue, recvStr, grpStr, delayMin, recvType); return resp; } public static String alarm(String sysName, String hostName, String hostIP, String alarmType, String alarmValue, String recvStr, String grpStr, int delayMin, String recvType) { PostParam pp = new PostParam(); pp.setSysName(sysName); pp.setHostName(hostName); pp.setHostIP(hostIP); pp.setAlarmType(alarmType); pp.setAlarmValue(alarmValue); pp.setRecvStr(recvStr); pp.setGrpStr(grpStr); pp.setDelayMin(delayMin); pp.setRecvType(recvType); System.out.println(pp); Poster poster = Poster.getPoster(); String resp = "UNKNOWN"; if (pp.validate()) { String url = Poster.URL; resp = poster.postService(url, pp.toString()); } return resp; } public static void alarm(String sysName, int delayMin, int count) throws UnknownHostException { String alarmType = "例外"; String recvStr = "欧锐"; String grpStr = "平台开发部"; String recvType = "ALL"; InetAddress ia = InetAddress.getLocalHost(); for (int i = 0; i < count; i++) { System.out.println("============== " + i + " ============="); String resp = alarm(sysName, ia.getHostName(),ia.getHostAddress(), alarmType, randomValue(), recvStr, grpStr, delayMin, recvType); System.out.println(resp); System.out.println("================================"); System.out.println(); } } public static void alarm(String sysName, int delayMin,String alarmType) throws UnknownHostException { String recvStr = "欧锐"; String grpStr = "平台开发部"; String recvType = "ALL"; InetAddress ia = InetAddress.getLocalHost(); System.out.println("================================"); String resp = alarm(sysName, ia.getHostName(),ia.getHostAddress(), alarmType, alarmType, recvStr, grpStr, delayMin, recvType); System.out.println(resp); System.out.println("================================"); System.out.println(); } }
package com.pedidovenda.repository.filter; import java.io.Serializable; import java.util.Date; import com.pedidovenda.model.StatusPedido; public class PedidoFilter implements Serializable{ private static final long serialVersionUID = 1L; private Long numeroDe; private Long numeroAte; private Date dataCriacaoDe; private Date dataCriacaoAte; private String nomeCliente; private String nomeUsuario; private StatusPedido[] statuses; public void setNumeroDe(Long numeroDe) { this.numeroDe = numeroDe; } public void setNumeroAte(Long numeroAte) { this.numeroAte = numeroAte; } public void setDataCriacaoDe(Date dataCriacaoDe) { this.dataCriacaoDe = dataCriacaoDe; } public void setDataCriacaoAte(Date dataCriacaoAte) { this.dataCriacaoAte = dataCriacaoAte; } public void setNomeCliente(String nomeCliente) { this.nomeCliente = nomeCliente; } public void setStatuses(StatusPedido[] statuses) { this.statuses = statuses; } public Long getNumeroDe() { return this.numeroDe; } public Long getNumeroAte() { return this.numeroAte; } public Date getDataCriacaoDe() { return this.dataCriacaoDe; } public Date getDataCriacaoAte() { return this.dataCriacaoAte; } public String getNomeCliente() { return this.nomeCliente; } public StatusPedido[] getStatuses() { return this.statuses; } public String getNomeUsuario() { return nomeUsuario; } public void setNomeUsuario(String nomeUsuario) { this.nomeUsuario = nomeUsuario; } }
package com.data.rhis2; import java.io.Serializable; import java.util.ArrayList; /** * Created by angsuman on 4/5/2016. */ public class Options implements Serializable { public ArrayList<Integer> codeList = new ArrayList<Integer>(); public ArrayList<String> HouseholdidList = new ArrayList<String>(); public ArrayList<String> capEngList = new ArrayList<String>(); }
package com.ats.qa.pages; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import com.ats.qa.base.Log; import com.ats.qa.base.TestBase; public class ParameterMaster { public WebDriver driver; public ParameterMaster(WebDriver driver) throws Exception { this.driver=driver; // TODO Auto-generated constructor stub } By Master=By.id("cphMain_Masters"); By para=By.id("ParameterMaster"); By parameter=By.id("cphMain_ddlParameter"); By save=By.id("cphMain_lbtnSave"); By update=By.id("cphMain_lbtnUpdate"); public void clickonMaster() throws InterruptedException { Thread.sleep(2000); driver.findElement(Master).click(); Log.info("Master module is click"); } public void clickonparameter() throws InterruptedException { Thread.sleep(2000); driver.findElement(para).click(); Log.info("parameter master is click"); } public void clickonEnterdetails() throws InterruptedException { Thread.sleep(2000); Select category=new Select(driver.findElement(parameter)); category.selectByVisibleText("College"); Log.info("college drop down value is selected"); Thread.sleep(2000); WebElement value=driver.findElement(By.id("cphMain_txtValue")); value.sendKeys("Test123"); Log.info("Test123 value is inserted"); driver.findElement(save).click(); Log.info("save button is selected"); Thread.sleep(2000); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("scroll(0, 350)"); driver.findElement(By.id("cphMain_gvShowParameterReport_lbtnEdit_0")).click(); Log.info("Edit button is selected"); Select category1=new Select(driver.findElement(parameter)); category1.selectByVisibleText("Degree"); Log.info("Degree drop down value is selected"); Thread.sleep(2000); WebElement senddocument=driver.findElement(By.id("cphMain_txtValue")); senddocument.clear(); senddocument.sendKeys("Degre certificate"); Log.info("Degree certificate value is selected"); driver.findElement(update).click(); Log.info("update button is selected"); } }
package com.okellosoftwarez.modelfarm; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.os.Bundle; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.okellosoftwarez.modelfarm.models.userModel; import java.net.InetAddress; public class SignIn extends AppCompatActivity { private static final String TAG = "SignIn"; private static FirebaseAuth signInmAuth; private EditText signInMail, signInPassword, signInPhone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); // Initialize Firebase Auth signInmAuth = FirebaseAuth.getInstance(); signInMail = findViewById(R.id.etSignInMail); signInPassword = findViewById(R.id.etPassword_signIn); signInPhone = findViewById(R.id.etPhone_signIn); Button next = findViewById(R.id.nextBtn_signIn); TextView registerBtn = findViewById(R.id.registerTxt_signIn); registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent regIntent = new Intent(SignIn.this, SignUp.class); startActivity(regIntent); } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isNetworkConnected()) { // if (isInternetAvailable()){ String email = signInMail.getText().toString().trim(); String password = signInPassword.getText().toString().trim(); String phone = signInPhone.getText().toString().trim(); if (email.isEmpty()) { signInMail.setError("Missing Log In Mail"); } else if (phone.isEmpty()) { signInPhone.setError("Phone Number required"); } else if (phone.length() < 10) { signInPhone.setError("Short Phone Number"); } else if (password.isEmpty()) { signInPassword.setError("Missing Log In PassWord"); } else if (password.length() < 6) { signInPassword.setError("PassWord Too Short"); } else { loadPreference(phone, email, password); // logInUser(email, password); } // } // else { // Toast.makeText(SignIn.this, R.string.No_internet, Toast.LENGTH_LONG).show(); // } } else { Toast.makeText(SignIn.this, R.string.No_network, Toast.LENGTH_LONG).show(); } } }); } private void loadPreference(String signInPhone, final String signInMail, final String signInPassword) { DatabaseReference signPreference = FirebaseDatabase.getInstance().getReference("userProfile").child(signInPhone); SharedPreferences pref = getApplicationContext().getSharedPreferences("Preferences", 0); final SharedPreferences.Editor signEditor = pref.edit(); signPreference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { userModel signInUser = dataSnapshot.getValue(userModel.class); if (signInUser != null) { // Storing Preference Data signEditor.putString("eMail", signInUser.getEmail()); signEditor.putString("userName", signInUser.getUserName()); signEditor.putString("phone", signInUser.getPhone()); signEditor.putString("location", signInUser.getLocation()); // commit changes signEditor.commit(); String confMail = signInUser.getEmail(); if (!confMail.isEmpty()) { if (confMail.equals(signInMail)) { logInUser(signInMail, signInPassword); } else { Toast.makeText(SignIn.this, "Incorrect Phone Number", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(SignIn.this, "No Retrieved User Mail", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SignIn.this, "Invalid Fields Try Creating an Account", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(SignIn.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void updateUI() { Intent autoIntent = new Intent(this, user.class); startActivity(autoIntent); } private void logInUser(String email, String password) { signInmAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success"); Toast.makeText(SignIn.this, "Welcome Back to Agriculture Commerce...", Toast.LENGTH_SHORT).show(); FirebaseUser user = signInmAuth.getCurrentUser(); if (user != null) { updateUI(); } } else { // If sign in fails, display a message to the user. Log.d(TAG, "signInWithEmail:failure:" + task.getException().getMessage() + ":"); String attempts = "We have blocked all requests from this device due to unusual activity. Try again later. [ Too many unsuccessful login attempts. Please try again later. ]"; if (task.getException().getMessage().equals("The email address is badly formatted.")) { Toast.makeText(SignIn.this, "Bad Format E mail...", Toast.LENGTH_LONG).show(); signInMail.setError("Bad Format for E-Mail Address"); } if (task.getException().getMessage().equals("The password is invalid or the user does not have a password.")) { Toast.makeText(SignIn.this, "PassWord or E mail is Incorrect...", Toast.LENGTH_LONG).show(); } if (task.getException().getMessage().equals("There is no user record corresponding to this identifier. The user may have been deleted.")) { Toast.makeText(SignIn.this, "Your E mail is Not Registered Try Create Account...", Toast.LENGTH_LONG).show(); } if (task.getException().getMessage().equals(attempts)) { Toast.makeText(SignIn.this, "Too Many Attempts !!! Get The Right Password and Try Again Later...", Toast.LENGTH_LONG).show(); } } } }); } public void forgotPassWord(View view) { if (isNetworkConnected()) { // if (isInternetAvailable()){ AlertDialog.Builder resetBuilder = new AlertDialog.Builder(this); resetBuilder.setTitle("Reset"); resetBuilder.setMessage("Enter Email To Receive Password Resent Link"); final EditText resetInput = new EditText(this); resetBuilder.setView(resetInput); resetBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String resetMail = resetInput.getText().toString().trim(); if (resetMail.isEmpty()) { Toast.makeText(SignIn.this, "The Email Address is Blank...", Toast.LENGTH_SHORT).show(); } if (Patterns.EMAIL_ADDRESS.matcher(resetMail).matches()) { FirebaseAuth auth = FirebaseAuth.getInstance(); auth.sendPasswordResetEmail(resetMail) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); Toast.makeText(SignIn.this, "Recovery Email has been Sent to : " + resetMail, Toast.LENGTH_SHORT).show(); } } }); } else { Toast.makeText(SignIn.this, "Invalid E-Mail Address...", Toast.LENGTH_LONG).show(); } } }); resetBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(SignIn.this, "Request Cancelled...", Toast.LENGTH_SHORT).show(); } }); resetBuilder.show(); // } // else { // // Toast.makeText(SignIn.this, R.string.No_internet, Toast.LENGTH_LONG).show(); // } } else { Toast.makeText(SignIn.this, R.string.No_network, Toast.LENGTH_LONG).show(); } } // This method checks whether mobile is connected to internet and returns true if connected: public boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected(); } // This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet). public boolean isInternetAvailable() { try { InetAddress ipAddr = InetAddress.getByName("google.com"); return !ipAddr.equals(""); } catch (Exception e) { return false; } } @Override public void onBackPressed() { // super.onBackPressed(); Intent backLintent = new Intent(this, welcome_screen.class); backLintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(backLintent); finish(); } }
import java.time.*; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.*; import java.util.Date; import java.text.SimpleDateFormat; public class Alexa { HashMap<String,ArrayList<String>> answers = new HashMap<String,ArrayList<String>>(); public Alexa(){ p(); System.out.println("Alexa Online :)"); } public String responder(String pregunta){ String respuesta =""; boolean coincidencias = false; for(HashMap.Entry<String,ArrayList<String>> entrada : answers.entrySet()){ if(pregunta.contains(entrada.getKey())){ coincidencias = true; ArrayList<String> respuestas = entrada.getValue(); int IRandom =(int)(Math.random() * respuestas.size()); switch(entrada.getKey()){ case "hora": respuesta = respuestas.get(IRandom) + obtenerHoraFormateada(); break; case "dia": respuesta = respuestas.get(IRandom) + obtenerFechaFormateada(); break; default: respuesta = respuestas.get(IRandom); break; } } } if(coincidencias == false){ ArrayList<String> sinrespuesta = answers.get("indefinido"); int IRandom=(int)(Math.random() * sinrespuesta.size()); respuesta = sinrespuesta.get(IRandom); } return respuesta; } public String obtenerHoraFormateada(){ LocalTime tiempo = LocalTime.now(); return tiempo.format(DateTimeFormatter.ofPattern("HH:mm")); } public String obtenerFechaFormateada(){ Date fecha= new Date(); SimpleDateFormat formatofecha = new SimpleDateFormat("dd/MM/YYYY"); return formatofecha.format(fecha); } public void p(){ answers.put("hora", new ArrayList<String>()); answers.get("hora").add("Son las"); answers.get("hora").add("La hora es"); answers.get("hora").add("La hora actual es"); answers.put("escuela", new ArrayList<String>()); answers.get("escuela").add("ESCOM-IPN"); answers.get("escuela").add("Estudio ESCOM"); answers.get("escuela").add("En la mejor escuela ESCOM"); answers.put("deporte", new ArrayList<String>()); answers.get("deporte").add("El futbol americano"); answers.get("deporte").add("El futbol soccer"); answers.get("deporte").add("La formula 1"); answers.put("ciudad", new ArrayList<String>()); answers.get("ciudad").add("de la CDMX"); answers.get("ciudad").add("Existo en Ciudad de Mexico"); answers.get("ciudad").add("from Mexico city"); answers.put("chiste", new ArrayList<String>()); answers.get("chiste").add("Mmmm, velas!, que celebramos? \n - Que nos han cortado la luz.."); answers.get("chiste").add("Que le habla un bit al otro? \n Nos vemos en el bus."); answers.get("chiste").add("Error 0094782: No se detecta ningun teclado pulse una tecla para continuar."); answers.put("edad", new ArrayList<String>()); answers.get("edad").add("Tengo 18"); answers.get("edad").add("vivio desde el 2001"); answers.get("edad").add("Tengo 10010"); answers.put("pais", new ArrayList<String>()); answers.get("pais").add("Mexico"); answers.get("pais").add("vivio en Mexico"); answers.get("pais").add("Soy Azteca"); answers.put("dia", new ArrayList<String>()); answers.get("dia").add("Hoy es"); answers.get("dia").add("Estamos a"); answers.get("dia").add("Es"); answers.put("indefinido", new ArrayList<String>()); answers.get("indefinido").add("Lo siento, no entendi lo que dices"); answers.get("indefinido").add("Perdon no se que responder"); answers.get("indefinido").add("Lo siento, no se que decir, estudiare mas para que no pase de nuevo"); answers.put("hola", new ArrayList<String>()); answers.get("hola").add("Hola, es un placer saludarte"); answers.get("hola").add("Hola, que tal tu cuarentena?"); answers.get("hola").add("Hola!!"); } }
package Practice; import java.util.Scanner; public class Practice { public static void main(String[] args) { System.out.println(multiChar("The")); } // Questions question 2 public static String multiChar(String input) { String output = ""; int len = input.length(); // To practice this for loop, change the len to a value and change around the "The" string etc for (int j = 0; j < len; j++) { // Outer loop for (int i = 0; i < 3; i++) { // Inner loop output = output + input.charAt(j); // equivalent to output += input.charAt(j); } } return output; } // Questions question 3 // public static void StringReverse() { // String reverseString = ""; // System.out.println("Enter string to reversed"); // // Scanner scanner = new Scanner(System.in); // String input = scanner.nextLine(); // // char[] inputArray = input.toCharArray(); // // for(int i=inputArray.length-1;i>=0;i--) // { // reverseString = reverseString+inputArray[i]; // } // System.out.println("Original String: "+input); // System.out.println("Reversed String: "+reverseString); // // } // } // public class StringReverse{ // String reverseString = ""; // public static void backwardsString() { // // System.out.println("Bread"); // // Scanner read = new Scanner(System.in); // String str = read.nextLine(); // String reverse= ""; // // for(int i = str.length() - 1; i >= 0; i--) // { // reverse = reverse + str.charAt(i); // } // System.out.println("Reversed string is:"); // System.out.println(reverse); // } }
/* Generated SBE (Simple Binary Encoding) message codec */ package sbe.msg.marketData; import uk.co.real_logic.sbe.codec.java.CodecUtil; import uk.co.real_logic.agrona.MutableDirectBuffer; @SuppressWarnings("all") public class BestBidOfferEncoder { public static final int BLOCK_LENGTH = 29; public static final int TEMPLATE_ID = 26; public static final int SCHEMA_ID = 1; public static final int SCHEMA_VERSION = 0; private final BestBidOfferEncoder parentMessage = this; private MutableDirectBuffer buffer; protected int offset; protected int limit; protected int actingBlockLength; protected int actingVersion; public int sbeBlockLength() { return BLOCK_LENGTH; } public int sbeTemplateId() { return TEMPLATE_ID; } public int sbeSchemaId() { return SCHEMA_ID; } public int sbeSchemaVersion() { return SCHEMA_VERSION; } public String sbeSemanticType() { return ""; } public int offset() { return offset; } public BestBidOfferEncoder wrap(final MutableDirectBuffer buffer, final int offset) { this.buffer = buffer; this.offset = offset; limit(offset + BLOCK_LENGTH); return this; } public int encodedLength() { return limit - offset; } public int limit() { return limit; } public void limit(final int limit) { buffer.checkLimit(limit); this.limit = limit; } public BestBidOfferEncoder messageType(final MessageTypeEnum value) { CodecUtil.charPut(buffer, offset + 0, value.value()); return this; } public static long instrumentIdNullValue() { return 4294967294L; } public static long instrumentIdMinValue() { return 0L; } public static long instrumentIdMaxValue() { return 4294967293L; } public BestBidOfferEncoder instrumentId(final long value) { CodecUtil.uint32Put(buffer, offset + 1, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } private final PriceEncoder bid = new PriceEncoder(); public PriceEncoder bid() { bid.wrap(buffer, offset + 5); return bid; } public static long bidQuantityNullValue() { return 4294967294L; } public static long bidQuantityMinValue() { return 0L; } public static long bidQuantityMaxValue() { return 4294967293L; } public BestBidOfferEncoder bidQuantity(final long value) { CodecUtil.uint32Put(buffer, offset + 13, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } private final PriceEncoder offer = new PriceEncoder(); public PriceEncoder offer() { offer.wrap(buffer, offset + 17); return offer; } public static long offerQuantityNullValue() { return 4294967294L; } public static long offerQuantityMinValue() { return 0L; } public static long offerQuantityMaxValue() { return 4294967293L; } public BestBidOfferEncoder offerQuantity(final long value) { CodecUtil.uint32Put(buffer, offset + 25, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } }
package ru.lischenko_dev.fastmessenger.vkapi.models; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import ru.lischenko_dev.fastmessenger.vkapi.Api; public class VKVideo implements Serializable { private static final long serialVersionUID = 1L; public long vid; public long owner_id; public String title; public String description; public long duration; public String link1; public String image;//130*97 public String image_big;//320*240 //public String photo_640; public long date; public String player; //files public String external; public String mp4_240; public String mp4_360; public String mp4_480; public String mp4_720; public String flv_320; public String access_key;//used when private video attached to message public int views; public static VKVideo parse(JSONObject o) throws NumberFormatException, JSONException { VKVideo v = new VKVideo(); v.vid = o.getLong("id"); v.owner_id = o.getLong("owner_id"); v.title = Api.unescape(o.optString("title")); v.duration = o.optLong("duration"); v.description = Api.unescape(o.optString("description")); v.image = o.optString("photo_130"); //notifications.get возвращает видео по-старому в типе like_video - баг в API if (!o.has("photo_130") && o.has("image")) v.image = o.optString("image"); v.image_big = o.optString("photo_320"); //notifications.get возвращает видео по-старому в типе like_video - баг в API if (!o.has("photo_320") && o.has("image_medium")) v.image_big = o.optString("image_medium"); v.date = o.optLong("date"); v.player = o.optString("player"); if (o.has("views")) v.views = o.getInt("views"); JSONObject files = o.optJSONObject("files"); if (files != null) { v.external = files.optString("external"); v.mp4_240 = files.optString("mp4_240"); v.mp4_360 = files.optString("mp4_360"); v.mp4_480 = files.optString("mp4_480"); v.mp4_720 = files.optString("mp4_720"); v.flv_320 = files.optString("flv_320"); } return v; } public static VKVideo parseForAttachments(JSONObject o) throws NumberFormatException, JSONException { VKVideo v = new VKVideo(); v.vid = o.getLong("id"); v.owner_id = o.getLong("owner_id"); v.title = Api.unescape(o.getString("title")); v.duration = o.getLong("duration"); v.description = Api.unescape(o.optString("description")); v.image = o.optString("photo_130"); v.image_big = o.optString("photo_320"); v.date = o.optLong("date"); v.player = o.optString("player"); v.access_key = o.optString("access_key"); return v; } public String getVideoUrl() { return getVideoUrl(owner_id, vid); } public static String getVideoUrl(long owner_id, long video_id) { String res = null; String base_url = "http://vk.com/"; res = base_url + "video" + owner_id + "_" + video_id; //sample http://vkontakte.ru/video4491835_158963813 //http://79.gt2.vkadre.ru/assets/videos/f6b1af1e4258-24411750.vk.flv return res; } }
package amt.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Created by ahmed.motair on 1/6/2018. */ @Entity @Table(name = "loggerDataList") public class UserLog { @Id @Column(name = "log_id") private String logID; public UserLog() { } public UserLog(String logID) { this.logID = logID; } public String getLogID() { return logID; } public void setLogID(String logID) { this.logID = logID; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserLog)) return false; UserLog userLog = (UserLog) o; return getLogID() != null ? getLogID().equals(userLog.getLogID()) : userLog.getLogID() == null; } @Override public int hashCode() { return getLogID() != null ? getLogID().hashCode() : 0; } @Override public String toString() { return "UserLog{" + "logID = " + logID + "}\n"; } }
package market; import java.awt.Canvas; import java.awt.Choice; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.table.AbstractTableModel; import main.AppMain; import main.Page; public class MarketPost extends Page{ // 서쪽 JPanel p_west; JButton bt_regist; JTextField t_title; JTextField t_price; JTextArea t_detail; JScrollPane scroll; JButton bt_web; JButton bt_file; Canvas can; JButton bt_edit; JButton bt_del; // 센터 JPanel p_center; JPanel p_search; // 검색 컴포넌트 올려두는 패널 Choice ch_category; // 검색 카테고리 JTextField t_keyword; // 검색어입력 JButton bt_search; JTable table; JScrollPane scroll_table; // 캔버스의 사진 Toolkit kit= Toolkit.getDefaultToolkit(); Image image; JFileChooser chooser; String filename; // 유저의 복사에 의해 생성된 파일명 // 테이블 String[] columns= {"pk_usermarket", "title ", "price ", "regdate", "pk_user "}; // 컬럼배열 String[][] records= {};// 레코드 배열 public MarketPost(AppMain appMain) { // -----------------------------------------------[생성] // 서쪽 관련 p_west= new JPanel(); bt_regist= new JButton("상품등록"); t_title= new JTextField(); t_price= new JTextField(); t_detail= new JTextArea(); scroll= new JScrollPane(t_detail); bt_web= new JButton("웹에서 파일 찾기"); bt_file= new JButton("내 컴퓨터에서 파일 찾기"); // 내부익명 클래스는 외부클래스의 멤버변수, 메소드를 접근가능. can= new Canvas() { // {}붙으며 extends효과 public void paint(Graphics g) { g.drawImage(image, 0, 0, 180, 180, can); } }; bt_edit= new JButton("수정"); bt_del= new JButton("삭제"); // 센터 p_center= new JPanel(); p_search= new JPanel(); ch_category= new Choice(); // 검색 카테고리 등록 ch_category.add("선택"); ch_category.add("작성자"); ch_category.add("내용"); t_keyword= new JTextField(); bt_search= new JButton("검색"); table= new JTable(new AbstractTableModel() { public int getRowCount() { return records.length; } public int getColumnCount() { return columns.length; } // 컬럼 제목 public String getColumnName(int col) { return columns[col]; } // 각 셀에 들어갈 데이터를 이차원 배열로부터 구함 public Object getValueAt(int row, int col) { return records[row][col]; } // JTable의 각 셀의 값을 지정 // 셀을 편집한 후 엔터치는 순간 아래의 메소드 호출 public void setValueAt(Object val, int row, int col) { records[row][col]=(String)val; // updateProduct(); // System.out.println(row+","+col+"번째 셀의 데이터는 "+val+"로 바꿀게요~"); } // 다른 메소드와 마친가지로, 아래의 isCe;;Editable메서드도 호출자가 JTable public boolean isCellEditable(int row, int col) { if(col==0) { // 첫번쩨 열인 product_id만 읽기전용으로 셋팅 return false; }else { return true; } } }); scroll_table= new JScrollPane(table); } }
/* * 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 LoginSistema; import java.net.ServerSocket; import javax.swing.JOptionPane; /** * * @author ingdonaldo */ public class Main { private static ServerSocket SERVER_SOCKET; public static void main(String[] args) { try { SERVER_SOCKET = new ServerSocket(1334); for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } new Login_Hospital().setVisible(true); } catch (Exception e) { JOptionPane.showMessageDialog(null, "El Programa ya ha sido ejecutado", "Informacion del Sistema", JOptionPane.ERROR_MESSAGE); } } }
package com.tencent.mm.plugin.appbrand.config; import android.util.Pair; import com.tencent.mm.sdk.platformtools.bi; import java.util.List; public final class t { public String appId; public int bGM; public String dLS; public List<WxaAttributes$WxaEntryInfo> frQ; public List<Pair<String, String>> fsc; public int fsi; public String fsq; private String fsr = null; public String nickname; public String signature; public String username; public final String aep() { if (bi.oW(this.fsr) && !bi.cX(this.fsc)) { String str; StringBuilder stringBuilder = new StringBuilder(); for (Pair pair : this.fsc) { str = bi.oW((String) pair.second) ? (String) pair.first : (String) pair.second; if (!bi.oW(str)) { stringBuilder.append("、"); stringBuilder.append(str); } } str = stringBuilder.toString(); if (!bi.oW(str)) { str = str.replaceFirst("、", ""); } this.fsr = str; } return bi.oV(this.fsr); } }
package wzs201609201; import java.awt.*; import java.awt.event.*; public class wzs201609201 { public static void main(String[] args) { // TODO Auto-generated method stub MainFrame mFrm = new MainFrame(); mFrm.setVisible(true); } } class MainFrame extends Frame{ private Label lab = new Label("Are you handsome?"); private Button btnStay = new Button("Yes"); private Button btnExit = new Button("No"); public MainFrame(){ initComp(); } private void initComp(){ this.setBounds(200,150,380,320); this.setLayout(new BorderLayout(2,1)); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); this.setBackground(Color.black); this.setLayout(null); lab.setLocation(150,100); lab.setBackground(Color.black); lab.setForeground(Color.white); lab.setSize(120,50); btnExit.setLocation(100, 200); btnExit.setSize(80,25); btnExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.exit(0); } }); btnStay.setLocation(200,200); btnStay.setSize(80,25); btnStay.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ fun1(); //System.exit(0); } }); this.add(btnStay); this.add(btnExit); this.add(lab); } private void fun1(){ this.setTitle("Keep Stay ! You idiot !"); } }
package com.cse308.sbuify.test; import com.cse308.sbuify.admin.Admin; import com.cse308.sbuify.admin.AdminRepository; import com.cse308.sbuify.song.Song; import com.cse308.sbuify.song.SongRepository; import com.cse308.sbuify.test.helper.AuthenticatedTest; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.*; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class AdminControllerTest extends AuthenticatedTest { @Autowired private SongRepository songRepository; @Autowired private AdminRepository adminRepository; /** * Test if getting all admin endpoint works */ @Test public void getAllAdmins() { Map<String, String> params = new HashMap<>(); ResponseEntity<ArrayList<Admin>> response = restTemplate.exchange("/api/admins/", HttpMethod.GET, null, new ParameterizedTypeReference<ArrayList<Admin>>() { }, params); assertEquals(HttpStatus.OK, response.getStatusCode()); // todo: systematically validate this List<Admin> admins = response.getBody(); for (int i = 0; i < admins.size(); i++) { System.out.println(admins.get(i)); } } /** * Test if getting admin by id works. Following is the expected admin object. { * "type" : "admin", "id" : 4, "email" : "sbuify+admin@gmail.com", "password" : * "$2a$10$UeuOatqlhQnbSeeqvHV.MOIFP3sNdrY204Ab7irDCILaTOQOJKy/y", "firstName" : * "John", "lastName" : "Doe", "superAdmin" : false } */ @Test public void getAdminByIdTest() { Admin expected = adminRepository.findByEmail("sbuify+admin@gmail.com"); Map<String, Object> params = new HashMap<>(); params.put("id", 4); ResponseEntity<Admin> response = restTemplate.getForEntity("/api/admins/{id}", Admin.class, params); assertEquals(HttpStatus.OK, response.getStatusCode()); Admin admin = response.getBody(); assertNotEquals(null, admin); assertEquals(expected.getEmail(), admin.getEmail()); assertEquals(expected.getFirstName(), admin.getFirstName()); assertEquals(expected.getLastName(), admin.getLastName()); assertEquals(expected.isSuperAdmin(), admin.isSuperAdmin()); } /** * Test creating admin. Update DB in order to pass this test: UPDATE Admin SET * super_admin = 1 WHERE Admin.id = 4; */ @Test public void createAdminTest() { Admin admin = new Admin("newEmail@gmail.com", "newPassword", "NewAdmin", "TestNewAdmin", false); long originalSize = adminRepository.count(); ResponseEntity<?> response = restTemplate.postForEntity("/api/admins/", admin, Admin.class); assertEquals(HttpStatus.CREATED, response.getStatusCode()); assertEquals(originalSize + 1, adminRepository.count()); } /** * Test updating the admin information. */ @Test public void updateAdminTest() { Optional<Admin> optionalAdmin = adminRepository.findById(4); assertEquals(true, optionalAdmin.isPresent()); Admin admin = optionalAdmin.get(); Map<String, String> params = new HashMap<>(); params.put("id", Integer.toString(4)); HttpEntity<Admin> req = new HttpEntity<Admin>(admin); ResponseEntity<Void> response = restTemplate.exchange("/api/admins/{id}", HttpMethod.PATCH, req, Void.class, params); assertEquals(HttpStatus.OK, response.getStatusCode()); } /** * Test to activate / deactivate a song. */ @Test public void deactivateActivateSong() { // todo: use a different endpoint or update existing endpoint to process ALL // updates (not just activate/deactivate) Map<String, String> params = new HashMap<>(); params.put("id", "1"); Optional<Song> optionalSong = songRepository.findById(1); assertTrue(optionalSong.isPresent()); Song original = optionalSong.get(); Boolean originalActive = original.isActive(); original.setActive(!originalActive); HttpEntity<Song> req = new HttpEntity<>(original); ResponseEntity<Song> res = null; res = restTemplate.exchange("/api/songs/{id}", HttpMethod.PATCH, req, Song.class, params); assertEquals(HttpStatus.OK, res.getStatusCode()); Song updated = res.getBody(); // If original activated, request should deactivate and vice versa assertEquals(!originalActive, updated.isActive()); } @Override public String getEmail() { return "sbuify+admin@gmail.com"; // use the user sbuify+admin@gmail.com for all tests in this class request // require admin role } @Override public String getPassword() { return "a"; } }
package com.ibm.jikesbt; /* * Licensed Material - Property of IBM * (C) Copyright IBM Corp. 1998, 2003 * All rights reserved */ /** This can be used to visit (call a method on) each kid (subclass, subinterface, or implemented class), its kids, their kids, .... E.g., do: <code><pre> * BT_ClassDescendentVisitor cdv = new BT_ClassDescendentVisitor() { * public void visit(BT_Class visitingC) { * System.out.println( " t Visiting ... " + visitingC.useName()); * super.visit(visitingC); * System.out.println( " t ... Visited " + visitingC.useName()); * } }; * BT_Class initC = __; * cdv.visitAncestors(initC); // or cdv.visitAClassAndDescendents(initC); </pre></code> The "opposite of" {@link BT_ClassAncestorVisitor}. * @author IBM **/ public abstract class BT_ClassDescendentVisitor extends BT_Base { /** Visits a class and its descendents. This method can be overridden with a method that does something interesting and that then invokes this method via <code>super.visit(visitingC)</code> to continue visiting its descendents. @param visitingC The class to be visited. **/ public void visit(BT_Class visitingC) { BT_ClassVector kids = visitingC.kids_; int size = kids.size(); for (int i = 0; i < size; ++i) visit(kids.elementAt(i)); } /** Calls {@link BT_ClassDescendentVisitor#visit} for this class, so visits this class and its descendents. Invoke this method both the initial class (initC) and its descendents are to be visited. <p> Override this method if you want to return something from an anonymous class -- something like: <code><pre> * public Object visitAClassAndDescendents(BT_Class initC) { * super.visitAClassAndDescendents( initC); * return this.someField; * } </pre></code> <p> {@link BT_ClassDescendentVisitor#visitDescendents} is the same except that it does not visit initC. @param initC The initial class to be visited. **/ public Object visitAClassAndDescendents(BT_Class initC) { visit(initC); return null; } /** Calls {@link BT_ClassDescendentVisitor#visit} for each kid of this class, so visits the descendents of the initial class (initC) -- not initC itself. Invoke this method if the initial class is <em>not</em> to be visited. <p> Override this method if you want to return something from an anonymous class. <p> {@link BT_ClassDescendentVisitor#visitAClassAndDescendents} is the same except that it also visits initC. @param initC The parent of the classes to be visited. **/ public Object visitDescendents(BT_Class initC) { BT_ClassVector kids = initC.kids_; int size = kids.size(); for (int i = 0; i < size; ++i) visit(kids.elementAt(i)); return null; } }
package jbyco.analysis.patterns.parameters; /** * A factory for creating FullParameter objects. */ public class FullParameterFactory implements AbstractParameterFactory { /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#init() */ @Override public void init() { } /** * Creates a new FullParameter object. * * @param type the type * @param components the components * @return the abstract parameter */ public AbstractParameter createParameter(ParameterType type, Object... components) { return new FullParameter(type, components); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getVariable(int) */ @Override public AbstractParameter getVariable(int index) { return createParameter(ParameterType.VARIABLE, new Integer(index)); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getMethodParameter(int) */ @Override public AbstractParameter getMethodParameter(int index) { return createParameter(ParameterType.PARAMETER, new Integer(index)); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getInt(int) */ @Override public AbstractParameter getInt(int i) { return createParameter(ParameterType.INT, new Integer(i)); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getFloat(float) */ @Override public AbstractParameter getFloat(float f) { return createParameter(ParameterType.FLOAT, new Float(f)); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getLong(long) */ @Override public AbstractParameter getLong(long l) { return createParameter(ParameterType.LONG, new Long(l)); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getDouble(double) */ @Override public AbstractParameter getDouble(double d) { return createParameter(ParameterType.DOUBLE, new Double(d)); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getString(java.lang.String) */ @Override public AbstractParameter getString(String s) { return createParameter(ParameterType.STRING, s); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getClass(java.lang.String) */ @Override public AbstractParameter getClass(String internalName) { return createParameter(ParameterType.CLASS, internalName); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getArray(java.lang.String) */ @Override public AbstractParameter getArray(String internalName) { return createParameter(ParameterType.ARRAY, internalName); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getField(java.lang.String, java.lang.String) */ @Override public AbstractParameter getField(String name, String desc) { return createParameter(ParameterType.FIELD, name, desc); } /* (non-Javadoc) * @see jbyco.analysis.patterns.parameters.AbstractParameterFactory#getMethod(java.lang.String, java.lang.String) */ @Override public AbstractParameter getMethod(String name, String desc) { return createParameter(ParameterType.METHOD, name, desc); } @Override public AbstractParameter getNull() { return ParameterValue.NULL; } @Override public AbstractParameter getThis() { return ParameterValue.THIS; } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.extension.frontend.client.widget.openmeetings; import java.util.ArrayList; import java.util.List; import com.openkm.frontend.client.extension.comunicator.DashboardComunicator; import com.openkm.frontend.client.extension.event.HasDashboardEvent; import com.openkm.frontend.client.extension.event.HasDashboardEvent.DashboardEventConstant; import com.openkm.frontend.client.extension.event.HasLanguageEvent; import com.openkm.frontend.client.extension.event.HasLanguageEvent.LanguageEventConstant; import com.openkm.frontend.client.extension.event.handler.DashboardHandlerExtension; import com.openkm.frontend.client.extension.event.handler.LanguageHandlerExtension; /** * OpenMeetings * * @author jllort * */ public class OpenMeetings implements DashboardHandlerExtension, LanguageHandlerExtension { private static final String UUID = "905075bd-f969-4d95-91ea-4900adc90471"; private static OpenMeetings singleton; public Status generalStatus; public ToolBarBoxOpenMeeting toolBarBoxOpenMeeting; /** * OpenMeetings * * @param uuidList */ public OpenMeetings(List<String> uuidList) { if (isRegistered(uuidList)) { singleton = this; toolBarBoxOpenMeeting = new ToolBarBoxOpenMeeting(); generalStatus = new Status(toolBarBoxOpenMeeting.manager); generalStatus.setStyleName("okm-StatusPopup"); } } /** * getExtensions * * @return */ public List<Object> getExtensions() { List<Object> extensions = new ArrayList<Object>(); extensions.add(singleton); extensions.add(toolBarBoxOpenMeeting.getToolBarBox()); return extensions; } /** * get * * @return */ public static OpenMeetings get() { return singleton; } @Override public void onChange(DashboardEventConstant event) { if (event.equals(HasDashboardEvent.TOOLBOX_CHANGED)) { if (DashboardComunicator.isWidgetExtensionVisible(toolBarBoxOpenMeeting.getToolBarBox().getWidget())) { toolBarBoxOpenMeeting.refreshPixelSize(); } } } @Override public void onChange(LanguageEventConstant event) { if (event.equals(HasLanguageEvent.LANGUAGE_CHANGED)) { toolBarBoxOpenMeeting.langRefresh(); } } /** * isRegistered * * @param uuidList * @return */ public static boolean isRegistered(List<String> uuidList) { return uuidList.contains(UUID); } }
package com.smxknife.dubbo.spi; /** * @author smxknife * 2021/5/24 */ public interface ProviderService { String sayHi(); }
package ex27; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class AppTest { @Test void validateFName() { assertEquals("", App.validateFName("James") ); } @Test void validateLName() { assertEquals("", App.validateLName("Moore") ); } @Test void validateID() { assertEquals("", App.validateID("jj-1312") ); } @Test void validateZIP() { assertEquals("", App.validateZIP("32888") ); } @Test void validateInput() { assertEquals("There were no errors found.\n", App.validateInput("james", "moore", "jj-1234", "32888") ); } }
package plattern.VisitorPattern; public class Grades implements Acceptor { Acceptor [] grades; public Grades () { grades = new Acceptor [] { new Grade1Student(), new Grade2Student(), new Grade3Student() }; } public void accept(Visitor visitor) { for (int i=0;i<grades.length;i++) { Acceptor acceptor = grades[i]; acceptor.accept(visitor); } } }
package com.tencent.mm.plugin.voip; import android.content.Context; import com.tencent.mm.R; import com.tencent.mm.compatible.util.g; import com.tencent.mm.g.a.su; import com.tencent.mm.g.a.su$b; import com.tencent.mm.model.au; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.voip.model.i; import com.tencent.mm.plugin.voip.model.m; import com.tencent.mm.plugin.voip.model.q; import com.tencent.mm.plugin.voip.model.r; import com.tencent.mm.plugin.voip.model.s; import com.tencent.mm.protocal.c.caa; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.nio.ByteBuffer; public final class a extends c<su> { public a() { this.sFo = su.class.getName().hashCode(); } private static boolean a(su suVar) { boolean z = true; if ((suVar instanceof su) && au.HX()) { r bJI; Object obj; Object obj2; caa caa; s sVar; switch (suVar.cdE.bOh) { case 1: i.bJI(); com.tencent.mm.plugin.voip.model.n.a OG = r.OG(suVar.cdE.content); if (OG != null) { if (!OG.bKi()) { if (OG.oLD != com.tencent.mm.plugin.voip.model.n.a.oLK) { z = false; } if (z) { suVar.cdF.type = 3; break; } } suVar.cdF.type = 2; break; } break; case 2: suVar.cdF.cdG = i.bJI().bCI; break; case 3: bJI = i.bJI(); obj = suVar.cdE.cdy; if (obj != null && obj.length >= 10 && obj[0] == (byte) 1) { obj2 = new byte[(obj.length - 1)]; System.arraycopy(obj, 1, obj2, 0, obj2.length); m mVar = bJI.oNa.oHa.oJX.oPS; mVar.oLw = System.currentTimeMillis(); com.tencent.mm.plugin.voip.b.a.eV("MicroMsg.VoipDailReport", "devin:recvInvite:" + mVar.oLw); try { caa caa2 = (caa) new caa().aG(obj2); x.d("MicroMsg.Voip.VoipService", "doTaskCallin in onInviteNotify"); if (!bJI.oNa.bLd()) { h.mEJ.a(11523, true, true, new Object[]{Integer.valueOf(caa2.rxG), Long.valueOf(caa2.rxH), Integer.valueOf(caa2.svK), Integer.valueOf(0), Long.valueOf(System.currentTimeMillis())}); bJI.a(caa2); break; } h.mEJ.a(11523, true, true, new Object[]{Integer.valueOf(caa2.rxG), Long.valueOf(caa2.rxH), Integer.valueOf(caa2.svK), Integer.valueOf(0), Long.valueOf(System.currentTimeMillis())}); break; } catch (Throwable e) { x.printErrStackTrace("MicroMsg.Voip.VoipService", e, "", new Object[0]); break; } } case 4: su$b su_b = suVar.cdF; r bJI2 = i.bJI(); Context context = ad.getContext(); if (bJI2.bCI && bJI2.oNl && !bJI2.oNm) { x.d("MicroMsg.Voip.VoipService", "isVideoCalling " + bJI2.oNc + " isAudioCalling " + bJI2.oNd); if (!bi.oW(bJI2.talker)) { au.HU(); if (com.tencent.mm.model.c.FR().Yg(bJI2.talker) != null) { r.a(context, bJI2.talker, true, bJI2.oNc, true); su_b.cdH = z; break; } } } z = false; su_b.cdH = z; case 5: if (!com.tencent.mm.p.a.BQ()) { if (suVar.cdE.cdz != 2) { if (suVar.cdE.cdz != 3) { if (suVar.cdE.cdz == 4) { q.aM(suVar.cdE.context, suVar.cdE.talker); break; } } q.aL(suVar.cdE.context, suVar.cdE.talker); break; } q.aK(suVar.cdE.context, suVar.cdE.talker); break; } com.tencent.mm.ui.base.h.i(suVar.cdE.context, R.l.multitalk_in_tip, R.l.app_tip); break; break; case 6: bJI = i.bJI(); byte[] bArr = suVar.cdE.cdy; if (bArr != null) { x.i("MicroMsg.Voip.VoipService", "____voipNotify with data size:" + bArr.length); int i = ByteBuffer.wrap(bArr, 0, 4).getInt(); long j = ByteBuffer.wrap(bArr, 4, 8).getLong(); x.i("MicroMsg.Voip.VoipService", "voipNotify roomid:" + i + " roomkey:" + j); if (bJI.oNn == null) { x.i("MicroMsg.Voip.VoipServiceEx", "current roomid:%d, params roomid:%d", new Object[]{Integer.valueOf(bJI.oNa.oHa.oJX.kpo), Integer.valueOf(i)}); if (i == 0 || r5.oHa.oJX.kpo != i) { z = false; } if (!z) { x.e("MicroMsg.Voip.VoipService", "voipSyncStatus ignored , not current roomid"); break; } } if (bArr.length > 12) { bJI.b(r.R(bArr, bArr.length - 12), i, j); } s sVar2 = bJI.oNa; com.tencent.mm.plugin.voip.b.a.eU("MicroMsg.Voip.VoipServiceEx", g.Ac() + " need doSync by notify, status:" + sVar2.oHa.mStatus); sVar2.oHa.oKa.a(null, false, 7); break; } x.i("MicroMsg.Voip.VoipService", "sidney:notify content null"); break; case 9: bJI = i.bJI(); obj = suVar.cdE.cdy; if (!bi.bC(obj) && obj[0] == (byte) 3) { try { x.i("MicroMsg.Voip.VoipService", "onCancelNotify"); obj2 = new byte[(obj.length - 1)]; System.arraycopy(obj, 1, obj2, 0, obj2.length); caa = new caa(); caa.aG(obj2); bJI.yH(caa.rxG); if (!(bJI.oNn == null || caa.rxG != bJI.oNn.rxG || bJI.ltH.ciq())) { bJI.oNn = null; bJI.oNo = 0; bJI.ltH.SO(); } sVar = bJI.oNa; x.i("MicroMsg.Voip.VoipServiceEx", "onCancelInviteNotify, roomId: %s", new Object[]{Integer.valueOf(caa.rxG)}); if (sVar.oHa.oKc != null && caa.rxG == sVar.oHa.oKc.rxG) { sVar.bLi(); sVar.oHa.shutdown(); break; } } catch (Exception e2) { x.e("MicroMsg.Voip.VoipService", "onCancelNotify error: %s", new Object[]{e2.getMessage()}); break; } } case 10: bJI = i.bJI(); obj = suVar.cdE.cdy; if (!bi.bC(obj) && obj[0] == (byte) 2) { try { x.i("MicroMsg.Voip.VoipService", "onAnswerNotify"); obj2 = new byte[(obj.length - 1)]; System.arraycopy(obj, 1, obj2, 0, obj2.length); caa = new caa(); caa.aG(obj2); sVar = bJI.oNa; x.i("MicroMsg.Voip.VoipServiceEx", "onAnswerNotify, roomId: %s", new Object[]{Integer.valueOf(caa.rxG)}); if (caa.rxG == sVar.oHa.oKc.rxG) { if (!sVar.oHa.bXc) { x.i("MicroMsg.Voip.VoipServiceEx", "onAnswerNotify, not accept, hangout"); sVar.bLi(); sVar.oHa.shutdown(); break; } x.i("MicroMsg.Voip.VoipServiceEx", "onAnswerNotify, already accept, ignore it"); break; } } catch (Exception e22) { x.e("MicroMsg.Voip.VoipService", "onAnswerNotify error: %s", new Object[]{e22.getMessage()}); break; } } break; } } return false; } }
package com.kunsoftware.directive; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.kunsoftware.entity.ValueSet; import com.kunsoftware.service.ValueSetService; import com.kunsoftware.util.WebUtil; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; public class ValueSetWriteDirective implements TemplateDirectiveModel { @SuppressWarnings("rawtypes") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String code = ObjectUtils.toString(params.get("code")); String value = ObjectUtils.toString(params.get("value")); String str = getResult(code,value); Writer out = env.getOut(); out.write(str.toString()); } public static String getResult(String code,String value) { ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(WebUtil.getRequest().getSession().getServletContext()); ValueSetService service = ctx.getBean(ValueSetService.class); List<ValueSet> list = null; String writeValue = ""; if("destination".equals(code)) { list = service.selectValueSetDestinationList(); } else if("airline".equals(code)) { list = service.selectValueSetAirlineList(); } else if("ground".equals(code)) { writeValue = service.getGroundName(value); } else if("article_classify".equals(code)) { list = service.selectValueSetArticleClassify(); } else { list = service.selectValueSetList(code); } StringBuilder str = new StringBuilder(); if(list != null) { List<String> selectedList = new ArrayList<String>(); if(StringUtils.isNotBlank(value)) selectedList.addAll(Arrays.asList(StringUtils.split(value,","))); String resultStr = null; for(ValueSet entity:list) { resultStr = WebUtil.write(entity.getName(), entity.getValue(), selectedList); if(StringUtils.isEmpty(resultStr)) continue; if(StringUtils.isNotEmpty(str.toString())) str.append(","); str.append(resultStr); } } else { str.append(writeValue); } return str.toString(); } }
package com.samyotech.laundry.ui.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; import com.samyotech.laundry.R; import com.samyotech.laundry.databinding.AdapterNotificationBinding; import com.samyotech.laundry.model.NotificationDTO; import com.samyotech.laundry.utils.ProjectUtils; import java.util.List; public class AdapterNotifcation extends RecyclerView.Adapter<AdapterNotifcation.MyViewHolder> { LayoutInflater layoutInflater; AdapterNotificationBinding binding; Context kContext; List<NotificationDTO> popLaundryDTOArrayList; public AdapterNotifcation(Context kContext, List<NotificationDTO> popLaundryDTOArrayList) { this.kContext = kContext; this.popLaundryDTOArrayList = popLaundryDTOArrayList; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (layoutInflater == null) { layoutInflater = LayoutInflater.from(parent.getContext()); } binding = DataBindingUtil.inflate(layoutInflater, R.layout.adapter_notification, parent, false); return new MyViewHolder(binding); } @Override public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { NotificationDTO item = popLaundryDTOArrayList.get(position); holder.binding.title.setText(item.getTitle()); holder.binding.ctvMessage.setText(item.getMessage()); holder.binding.ctvtime.setText(ProjectUtils.convertTimestampDateToTime(Long.parseLong(item.getCreated_at()))); } @Override public int getItemCount() { return popLaundryDTOArrayList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { AdapterNotificationBinding binding; public MyViewHolder(@NonNull AdapterNotificationBinding itemView) { super(itemView.getRoot()); this.binding = itemView; } } }
package org.wuqinghua.thread; /** * Created by wuqinghua on 18/2/11. */ public class SyncException1 { private int i = 0; public synchronized void operation() { while (true) { try { i++; Thread.sleep(200); System.out.println(Thread.currentThread().getName() + ",i = " + i); if (i == 10) { Integer.parseInt("a"); // throw new RuntimeException(); } } catch (Exception e) { //InterruptedException e.printStackTrace(); System.out.println(" log info i = " + i); // throw new RuntimeException(); // continue; } } } public static void main(String[] args) { final SyncException1 se = new SyncException1(); Thread t1 = new Thread(() -> se.operation(), "t1"); t1.start(); } }
package rent.common.projection; import org.springframework.data.rest.core.config.Projection; import rent.common.entity.BuildingMeterEntity; import java.time.LocalDate; @Projection(types = {BuildingMeterEntity.class}) public interface BuildingMeterBasic extends AbstractBasic { MeterBasic getMeter(); LocalDate getDateStart(); LocalDate getDateEnd(); }
package com.xiaodao.admin.entity; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.xiaodao.core.domain.BaseEntity; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.Date; @Data @Slf4j public class SysOperLog extends BaseEntity { /** * 日志主键 */ @JsonSerialize(using = ToStringSerializer.class) @ApiModelProperty("日志主键") private Long operId; /** * 模块标题 */ @ApiModelProperty("模块标题") private String title; /** * 业务类型(0其它 1新增 2修改 3删除) */ @ApiModelProperty("业务类型(0其它 1新增 2修改 3删除)") private Integer businessType; /** * 方法名称 */ @ApiModelProperty("方法名称") private String method; /** * 请求方式 */ @ApiModelProperty("请求方式") private String requestMethod; /** * 操作类别(0其它 1后台用户 2手机端用户) */ @ApiModelProperty("操作类别(0其它 1后台用户 2手机端用户)") private Integer operatorType; /** * 操作人员 */ @ApiModelProperty("操作人员") private String operName; /** * 部门名称 */ @ApiModelProperty("部门名称") private String deptName; /** * 请求URL */ @ApiModelProperty("请求URL") private String operUrl; /** * 主机地址 */ @ApiModelProperty("主机地址") private String operIp; /** * 操作地点 */ @ApiModelProperty("操作地点") private String operLocation; /** * 请求参数 */ @ApiModelProperty("请求参数") private String operParam; /** * 操作状态(0正常 1异常) */ @ApiModelProperty("操作状态(0正常 1异常)") private Integer status; /** * 错误消息 */ @ApiModelProperty("错误消息") private String errorMsg; /** * 操作时间 */ @ApiModelProperty("操作时间") private Date operTime; }
package xyz.maksimenko.iqbuzztt.DAO; import xyz.maksimenko.iqbuzztt.Visitor; public interface VisitorDAO { public void addVisitor(Visitor visitor); public void updateVisitor(Visitor visitor); public Visitor getVisitor(Long visitorId); public Visitor getVisitorByUserName(String userName); public void removeVisitor(Long visitorId); }
package com.example.tianshuai.swipetoloadlayout; /** * Created by tianshuai on 2017/9/5. */ import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import java.util.HashMap; import java.util.Set; public class SharePreferenceUtils { private static final String DEFAULT_FILE_NAME="sp_yuliao"; /** * 保存数据到sp的方法,根据value类型调用不同的保存方法,默认用的sp的文件名字为DEFAULT_FILE_NAME * @param context * @param key * @param value */ public static boolean setParam(Context context , String key, Object value){ HashMap<String ,Object> map = new HashMap<>(); map.put(key ,value); return setParam(DEFAULT_FILE_NAME,context,map); } public static boolean setParam( Context context ,HashMap<String ,Object> values){ return setParam(DEFAULT_FILE_NAME,context,values); } public static boolean setParam( String fileName,Context context ,String key, Object value){ HashMap<String ,Object> map = new HashMap<>(); map.put(key ,value); return setParam(fileName,context,map); } public static boolean setParam(String fileName, Context context , HashMap<String ,Object> values){ if(context == null || fileName == null){ return false; } SharedPreferences sp = context.getSharedPreferences(fileName ,Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); Set<String> keys = values.keySet(); for(String tempKey :keys){ Object value = values.get(tempKey); String type = value.getClass().getSimpleName(); if("String".equals(type)){ editor.putString(tempKey, (String)value); } else if("Integer".equals(type)){ editor.putInt(tempKey, (Integer)value); } else if("Boolean".equals(type)){ editor.putBoolean(tempKey, (Boolean)value); } else if("Float".equals(type)){ editor.putFloat(tempKey, (Float)value); } else if("Long".equals(type)){ editor.putLong(tempKey, (Long)value); } } return editor.commit(); } /** * 根据defaultValue的类型返回相应的类型值,默认用的sp的文件名字为DEFAULT_FILE_NAME * @param context * @param key * @param defaultValue * @return */ public static Object getParam(Context context , String key, Object defaultValue){ return getParam(DEFAULT_FILE_NAME,context,key,defaultValue); } public static Object getParam(String fileName,Context context , String key, Object defaultValue){ String type = defaultValue.getClass().getSimpleName(); SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); if("String".equals(type)){ return sp.getString(key, (String)defaultValue); } else if("Integer".equals(type)){ return sp.getInt(key, (Integer)defaultValue); } else if("Boolean".equals(type)){ return sp.getBoolean(key, (Boolean)defaultValue); } else if("Float".equals(type)){ return sp.getFloat(key, (Float)defaultValue); } else if("Long".equals(type)){ return sp.getLong(key, (Long)defaultValue); } return null; } }
package com.diumotics.qms.service.QueueService; import com.diumotics.qms.qms.dto.QueueDto; import com.diumotics.qms.qms.dto.TellerDto; import java.util.ArrayList; /** * Created by Thilini Hansika on 3/13/2019. */ public interface QueueService { public boolean save(QueueDto queueDto); public ArrayList<QueueDto> getQueueList(); public boolean deactiveQueueRecord(String id); }
package by.training.fundamental.task02; import org.junit.Assert; import org.junit.Test; public class FindSumTest1 { @Test public void findSum01() { int firstNumber = -559; int secondNumber = 392; int thirdNumber = 548; int expectedSum = -11; MathProblem mathProblem = new MathProblem(firstNumber, secondNumber, thirdNumber); int realSum = mathProblem.calculateSum(); Assert.assertEquals(expectedSum, realSum); } }
package request; import java.util.List; import dataHolder.TarSrvAccInfo; public class EditSettingReq { private String srvID; private String name; private List<TarSrvAccInfo> targetSrvAccInfo; public String getSrvID() { return srvID; } public String getName() { return name; } public void setSrvID(String srvID) { this.srvID = srvID; } public void setName(String name) { this.name = name; } public void setTargetSrvAccInfo(List<TarSrvAccInfo> targetSrvInfo) { this.targetSrvAccInfo = targetSrvInfo; } public List<TarSrvAccInfo> getTargetSrvAccInfo() { return targetSrvAccInfo; } }
package spring.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import spring.entity.ItemDto; import spring.repository.ItemDao; public class DetailController implements Controller{ private ItemDao itemDao; public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse arg1) throws Exception { //no를 받아 해당상품의 정보를 꺼내어 전달 int no = Integer.parseInt(req.getParameter("no")); ItemDto itemDto = itemDao.get(no); ModelAndView mv = new ModelAndView(); mv.setViewName("/WEB-INF/view/product/detail.jsp"); mv.addObject("itemDto", itemDto); return mv; } }
package Flowers.Observer; import Flowers.Order; import java.util.ArrayList; /** * Created by Yasya on 25.12.16. */ public class Observable<T> { private ArrayList<Observer> observers; private T items; public Observable() { observers = new ArrayList<>(); } public Observable(T i) { items = i; observers = new ArrayList<>(); } public T getState(){ return this.items; } public void setState(T items){ this.items = items; notifyAllobservers(); } public void attach(Observer observer){ observers.add(observer); } public void notifyAllobservers(){ for(Observer observer: observers) { observer.update(items); } } }
package com.travel_agency.controller; import com.travel_agency.service.RoomBookArchiveService; import com.travel_agency.service.UserService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Controller @AllArgsConstructor public class UserController { private final UserService userService; private final RoomBookArchiveService roomBookArchiveService; @GetMapping("/allUsers") public String getAllUsers(HttpServletRequest request, Model model) { model.addAttribute("users", userService.getAllUsers()); model.addAttribute("id", request.getParameter("id")); return "management/users"; } @GetMapping("/info") public String info(@RequestParam int id, Model model) { model.addAttribute("user", userService.getUserById(id)); model.addAttribute("rooms", roomBookArchiveService.getRoomBookArchiveByUserId(id)); return "management/user"; } }
class Solution { public int numJewelsInStones(String J, String S) { HashSet<Character> hs = new HashSet<>(); for(char c: J.toCharArray()) hs.add(c); int count = 0; for(char c: S.toCharArray()){ if(hs.contains(c)) count++; } return count; } }
package cci_stacks_queues; import java.util.LinkedList; /** * Animal Shelter: An animal shelter, which holds only dogs and cats, operates * on a strictly"first in, first out" basis. People must adopt either the * "oldest" (based on arrival time) of all animals at the shelter, or they can * select whether they would prefer a dog or a cat (and will receive the oldest * animal of that type). They cannot select which specific animal they would * like. Create the data structures to maintain this system and implement * operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may * use the built-in Linked list data structure. * * @author chenfeng * */ public class AnimalShelter_3_6 { public static void main(String[] args) { // create test case } public static class animalQueue { private static LinkedList<Dog> dogs; private static LinkedList<Cat> cats; private static int time; public animalQueue() { dogs = new LinkedList<Dog>(); cats = new LinkedList<Cat>(); time = 0; } public void enqueue(Animal a) { a.setTime(time); time++; if (a instanceof Dog) dogs.addLast((Dog) a); else if (a instanceof Cat) cats.addLast((Cat) a); } public static Animal dequeueAny() { if (dogs.isEmpty() && cats.isEmpty()) return null; else if (dogs.isEmpty()) return cats.removeFirst(); else if (cats.isEmpty()) return dogs.removeFirst(); else { return dogs.getFirst().getTime() > cats.getFirst().getTime() ? dogs.removeFirst() : cats.removeFirst(); } } public static Animal dequeueDog() { if (dogs.isEmpty()) return null; return dogs.removeFirst(); } public static Animal dequeueCat() { if (cats.isEmpty()) return null; return cats.removeFirst(); } } ////////////////////////////////////////////////// // Helper classes ////////////////////////////////////////////////// public static class Dog extends Animal { public Dog(String name) { super(name); } } public static class Cat extends Animal { public Cat(String name) { super(name); } } public static class Animal { private String name; private int time; public Animal(String name) { this.name = name; } public void setTime(int time) { this.time = time; } public int getTime() { return time; } } }
package pl.finapi.paypal; import org.scribe.builder.ServiceBuilder; import org.scribe.model.Token; import org.scribe.model.Verifier; import org.scribe.oauth.OAuthService; import pl.finapi.paypal.oauth.InfaktApi; public class InfaktMain { @SuppressWarnings("unused") public static void main(String[] args) { String consumerKey = ""; String consumerSecret = ""; String requestTokenURL = "https://www.infakt.pl/oauth/request_token"; String accessTokenURL = "https://www.infakt.pl/oauth/access_token"; String authorizeURL = "https://www.infakt.pl/oauth/authorize"; String infaktWsBaseUrl = "https://www.infakt.pl/api/v2/"; OAuthService service = new ServiceBuilder().provider(InfaktApi.class).apiKey(consumerKey).apiSecret(consumerSecret).build(); Verifier verifier = new Verifier("value"); Token requestToken = service.getAccessToken(new Token("token", "secret"), verifier); Token requestToken2 = service.getRequestToken(); System.out.println(""); // service. } }
/* * 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 Ejercicio3_14; /** * * @author leonardo */ public class Empleado { private String nombre; private String apellido; private double salariomensual; public Empleado(String nombre, String apellido, double salariomensual) { this.nombre = nombre; this.apellido = apellido; setSalarioMensual(salariomensual); setSalarioAnual(salariomensual); } public String getNombre() { return nombre; } public String getApellido() { return apellido; } public double getSalarioMensual() { return salariomensual; } public void setNombre(String nombre) { this.nombre = nombre; } public void setApellido(String apellido) { this.apellido = apellido; } public void setSalarioMensual(double salariomensual) { this.salariomensual = (salariomensual > 0) ? salariomensual : 0.0; } public double getSalarioAnual() { double salarioAnual; double aumento; salarioAnual = (salariomensual * 12); aumento = salarioAnual * 0.10; salarioAnual += aumento; return salarioAnual; } public void setSalarioAnual(double salarioAnual) { // this.salarioAnual = salarioAnual; } }
package com.ld.common.model; import java.math.BigDecimal; import java.util.Date; public class ParkingSpaceModel { private Long id; private Long communityId; private Long code; private String name; private BigDecimal size; private String remark; private Long bigint1; private Long bigint2; private String varchar1; private String varchar2; private Date createTime; private Date updateTime; private Long updateUser; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCommunityId() { return communityId; } public void setCommunityId(Long communityId) { this.communityId = communityId; } public Long getCode() { return code; } public void setCode(Long code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public BigDecimal getSize() { return size; } public void setSize(BigDecimal size) { this.size = size; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public Long getBigint1() { return bigint1; } public void setBigint1(Long bigint1) { this.bigint1 = bigint1; } public Long getBigint2() { return bigint2; } public void setBigint2(Long bigint2) { this.bigint2 = bigint2; } public String getVarchar1() { return varchar1; } public void setVarchar1(String varchar1) { this.varchar1 = varchar1 == null ? null : varchar1.trim(); } public String getVarchar2() { return varchar2; } public void setVarchar2(String varchar2) { this.varchar2 = varchar2 == null ? null : varchar2.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Long getUpdateUser() { return updateUser; } public void setUpdateUser(Long updateUser) { this.updateUser = updateUser; } }
package vn.geekup.geekupandroidsample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import vn.geekup.utils.DateUtils; import vn.geekup.utils.ScreenUtils; import vn.geekup.utils.StringUtils; public class HomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); StringUtils.init(this); // or ScreenUtils.init(this); // or DateUtils.init(this); } }
package backjoon.dp_minpath; import java.io.*; import java.util.*; class Bus implements Comparable<Bus>{ int end; int cost; public Bus(int end, int cost) { this.end = end; this.cost = cost; } @Override public int compareTo(Bus o) { return cost - o.cost; } } public class Backjoon11779 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); // 최단거리의 최댓 값 // 최대 노드 수 * 버스 최대 비용 static int INF = 1_000 * 100_000; static ArrayList<Bus> busList[]; static int dist[]; static int start, end; static int n, m; static int parent[]; static int cityCnt; static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException { n = Integer.parseInt(br.readLine()); m = Integer.parseInt(br.readLine()); busList = new ArrayList[n + 1]; // 인접리스트 초기화 for(int i = 1 ; i <= n; i++){ busList[i] = new ArrayList<>(); } // 인접리스트 초기화 for(int i = 0 ; i < m; i++){ StringTokenizer st = new StringTokenizer(br.readLine()); int start = Integer.parseInt(st.nextToken()); int end = Integer.parseInt(st.nextToken()); int cost = Integer.parseInt(st.nextToken()); busList[start].add(new Bus(end, cost)); } StringTokenizer st = new StringTokenizer(br.readLine()); start = Integer.parseInt(st.nextToken()); end = Integer.parseInt(st.nextToken()); // 최단경로를 저장한다. dist = new int[n + 1]; // 경로 추적을 위한 부모노드 정보를 저장한다. parent = new int[n + 1]; Arrays.fill(dist, INF); // 다익스트라를 이용하여 최단거리를 구한다. dijkstra(); Stack<Integer> stack = searchPath(); while(!stack.isEmpty()){ int city = stack.pop(); sb.append(city + " "); } bw.write(dist[end] + "\n"); bw.write(cityCnt + "\n"); bw.write(sb.toString()); bw.close(); br.close(); } public static void dijkstra(){ PriorityQueue<Bus> pq = new PriorityQueue<>(); boolean check[] = new boolean[n + 1]; pq.add(new Bus(start, 0)); dist[start] = 0; while(!pq.isEmpty()){ Bus curBus = pq.poll(); int cur = curBus.end; if(check[cur] == true) continue; check[cur] = true; for(Bus bus : busList[cur]){ if(dist[bus.end] > dist[cur] + bus.cost){ dist[bus.end] = dist[cur] + bus.cost; pq.add(new Bus(bus.end, dist[bus.end])); parent[bus.end] = cur; } } } } public static Stack<Integer> searchPath(){ Stack<Integer> stack = new Stack<>(); int cur = end; while(cur != start) { stack.push(cur); cityCnt++; cur = parent[cur]; } stack.push(cur); cityCnt++; return stack; } }
package co.edu.utp.misiontic2022.c2; import java.util.ArrayList; public class materia { // Atributos public String nombre; private double promedioAjustado; private ArrayList<nota> notasQuizes = new ArrayList<nota>(); //creamos el array bacio public nota peorNota; String codigoEstudianteCursando; // Constructores materia(String pCodigoEstudiante, String pNombre, int n1, int n2, int n3, int n4, int n5){ this.nombre = pNombre; this.codigoEstudianteCursando = pCodigoEstudiante; this.notasQuizes.add(new nota(n1)); this.notasQuizes.add(new nota(n2)); this.notasQuizes.add(new nota(n3)); this.notasQuizes.add(new nota(n4)); this.notasQuizes.add(new nota(n5)); this.peorNota = new nota(100); this.promedioAjustado = 0; } //metodo: los metodos comienzan siempre por un verbo //1. obtener la peor nota public void obtenerPeorNota(){ for (nota califi: notasQuizes){ if(califi.getEscala100() < this.peorNota.getEscala100()){ this.peorNota = califi; } } } //2. calcular el pormedio ajustado public void calcularPromedioAjustado(){ //2. 1 obtener peor nota this.obtenerPeorNota(); //2. 2 Recorrar las notas para obtener la sumatoria int sumatoria = 0; for (nota califi: notasQuizes){ sumatoria += califi.getEscala5(); } this.promedioAjustado = (sumatoria - this.peorNota.getEscala5())/(this.notasQuizes.size()-1); } //2. 3 mostrar materia public void mostrarMateria(){ System.out.println("---info materia ---"); System.out.println("*****Materia : "+ this.nombre + "*****"); for (nota califi: notasQuizes){ califi.mostrarNota(); } System.out.println("Promedio ajustado : "+ this.promedioAjustado); System.out.println("peor nota:"); this.peorNota.mostrarNota(); } }
package edu.uic.ids561; //import statements import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class Mapper2 extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] user_list = line.split("\t"); String user_ratings = user_list[1]; // System.out.println(user_ratings); String[] input = user_ratings.split("\\s+"); // System.out.println(input[0]); for(int i=0; i< input.length; i++) { if(input[i].length() == 0) continue; for(int j=i+1; j <input.length; j++) { String[] pair1 = input[i].split(","); String [] pair2 = input[j].split(","); String movie_pair, rating_pair; if(Integer.parseInt(pair1[0]) <= Integer.parseInt(pair2[0])) { movie_pair = pair1[0] + "," + pair2[0]; rating_pair = pair1[1] + "," + pair2[1]; } else { movie_pair = pair2[0] + "," + pair1[0]; rating_pair = pair2[1] + "," + pair1[1]; } context.write(new Text(movie_pair), new Text(rating_pair)); } } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /* ACMICPC 문제 번호 : 2491 문제 제목 : 수열 풀이 날짜 : 2020-09-19 Solved By Reamer */ public class acm_2491 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] numArr = new int[N]; for (int i = 0; i < N; i++) { numArr[i] = Integer.parseInt(st.nextToken()); } int start = 0, end = 1; int maxASClength = 1; while (true) { if (end == N) { int length = end - start; if (maxASClength < length) maxASClength = length; break; } if (numArr[end] >= numArr[end - 1]) { end++; } else { int length = end - start; if (maxASClength < length) maxASClength = length; start = end; end++; } } start = 0; end = 1; int maxDESClength = 1; while (true) { if (end == N) { int length = end - start; if (maxDESClength < length) maxDESClength = length; break; } if (numArr[end] <= numArr[end - 1]) { end++; } else { int length = end - start; if (maxDESClength < length) maxDESClength = length; start = end; end++; } } int answer = maxASClength > maxDESClength ? maxASClength : maxDESClength; System.out.println(answer); } }
package com.campus.service.impl; import com.campus.entity.MenuBean; import com.campus.mapper.SysMapper; import com.campus.service.SysService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class SysServiceImpl implements SysService { @Resource private SysMapper sysMapper; public List<MenuBean> getMenuList(Long rid) { return sysMapper.getMenuList(rid); } }
package pe.edu.upeu.hotel.entity; public class Persona { private int idpersona; private String nombre; private String dni; private String fechanacimiento; public Persona() { } public Persona(int idpersona, String nombre, String dni, String fechanacimiento) { this.idpersona = idpersona; this.nombre = nombre; this.dni = dni; this.fechanacimiento = fechanacimiento; } public int getIdpersona() { return idpersona; } public void setIdpersona(int idpersona) { this.idpersona = idpersona; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getFechanacimiento() { return fechanacimiento; } public void setFechanacimiento(String fechanacimiento) { this.fechanacimiento = fechanacimiento; } }
package com.ncda.entity; public class AccountBillType { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column account_bill_type.TYPE_ID * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ private Integer typeId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column account_bill_type.TYPE_ONE_NAME * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ private String typeOneName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column account_bill_type.USER_ID * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ private Integer userId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column account_bill_type.TYPE_KEYWORD * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ private String typeKeyword; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column account_bill_type.TYPE_ID * * @return the value of account_bill_type.TYPE_ID * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public Integer getTypeId() { return typeId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column account_bill_type.TYPE_ID * * @param typeId the value for account_bill_type.TYPE_ID * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public void setTypeId(Integer typeId) { this.typeId = typeId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column account_bill_type.TYPE_ONE_NAME * * @return the value of account_bill_type.TYPE_ONE_NAME * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public String getTypeOneName() { return typeOneName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column account_bill_type.TYPE_ONE_NAME * * @param typeOneName the value for account_bill_type.TYPE_ONE_NAME * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public void setTypeOneName(String typeOneName) { this.typeOneName = typeOneName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column account_bill_type.USER_ID * * @return the value of account_bill_type.USER_ID * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public Integer getUserId() { return userId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column account_bill_type.USER_ID * * @param userId the value for account_bill_type.USER_ID * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public void setUserId(Integer userId) { this.userId = userId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column account_bill_type.TYPE_KEYWORD * * @return the value of account_bill_type.TYPE_KEYWORD * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public String getTypeKeyword() { return typeKeyword; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column account_bill_type.TYPE_KEYWORD * * @param typeKeyword the value for account_bill_type.TYPE_KEYWORD * * @mbggenerated Tue Aug 31 15:21:51 CST 2021 */ public void setTypeKeyword(String typeKeyword) { this.typeKeyword = typeKeyword; } }
import java.util.AbstractList; import java.util.Comparator; public class Pair<T extends Comparable<? super T>> { public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T get(int n) { return n == 0 ? first : n == 1 ? second : null; } public void set(int n, T t) { if (n == 0) first = t; else if (n == 1) second = t; } public void copyFrom (Pair<? extends T> other) { this.first = other.get(0); this.second = other.get(1); } public void copyTo (Pair<? super T> other) { other.first = this.first; other.second = this.second; } public T min(Comparator<? super T> comp) { if (comp.compare(first, second) < 0) return first; else return second; } public T min() { if (first.compareTo(second) < 0) return first; else return second; } private T first; private T second; }
package pe.gob.trabajo.repository.search; import pe.gob.trabajo.domain.Datlab; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the Datlab entity. */ public interface DatlabSearchRepository extends ElasticsearchRepository<Datlab, Long> { }
package leecode.DP; //https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/best-time-to-buy-and-sell-stock-ii-zhuan-hua-fa-ji/ //贪心解析 public class 买卖股票的最佳时机II { public static int maxProfit(int[] prices) { if(prices==null||prices.length==0){ return 0; } int temp=-1; int res=0; //解决 1 2 4 :第一天买,最后一天卖!也是两天之间的差值和! for (int i = 0; i <prices.length-1 ; i++) { temp=prices[i+1]-prices[i]; res+=temp>0?temp:0; //sum=sum+temp>0?temp:0;不对,要加括号 sum=sum+(temp>0?temp:0); } return res; } public static void main(String[] args) { int[]num={1,2,4}; int[]num1={7,1,5,3,6,4}; System.out.println(maxProfit(num1)); } }
package com.base.crm.procurement.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import com.base.common.util.PageTools; import com.base.crm.procurement.entity.ProcurementCosts; import com.base.crm.procurement.service.ProcurementCostService; import com.base.crm.users.entity.UserInfo; @Controller @RequestMapping(value = "/procurement") @SessionAttributes("user") public class ProcurementController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ProcurementCostService procurementCostService; @RequestMapping(value = "/primaryModalView") public String primaryModalView(Long id, String modifyModel, Model model) throws Exception { logger.debug("primaryModalView request:" + id + ",model:" + model); if (id != null) { ProcurementCosts procurementCosts = procurementCostService.selectByPrimaryKey(id); model.addAttribute("modifyInfo", procurementCosts); } model.addAttribute("modifyModel", modifyModel); logger.debug("primaryModalView model : " + model); return "page/procurement/ModifyModal"; } @RequestMapping(value = "/pageView") @ResponseBody public Map<String, Object> view(ProcurementCosts queryObject, PageTools pageTools, @ModelAttribute("user") UserInfo user) { logger.debug("procurementView request : " +queryObject); Assert.isTrue(user.isAdmin(), "非管理员不允许查询"); Long size = procurementCostService.selectPageTotalCount(queryObject); pageTools.setTotal(size); Map<String,Object> result = new HashMap<String,Object>(); result.put("pageTools", pageTools); return result; } @RequestMapping(value = "/loadPage") public ModelAndView loadPage(ProcurementCosts queryObject, PageTools pageTools, @ModelAttribute("user") UserInfo user) throws Exception { logger.debug("loadPage ProcurementCosts request:" + queryObject + " page info ===" + pageTools); Assert.isTrue(user.isAdmin(), "非管理员不允许查询"); queryObject.setPageTools(pageTools); Long size = procurementCostService.selectPageTotalCount(queryObject); pageTools.setTotal(size); List<ProcurementCosts> resultList = procurementCostService.selectPageByObjectForList(queryObject); logger.debug("loadPage ProcurementCosts result list info =====:" + resultList); ModelAndView mv = new ModelAndView("page/procurement/Content :: container-fluid"); mv.addObject("resultList", resultList); mv.addObject("pageTools", pageTools); mv.addObject("queryObject", queryObject); logger.debug("queryObject =====:" + mv); return mv; } @RequestMapping(value="/procurementEdit") @ResponseBody public Map<String,Object> edit(ProcurementCosts editData){ logger.info("procurementEdit request:{}",editData); int num = procurementCostService.doUpdate(editData); Map<String,Object> map = new HashMap<String,Object>(); map.put("success", true); map.put("editNumber", num); return map; } @RequestMapping(value="/procurementAdd") @ResponseBody public Map<String,Object> add(ProcurementCosts addData) throws Exception{ logger.info("procurementAdd request:{}",addData); int num = procurementCostService.insertSelective(addData); Map<String,Object> map = new HashMap<String,Object>(); map.put("success", true); map.put("addNumber", num); return map; } }
package com.stagnationlab.c8y.driver.devices; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cumulocity.rest.representation.event.EventRepresentation; import com.cumulocity.rest.representation.inventory.ManagedObjectRepresentation; import com.cumulocity.rest.representation.measurement.MeasurementRepresentation; import com.cumulocity.sdk.client.Platform; import com.cumulocity.sdk.client.event.EventApi; import com.cumulocity.sdk.client.inventory.InventoryApi; import com.cumulocity.sdk.client.measurement.MeasurementApi; import com.stagnationlab.c8y.driver.services.DeviceManager; import com.stagnationlab.c8y.driver.services.Util; import c8y.Hardware; import c8y.lx.driver.Driver; import c8y.lx.driver.OperationExecutor; @SuppressWarnings("WeakerAccess") public abstract class AbstractDevice implements Driver { private static final Logger log = LoggerFactory.getLogger(AbstractDevice.class); protected Platform platform; protected MeasurementApi measurementApi; protected EventApi eventApi; protected InventoryApi inventoryApi; protected ManagedObjectRepresentation childDevice; protected final List<OperationExecutor> operationExecutors; protected final String id; protected AbstractDevice(String id) { this.id = id; operationExecutors = new ArrayList<>(); } @Override public void initialize() throws Exception { log.info("starting '{}'", id); } @Override public void initialize(Platform platform) throws Exception { this.platform = platform; this.measurementApi = platform.getMeasurementApi(); this.eventApi = platform.getEventApi(); this.inventoryApi = platform.getInventoryApi(); } @Override public void initializeInventory(ManagedObjectRepresentation managedObjectRepresentation) { log.info("initializing '{}' inventory", id); } @Override public void start() { log.info("starting '{}'", id); } @Override public OperationExecutor[] getSupportedOperations() { return operationExecutors.toArray(new OperationExecutor[operationExecutors.size()]); } @Override public void discoverChildren(ManagedObjectRepresentation parent) { log.info("discovering '{}' children", id); childDevice = DeviceManager.createChild( id, getType(), platform, parent, getHardware(), getSupportedOperations(), getSensorFragment() ); } protected abstract String getType(); protected Hardware getHardware() { return null; } protected Object getSensorFragment() { return null; } protected void registerOperationExecutor(OperationExecutor operationExecutor) { log.info("registering operation executor for '{}' of type '{}'", id, operationExecutor.supportedOperationType()); operationExecutors.add(operationExecutor); } protected MeasurementRepresentation reportMeasurement(Object measurement, String type) { log.info("reporting measurement for '{}' of type '{}': {}", id, type, Util.stringify(measurement)); MeasurementRepresentation measurementRepresentation = new MeasurementRepresentation(); measurementRepresentation.setSource(childDevice); measurementRepresentation.setType(type); measurementRepresentation.set(measurement); measurementRepresentation.setTime(new Date()); measurementApi.create(measurementRepresentation); return measurementRepresentation; } protected MeasurementRepresentation reportMeasurement(Object measurement) { return reportMeasurement(measurement, measurement.getClass().getSimpleName()); } protected void reportEvent(EventRepresentation eventRepresentation) { log.info("reporting event for '{}' of type '{}': {}", id, eventRepresentation.getClass().getSimpleName(), Util.stringify(eventRepresentation)); eventRepresentation.setSource(childDevice); eventApi.create(eventRepresentation); } protected ManagedObjectRepresentation updateState(Object... properties) { log.info("updating state of '{}': {}", id, Util.stringify(properties)); ManagedObjectRepresentation managedObjectRepresentation = new ManagedObjectRepresentation(); managedObjectRepresentation.setId(childDevice.getId()); for (Object property : properties) { managedObjectRepresentation.set(property); } childDevice = platform.getInventoryApi().update(managedObjectRepresentation); return managedObjectRepresentation; } @SuppressWarnings("SameParameterValue") protected ScheduledFuture<?> setInterval(Runnable runnable, long intervalMs) { log.info("creating an interval for '{}' every {}ms", id, intervalMs); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor( r -> new Thread(r, getType() + "Interval") ); long now = new Date().getTime(); long initialDelay = intervalMs - (now % intervalMs); return executorService.scheduleAtFixedRate( runnable, initialDelay, intervalMs, MILLISECONDS ); } }
package com.polsl.edziennik.desktopclient.view.common.panels; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ExecutionException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import com.polsl.edziennik.delegates.DelegateFactory; import com.polsl.edziennik.delegates.login.LoginManager; import com.polsl.edziennik.desktopclient.controller.utils.FrameToolkit; import com.polsl.edziennik.desktopclient.controller.utils.factory.GuiComponentFactory; import com.polsl.edziennik.desktopclient.controller.utils.factory.IGuiComponentAbstractFactory; import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.IButton; import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.ILabel; import com.polsl.edziennik.desktopclient.controller.utils.workers.Worker; import com.polsl.edziennik.desktopclient.view.common.dialogs.ProfileDialog; import com.polsl.edziennik.modelDTO.person.PersonDTO; public class ProfilePanel extends JPanel { private JLabel password; private JLabel retype; private JPasswordField passwordText; private JPasswordField retypeText; private FrameToolkit frameToolkit = new FrameToolkit(); private JButton save; private IGuiComponentAbstractFactory factory = GuiComponentFactory.getInstance(); private ILabel label; private IButton button; private CellConstraints cc; private ProfileDialog parent; public ProfilePanel(ProfileDialog parent) { this.parent = parent; FormLayout layout = new FormLayout( "pref,4dlu, 100dlu,, min", "pref, 2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref,2dlu, pref, 2dlu, pref"); setLayout(layout); label = factory.createLabel(); button = factory.createTextButton(); init(); setComponents(); setVisible(true); } public void init() { password = label.getLabel("newPassword"); retype = label.getLabel("retype"); passwordText = new JPasswordField(30); retypeText = new JPasswordField(30); save = button.getButton("save", "saveNewPass"); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); } public void setComponents() { cc = new CellConstraints(); add(password, cc.xy(1, 1)); add(retype, cc.xy(1, 3)); add(passwordText, cc.xy(3, 1)); add(retypeText, cc.xy(3, 3)); } public class ChangePasswordWorker extends Worker<Boolean> { public ChangePasswordWorker() { super("set"); } @Override protected Boolean doInBackground() throws Exception { startProgress(); if (new String(passwordText.getPassword()).compareTo(new String(retypeText.getPassword())) == 0) { PersonDTO person = LoginManager.getUser(); DelegateFactory.getTeacherDelegate().changeTeachersPassword(person.getId(), new String(passwordText.getPassword())); return true; } else return false; } @Override public void done() { stopProgress(); try { if (!get()) { JOptionPane.showMessageDialog(null, "Podane hasła różnią się", "Błąd zmiany hasła", JOptionPane.ERROR_MESSAGE); parent.showDialog(); } } catch (HeadlessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package geeksforgeeks.mustdo; import java.util.Scanner; /** * Created by joetomjob on 12/6/18. */ public class MissingNumberArray { private static void missingnumber(int[]inp, int n){ int sum = (n*(n+1))/2; int s = 0; for (int i = 0; i < n-2; i++) { s += inp[i]; } System.out.println(sum-s); } public static void main(String[] args) { Scanner s = new Scanner(System.in); int test = s.nextInt(); for(int i = 0;i<test;i++){ int n = s.nextInt(); int[] inp =new int[n]; for(int j = 0;j< n-1; j++){ inp[j] = s.nextInt(); } missingnumber(inp,n); } } }
package mygroup; // 参考资料: https://blog.csdn.net/sgbfblog/article/details/8001651 // 6*(5+(2+3)*8+3) 的后缀表达式为: |6523+8*+3+* ,求值=288 // a + b*c + (d * e + f) * g 的后缀表达式为 abc*+de*f+g*+ import java.util.Scanner; import java.util.Stack; enum Operator { NON(' ', 0), ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2), LEFT('(', 3), RIGHT(')', 4); // should process stack immediately! private char op; private int priority; private Operator(char o, int p) { op = o; priority = p; } public char getOp() { return op; } public static Operator valueOf(char c) { switch(c) { case '+': return ADD; case '-': return SUB; case '*': return MUL; case '/': return DIV; case '(': return LEFT; case ')': return RIGHT; default: System.err.println("case value invalid"); System.exit(1); } return NON; } @Override public String toString() { return op + ", " + priority; } public boolean lessEqual(Operator o) { return priority <= o.priority; } } public class ReversePolishExpression { // 得到一个中缀表达式 infix expression 的后缀(逆波兰)表达式 suffix expression private Stack<Operator> stack; private Stack<Character> post; private boolean isOperator(char c) { switch(c) { case '+': case '-': case '*': case '/': case '(': case ')': return true; default: return false; } } private int evaluate() { if (!Character.isDigit(post.firstElement())) { return 0; } // 如果 operand 的 post 不是字母而是具体数字,对后缀表达式求值 System.out.println("开始求值"); Stack<Integer> si = new Stack<Integer>(); // 结果栈 for (Character c : post) { if (Character.isDigit(c)) { si.push(Character.getNumericValue(c)); } else { int op2 = si.pop(); int op1 = si.pop(); switch(c) { case '+': si.push(op1 + op2); break; case '-': si.push(op1 - op2); break; case '*': si.push(op1 * op2); break; case '/': si.push(op1 / op2); break; default: System.err.println("case value invalid"); System.exit(1); } } for (int i : si) { System.out.print(i + ","); } System.out.println(); } assert si.size() == 1; return si.pop(); } private void processOperator(char c) { Operator op = Operator.valueOf(c); if (stack.empty() || op.equals(Operator.LEFT)) { // 先判断是否左右括号 stack.push(op); return; } Operator top = stack.peek(); if (op.equals(Operator.RIGHT)) { // 栈顶操作符依次出栈,直到左括号出栈为止 while(! top.equals(Operator.LEFT)) { post.push(stack.pop().getOp()); top = stack.peek(); if (top == null) { System.out.println("错误: 没有找到匹配的左括号,栈已清空"); System.exit(1); } } assert stack.peek() == Operator.LEFT; stack.pop(); // 去掉左括号 return; } // 判断操作符 if (top.lessEqual(op)) { //直接入栈 stack.push(op); } else { // stack 栈顶操作符依次出栈,直到栈顶元素的优先级小于op while (op.lessEqual(top) && top != Operator.LEFT) { post.push(stack.pop().getOp()); if (stack.empty()) { break; } top = stack.peek(); } // 然后将op入栈 stack.push(op); } } private void processOperand(char c) { // 遇到操作数,直接输出到 post post.push(c); } public ReversePolishExpression() { stack = new Stack<Operator>(); post = new Stack<Character>(); } public boolean processLine(String infix) { for (char c : infix.toCharArray()) { if (Character.isSpaceChar(c)) { continue; } if (isOperator(c)) { processOperator(c); } else { processOperand(c); } System.out.print(c + " | "); print(); } while (!stack.empty()) { post.push(stack.pop().getOp()); } int sum = evaluate(); System.out.println("sum = " + sum); return true; } public void print() { for (Operator o : stack) { System.out.print(o.getOp()); } System.out.print('|'); for (char c : post) { System.out.print(c); } System.out.println(); } public void clear() { stack.clear(); post.clear(); } public static void main(String[] args) { // 简化版本: 每个操作数都是用字母表示 ReversePolishExpression solver = new ReversePolishExpression(); Scanner sc = new Scanner(System.in); while(true) { System.out.print("输入中缀表达式(直接回车可结束程序): "); String infix = sc.nextLine(); if (infix.isEmpty()) { break; } solver.processLine(infix); System.out.print(", 后缀表达式为: "); solver.print(); solver.clear(); } sc.close(); } }
package it.unical.asd.group6.computerSparePartsCompany.data.dao; import it.unical.asd.group6.computerSparePartsCompany.data.entities.ProductionHouse; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface ProductionHouseDao extends JpaRepository<ProductionHouse,Long>, JpaSpecificationExecutor<ProductionHouse> { Optional<ProductionHouse> findByName(String name); @Query("SELECT DISTINCT h.name FROM ProductionHouse h") List<String> getNames(); }
package in.bhargavrao.stalker.entities; import java.util.ArrayList; import java.util.List; public class SuccessMessage extends Message{ List<Item> items; Integer quota; public SuccessMessage(){ items = new ArrayList<Item>(); } public SuccessMessage(List<Item> items, Integer quota) { this.items = items; this.quota = quota; } public Integer getQuota() { return quota; } public void setQuota(Integer quota) { this.quota = quota; } public void addItem(Item item){ this.items.add(item); } public List<Item> getItems(){ return items; } @Override public String toString() { return "SuccessMessage{" + "items=" + items + ", quota=" + quota + '}'; } }
import java.util.Arrays; import java.util.Scanner; /* Name of the class has to be "Main" only if the class is public. */ public class Pyramid { public static void main (String[] args) throws java.lang.Exception { Scanner console=new Scanner(System.in); int number =Integer.parseInt(console.nextLine()); String n=console.nextLine(); int first =Integer.parseInt(n.trim()); String result=first+ ", "; int count=1; for(int i=1;i<number;i++){ String s=console.nextLine(); String [] input=s.trim().split("[ ]+"); int [] arr=new int[input.length]; for(int j=0;j<input.length;j++){ arr[j]=Integer.parseInt(input[j]);; } Arrays.sort(arr); for (int anArr : arr) { if (anArr >= first + 1) { result += anArr + ", "; first = anArr; count++; break; } } } System.out.print(result.substring(0,result.length()-2)); System.out.println(); } }
package top.zeroyiq.master_help_me.utils; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by ZeroyiQ on 2017/9/4. */ public class OkHttpUtils { private void sendOkHttpRequest(String address, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(address) .build(); client.newCall(request).enqueue(callback); } }
package com.tencent.mm.plugin.sight.decode.a; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.view.View; import com.tencent.mm.plugin.sight.decode.a.b.k; class b$k$1 implements Runnable { final /* synthetic */ View eHJ; final /* synthetic */ Bitmap ndf; final /* synthetic */ k ndg; b$k$1(k kVar, View view, Bitmap bitmap) { this.ndg = kVar; this.eHJ = view; this.ndf = bitmap; } public final void run() { this.eHJ.setBackgroundDrawable(new BitmapDrawable(this.ndf)); } }
package Common.Message; import java.net.InetAddress; /** * @File : MessageDelayRequest.java * @Author(s) : Michael Brouchoud & Thomas Lechaire * @Date : 17.10.2018 * * @Goal : Define message * * @Comment(s) : - */ public abstract class Message { public static int MESSAGE_SIZE = Byte.SIZE + Byte.SIZE + Long.SIZE; private byte type; private byte id; private long time; private InetAddress receivedPacketAddress; private int receivedPacketPort; protected Message(byte type, byte id, long time, InetAddress receivedPacketAddress, int receivedPacketPort) { this(type, id, time); this.receivedPacketAddress = receivedPacketAddress; this.receivedPacketPort = receivedPacketPort; } protected Message(byte type, byte id, long time) { this.type = type; this.id = id; this.time = time; } /** * Get message size * @return Message size */ public int getSize() { return MESSAGE_SIZE; } /** * Get message type * @return Message type */ public byte getType() { return type; } /** * Get message id * @return Message id */ public byte getId() { return id; } /** * Get message time * @return Message time */ public long getTime() { return time; } /** * Get message receive address packet * @return Message receive address packet */ public InetAddress getReceivedPacketAddress() { return receivedPacketAddress; } /** * Get message receive port packet * @return Message receive port packet */ public int getReceivedPacketPort() { return receivedPacketPort; } }
package org.vow.actos.domain.annotation; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.vow.actos.domain.note.Note; import javax.persistence.*; @Getter @Setter @NoArgsConstructor @Entity @Table(name = "annotation") public class Annotation { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String text; @ManyToOne private Note note; public Annotation(String text) { this.text = text; } public static Builder annotation() { return new Builder(); } public static class Builder { private String text; public Builder text(String text) { this.text = text; return this; } public Annotation build() { Annotation annotation = new Annotation(); annotation.setText(text); return annotation; } } }
package com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces; import javax.swing.JLabel; public interface ILabel { JLabel getLabel(String name); }
package com.smxknife.energy.services.consumer; import com.smxknife.energy.services.spi.SayHiService; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.rpc.cluster.support.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author smxknife * 2021/5/24 */ @RestController @RequestMapping("/say") public class SayHiController { // 这里默认指定版本号 // @DubboReference(version = "1.0") // 这里指定轮询,这里的timeout会覆盖provider // @DubboReference(version = "1.0", timeout = 10000, loadbalance = RoundRobinLoadBalance.NAME) // 如果没有指定,使用provider的timeout // @DubboReference(version = "1.0", loadbalance = RoundRobinLoadBalance.NAME) // 指定集群容错 /** * FailoverCluster: 失败自动切换,当出现失败,重试其它服务器。通常用于读操作,但重试会带来更长延迟 */ @DubboReference(version = "1.0", cluster = FailoverCluster.NAME) SayHiService sayHiService; @GetMapping public String say() { return sayHiService.sayHi(); } @GetMapping("to") public String sayTo() { return sayHiService.sayHiTimeout(); } @DubboReference(version = "1.0", cluster = FailoverCluster.NAME) SayHiService failoverSayHiService; @GetMapping("fo") public String sayFailover() { return failoverSayHiService.sayHiFailover(); } @DubboReference(version = "1.0", cluster = FailfastCluster.NAME) SayHiService failfastSayHiService; @GetMapping("ff") public String sayFailfast() { return failfastSayHiService.sayHiFailfast(); } @DubboReference(version = "1.0", cluster = FailsafeCluster.NAME) SayHiService failSafeSayHiService; @GetMapping("fs") public String sayFailSafe() { return failSafeSayHiService.sayHiFailSafe(); } @DubboReference(version = "1.0", cluster = FailbackCluster.NAME) SayHiService failBackSayHiService; @GetMapping("fb") public String sayFailback() { return failBackSayHiService.sayFailback(); } @DubboReference(version = "1.0", cluster = ForkingCluster.NAME) SayHiService forkingSayHiService; @GetMapping("fc") public String sayForking() { return forkingSayHiService.sayHiForking(); } @DubboReference(version = "1.0", cluster = "broadcast") SayHiService broadcastSayHiService; @GetMapping("b") public String sayBroadcast() { return broadcastSayHiService.sayHiBroadcast(); } @DubboReference(version = "1.0", timeout = 5000, mock = "com.smxknife.energy.services.consumer.MockSayHiService") SayHiService callMockSayHiService; @GetMapping("mock") public String mockSay() { return callMockSayHiService.sayHi(); } }
// 消费者:姓名+账户(检查+存储) package Banking5_2; public class Customer { private String firstName; private String lastName; private SavingAccount sa; private CheckingAccount ca; public Customer(String f, String l) { this.firstName = f; this.lastName = l; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public SavingAccount getSaving() { return sa; } public CheckingAccount getChecking() { return ca; } public void setSaving(SavingAccount sa) { this.sa = sa; } public void setChecking(CheckingAccount ca) { this.ca = ca; } }
package com.diozero.devices; /*- * #%L * Organisation: diozero * Project: diozero - Core * Filename: SevenSegmentDisplay.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import java.util.Arrays; import com.diozero.api.DeviceInterface; import com.diozero.api.DigitalOutputDevice; import com.diozero.internal.spi.GpioDeviceFactoryInterface; import com.diozero.sbc.DeviceFactoryHelper; /** * <p> * Multi-digit 7-segment display. Tested with this <a href= * "https://cdn-shop.adafruit.com/datasheets/865datasheet.pdf">Luckylight * model</a> from <a href= * "https://shop.pimoroni.com/products/7-segment-clock-display-0-56-digit-height?variant=31551016894547">Pimoroni</a>. * </p> * * <p> * Segments are assumed to be connected in the following order. Note decimal * point (DP) and colon (Col) not yet implemented. Connect each segment via a * current limiting resistor, e.g. 220 or 330 Ohms. * </p> * * Link: * https://www.electronics-tutorials.ws/blog/7-segment-display-tutorial.html * * <pre> * A * F B Col * G * E C Col * D DP * </pre> */ public class SevenSegmentDisplay implements DeviceInterface { private static final boolean[][] NUMBERS = { // { true, true, true, true, true, true, false }, // 0 { false, true, true, false, false, false, false }, // 1 { true, true, false, true, true, false, true }, // 2 { true, true, true, true, false, false, true }, // 3 { false, true, true, false, false, true, true }, // 4 { true, false, true, true, false, true, true }, // 5 { true, false, true, true, true, true, true }, // 6 { true, true, true, false, false, false, false }, // 7 { true, true, true, true, true, true, true }, // 8 { true, true, true, true, false, true, true }, // 9 }; // Length 7 - one for each segment private DigitalOutputDevice[] segments; private DigitalOutputDevice decimalPoint; private DigitalOutputDevice semicolon; // Control which digit is displayed, arbitrary length private DigitalOutputDevice[] digitControl; public SevenSegmentDisplay(int aGpio, int bGpio, int cGpio, int dGpio, int eGpio, int fGpio, int gGpio, int[] digitControlGpios) { this(DeviceFactoryHelper.getNativeDeviceFactory(), aGpio, bGpio, cGpio, dGpio, eGpio, fGpio, gGpio, digitControlGpios); } public SevenSegmentDisplay(GpioDeviceFactoryInterface deviceFactory, int aGpio, int bGpio, int cGpio, int dGpio, int eGpio, int fGpio, int gGpio, int[] digitControlGpios) { // TODO Include DP and Colon segments = new DigitalOutputDevice[7]; int i = 0; segments[i++] = new DigitalOutputDevice(deviceFactory, aGpio, true, false); segments[i++] = new DigitalOutputDevice(deviceFactory, bGpio, true, false); segments[i++] = new DigitalOutputDevice(deviceFactory, cGpio, true, false); segments[i++] = new DigitalOutputDevice(deviceFactory, dGpio, true, false); segments[i++] = new DigitalOutputDevice(deviceFactory, eGpio, true, false); segments[i++] = new DigitalOutputDevice(deviceFactory, fGpio, true, false); segments[i++] = new DigitalOutputDevice(deviceFactory, gGpio, true, false); digitControl = new DigitalOutputDevice[digitControlGpios.length]; for (i = 0; i < digitControlGpios.length; i++) { digitControl[i] = new DigitalOutputDevice(deviceFactory, digitControlGpios[i], false, false); } } @Override public void close() { Arrays.asList(digitControl).forEach(DeviceInterface::close); Arrays.asList(segments).forEach(DeviceInterface::close); } public void displayNumbers(int value, boolean[] onDigits) { if (onDigits.length > digitControl.length) { throw new IllegalArgumentException("Too many digits specified (" + onDigits.length + "), array length must be 1.." + digitControl.length); } if (value > NUMBERS.length - 1) { throw new IllegalArgumentException("Invalid value " + value + " - only numbers 0..9 are supported"); } for (int i = 0; i < digitControl.length; i++) { digitControl[i].setOn(onDigits[i]); } boolean[] values = NUMBERS[value]; for (int i = 0; i < segments.length; i++) { segments[i].setOn(values[i]); } } public void enableDigit(int digit) { for (int i = 0; i < digitControl.length; i++) { digitControl[i].setOn(i == digit); } } public void displayNumber(int value) { if (value > NUMBERS.length - 1) { throw new IllegalArgumentException("Invalid value " + value + " - only numbers 0..9 are supported"); } boolean[] values = NUMBERS[value]; for (int i = 0; i < segments.length; i++) { segments[i].setOn(values[i]); } } public void display(boolean[] values) { if (values.length != segments.length) { throw new IllegalArgumentException( "Invalid values array length (" + values.length + ") - must be " + segments.length); } for (int i = 0; i < segments.length; i++) { segments[i].setOn(values[i]); } } }
package cqu; import javax.swing.ImageIcon; public class IconResource { public static ImageIcon dirIcon =new ImageIcon("src/Icon/folder.png"); public static ImageIcon fileIcon = new ImageIcon("src/Icon/file.png"); public static ImageIcon javaIcon = new ImageIcon("src/Icon/java.png"); }
package com.jkb.yanolja.domain.reservation.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Builder public class ResReqDto { String motelId; String userId; String typeListId; String checkin_input; String checkin_inputT; String checkout_input; String checkout_inputT; String usernickname; String userphone; String cars; String lodgment; }
public class TestI { public static void main(String[] args) { Stud s=new Stud(); Lays l=new Lays(); s.EatChips(l); Kurkure k=new Kurkure(); s.EatChips(k); } }
package monopoly.model.bank; import monopoly.model.Owner; import monopoly.model.field.Property; public interface Bank extends Owner { int getMoney(); int getHotelCount(); int getHouseCount(); boolean canGiveBuilding(Property propToUpgrade); void addHouse(int count); void takeHouse(int count); void addHotel(int count); void takeHotel(int count); }
public class RemoveUserAccountControl { private DataManager dm; private LoginControl loginControl; private UserObject currentUser; public RemoveUserAccountControl(DataManager d, LoginControl lc) { this.dm = d; this.loginControl = lc; } public boolean handleRemoveUserAccount() { currentUser = loginControl.getUser(); if(currentUser!=null) {// check if logged in String userId = currentUser.uID; // dm.removeUser(userId); // remove the account return true; } return false; } }
package com.example.world.dao; import java.util.Collection; import java.util.Set; import com.example.world.entity.Country; public interface CountryDao extends GenericDao<Country, String> { Collection<Country> getByContinent(String continent); Set<String> getContinents(); }
package com.fish.interfaces; import java.util.List; import com.fish.object.EnemyFish; import android.graphics.Canvas; public interface IMyFish { public float getMiddle_x(); public void setMiddle_x(float middle_x); public float getMiddle_y(); public void setMiddle_y(float middle_y); public boolean isChangeBullet(); public void setChangeBullet(boolean isChangeBullet); public void shoot(Canvas canvas, List<EnemyFish> planes); public void initButtle(); public void changeButtle(); }
public class NewStudent implements Comparable { int english = 0; String name; NewStudent(int e, String n) { english = e; name = n; } public int compareTo(Object b) { NewStudent st = (NewStudent) b; return (this.english - st.english); // 按成绩大小排列对象。 } }
package org.firstinspires.ftc.teamcode_14345.samples; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Gamepad; import java.util.ArrayList; public class TankDriveComponent { private ArrayList<DcMotor> leftMotors; private ArrayList<DcMotor> rightMotors; Gamepad gamepad; public TankDriveComponent() { } public TankDriveComponent(Gamepad gamepad) { this.gamepad = gamepad; } public boolean addLeftMotor(DcMotor motor) { return leftMotors.add(motor); } public boolean addRightMotor(DcMotor motor) { return rightMotors.add(motor); } public void drive() { float leftY = gamepad.left_stick_y; float rightY = gamepad.right_stick_y; for(DcMotor motor : leftMotors) { motor.setPower(leftY); } for(DcMotor motor : rightMotors) { motor.setPower(rightY); } } }
package com.cnk.travelogix.sapintegrations.mappingtable.maintain.data; import com.cnk.travelogix.common.data.Errors; public class Response extends Errors { protected ResponseStatus status; protected String message; protected Failure error; /** * Gets the value of the status property. * * @return possible object is {@link ResponseStatus } * */ public ResponseStatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is {@link ResponseStatus } * */ public void setStatus(final ResponseStatus value) { this.status = value; } /** * Gets the value of the message property. * * @return possible object is {@link String } * */ public String getMessage() { return message; } /** * Sets the value of the message property. * * @param value * allowed object is {@link String } * */ public void setMessage(final String value) { this.message = value; } /** * Gets the value of the error property. * * @return possible object is {@link Failure } * */ public Failure getError() { return error; } /** * Sets the value of the error property. * * @param value * allowed object is {@link Failure } * */ public void setError(final Failure value) { this.error = value; } }
package tools; import java.util.Map; public class MybatisMapper { public static void main(String[] args) { String str = "B_WF_VOUMNG,TRANNO,SERSEQNO,ORGID,BUSICODE,TRANDATE,VOUSOURCE"; String[] s = str.split(","); insert(s); } //mybaties mapper插入映射sql public static void insert(String[] str) { String sql = "INSERT INTO " + str[0]+"(\r"; for (int i = 1; i < str.length; i++) { if(i == 1) { sql +="<if test=\""+str[i]+" != null and " + str[i]+ " !=''\">" + str[i] + "</if>\r"; }else { sql +="<if test=\""+str[i]+" != null and " + str[i]+ " !=''\">," + str[i] + "</if>\r"; } } sql +=")\rVALUES(\r"; for (int i = 1; i < str.length; i++) { if (i == 1) { sql +="<if test=\""+str[i]+" != null and " + str[i]+ " !=''\">#{" + str[i] + "}</if>\r" ; }else { sql +="<if test=\""+str[i]+" != null and " + str[i]+ " !=''\">,#{" + str[i] + "}</if>\r" ; } } sql += ")"; System.out.println(sql); } //mybaties mapper更新映射sql public static void update(String[] str) { String sql = "UPDATE " + str[0] +" SET\r" ; for (int i = 1 ;i < str.length; i++) { if (i == 1) { sql +="<if test=\"" + str[i] + " != null and " + str[i] + " !=''\">" + str[i] + " = #{" + str[i] + "}</if>\r" ; }else { sql +="<if test=\"" + str[i] + " != null and " + str[i] + " !=''\">," + str[i] + " = #{" + str[i] + "}</if>\r" ; } } sql += "WHERE" ; System.out.println(sql); } //mybaties mapper选择映射sql public static void select(String[] str) { String sql = "SELECT"; for (int i = 1 ;i < str.length; i++) { if (i==str.length-1) { sql +=str[i] ; } if (i % 10==0) { sql +="\r" ; }else { sql +=" "+str[i] + ","; } } sql += "WHERE" ; System.out.println(sql); } //实现类获取pool字符串 public static void getPoolString(String[] str) { String s = ""; for (int i = 0 ;i < str.length; i++) { s= "String "+str[i]+" = pool.getString(\""+str[i]+"\");"; System.out.println(s); } } //实现类获取pool字符串写进map public static void mapPut(String[] str) { String s = ""; for (int i = 0 ;i < str.length; i++) { s= "map.put(\"" + str[i] + "\", " + str[i].toLowerCase() + ");"; System.out.println(s); } } }
package com.yuorfei.util; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 缓存工具类 * Created by hxy on 2015/10/17. */ public class CacheUtil { private static final Log log = LogFactory.getLog(CacheUtil.class); /** * 拿到缓存 * @param name 缓存名 * @param key 缓存key * @return object */ public static Object get(String name,String key) { Cache cache = CacheManager.getInstance().getCache(name); if( cache == null ){ log.info("cache is null , name:"+name); return null; } Element element = cache.get(key); if( element==null ){ log.info("cache element is null , name:"+name+" key:"+key); return null; } return element.getObjectValue(); } /** * 设置缓存 * @param name 缓存名字 * @param key 缓存key * @param object 要缓存的对象 */ public static void set(String name,String key,Object object){ Cache cache = CacheManager.getInstance().getCache(name); if( cache==null ){ CacheManager.getInstance().addCache(name); cache = CacheManager.getInstance().getCache(name); } Element element = new Element(key,object); cache.put(element); } /** * 移出缓存 * @param name 缓存名 */ public static void remove(String name){ CacheManager.getInstance().removeCache(name); } public static void remove(String name,String key){ Cache cache = CacheManager.getInstance().getCache(name); cache.remove(key); } }
package quizzlr.user; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; 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 quizzlr.backend.*; /** * Servlet implementation class SendMessage */ @WebServlet("/SendMessage") public class SendMessage extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SendMessage() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession userSession = request.getSession(); User user = (User) userSession.getAttribute("User"); if (user == null) return; int recipientID = Integer.parseInt(request.getParameter("recipient")); User to = User.getUserFromID(recipientID); int messageType = 0; String messageContent = ""; String nextPage = "/"; if (request.getParameter("type").equals("friendRequest")) { List<Message> curMessages = to.getMessages(); for (Message message : curMessages) { if (message.getMessageType() == 1 && message.getFromUser().equals(user)) { RequestDispatcher dispatch = request.getRequestDispatcher("pending.jsp"); dispatch.forward(request, response); return; } } curMessages = user.getMessages(); for (Message message : curMessages) { if (message.getMessageType() == 1 && message.getFromUser().equals(to)) { RequestDispatcher dispatch = request.getRequestDispatcher("pending.jsp"); dispatch.forward(request, response); return; } } messageType = 1; messageContent = ""; nextPage = "requestSent.jsp"; } else if (request.getParameter("type").equals("note")) { messageType = 3; messageContent = request.getParameter("content"); nextPage = "noteSent.jsp"; } Message.sendMessage(user, to, messageType, messageContent); RequestDispatcher dispatch = request.getRequestDispatcher(nextPage); dispatch.forward(request, response); } }
package net.sssanma.mc.custommobs; import net.minecraft.server.v1_7_R4.EntitySkeleton; import net.minecraft.server.v1_7_R4.World; import net.sssanma.mc.utility.NMSUtil; public class ESkeleton extends EntitySkeleton { public ESkeleton(World world) { super(world); NMSUtil.clearAIList(goalSelector); } }
package ak; import java.util.Scanner; public class singledigit { public static void main(String[] args) { int a,i,count=0,m=0,n = 0,p=0,j; Scanner arun=new Scanner(System.in); a=arun.nextInt(); String s=String.valueOf(a); int[] b=new int[s.length()]; for(i=0;i<b.length;i++){ b[i]=Character.getNumericValue(s.charAt(i)); } int[] c=new int[b.length]; int d=c.length; while(d!=2){ for(i=0;i<d-1;i++){ b[i]=b[i]-b[i+1]; b[i]=Math.abs(b[i]); } d--; } System.out.println(b[i]); } }
/** * Model of the jungle game. <br><br> * * General data class of the jungle game including * {@link hk.edu.polyu.comp.comp2021.jungle.model.Board}, * {@link hk.edu.polyu.comp.comp2021.jungle.model.BoardConfiguration} and * {@link hk.edu.polyu.comp.comp2021.jungle.model.Player}. */ package hk.edu.polyu.comp.comp2021.jungle.model;
package br.com.treinarminas.academico.classandobject; public enum DiaSemana { SEGUNDA_FEIRA(false, "Segunda Feira") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }, TERCA_FEIRA(false, "Terça Feira") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }, QUARTA_FEIRA(false, "Quarta Feira") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }, QUINTA_FEIRA(false, "Quinta Feira") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }, SEXTA_FEIRA(false, "Sexta Feira") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }, SABADO(true, "Sábado") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }, DOMINGO(true, "Domingo") { public Boolean ehDiaDeFarra() { return calcularDiaDeFarra(this); } }; private static boolean calcularDiaDeFarra(DiaSemana dia) { return dia.toString().indexOf("_") < 0; } private DiaSemana(Boolean finalDeSemana, String descricao) { this.finalDeSemana = finalDeSemana; this.descricao = descricao; } public abstract Boolean ehDiaDeFarra(); private Boolean finalDeSemana; private String descricao; public Boolean getFinalDeSemana() { return finalDeSemana; } public String getDescricao() { return descricao; } }
package busterminal; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.locks.ReentrantLock; public class TicketPurchasing{ // ticketMachine tMachine = new ticketMachine(); // ticketCounter1 tCounter1 = new ticketCounter1(); // ticketCounter2 tCounter2 =new ticketCounter2(); // ExecutorService allTickets = Executors.newFixedThreadPool(3); } class ticket { int ticketID; public ticket(){} public ticket(int ticketID) { this.ticketID = ticketID; } } class ticketMachine{ ExecutorService tickMachine = Executors.newSingleThreadExecutor(); tMachinePrinter tickMPrinter = new tMachinePrinter(); private static final ReentrantLock tMachineLock = new ReentrantLock(true); //to ensure fairness to tackle starvation ticket ticket; protected ticket buyMTicket(customer cust ) throws InterruptedException, ExecutionException{ tMachineLock.lock(); try{ Random rnd = new Random(); boolean down = rnd.nextDouble() <= 0.2; if (down) { System.out.println("\n\n\t\tSorry Customer # " + cust.id + "...Ticket Machine is Down!....\n"); Thread.sleep(250); System.out.println("\n\tYes, Ticket Machine has been is fixed"); // int getTicketFrom = (int )( 1 + Math.random() *2 ); //send customers to booth } System.out.println("\n\tCustomer # " + cust.id + " is now using the Ticket Machine..."); Future<ticket> newTicket = tickMachine.submit(tickMPrinter); Thread.sleep(500); if(newTicket.isDone()){ System.out.println("\n\t\tCustomer # " + cust.id + " got a ticketID: " + newTicket.get().ticketID); ticket = newTicket.get(); } else{ System.out.println("\n\tCustomer # " + cust.id + " did not get a ticket..."); } } finally{ tMachineLock.unlock(); } return ticket; } private class tMachinePrinter implements Callable<ticket>{ @Override public synchronized ticket call() throws Exception { int ticketID = (int )( 1 + Math.random() *3); ticket ticket = new ticket(ticketID); return ticket; } } } class ticketCounter1{ ExecutorService tickCounter1 = Executors.newSingleThreadExecutor(); tCounterPrinter tickC1Printer = new tCounterPrinter(); private static final ReentrantLock tCounter1Lock = new ReentrantLock(true); ticket ticket = null; protected ticket buyC1Ticket(customer cust) throws InterruptedException, ExecutionException{ tCounter1Lock.lock(); try{ Random rnd = new Random(); boolean bbreak = rnd.nextDouble() <= 0.1; if (bbreak) { System.out.println("\n\n\t\tSorry Customer # " + cust.id+ " Counter 1 Personnel is on break!....will be back Shortly\n"); Thread.sleep(250); } System.out.println("\n\tCustomer # " + cust.id+ " is now at Ticket Counter 1..."); Future<ticket> newTicket = tickCounter1.submit(tickC1Printer); Thread.sleep(500); if(newTicket.isDone()){ System.out.println("\n\t\tCustomer # " + cust.id+ " got a ticketID: " + newTicket.get().ticketID); ticket = newTicket.get(); } else{ System.out.println("\n\tCustomer # " + cust.id + " did not get a ticket..."); } } finally{ tCounter1Lock.unlock(); } return ticket; } } //Counter 2 class to get a ticket from the counter class ticketCounter2 { ExecutorService tickCounter2 = Executors.newSingleThreadExecutor(); tCounterPrinter tickC2Printer = new tCounterPrinter(); private static final ReentrantLock tCounter2Lock = new ReentrantLock(true); ticket ticket = null; protected ticket buyC2Ticket(customer cust) throws InterruptedException, ExecutionException{ tCounter2Lock.lock(); try{ Random rnd = new Random(); boolean bbreak = rnd.nextDouble() <= 0.1; if (bbreak) { System.out.println("\n\n\t\tSorry Customer # " + cust.id + " Counter 2 Personnel is on break!.....will be back Shortly\n"); Thread.sleep(250); } System.out.println("\n\tCustomer # " + cust.id + " is now at Ticket Counter 2..."); Future<ticket> newTicket = tickCounter2.submit(tickC2Printer); Thread.sleep(500); if(newTicket.isDone()){ System.out.println("\n\t\tCustomer # " + cust.id + " got a ticketID: " + newTicket.get().ticketID); ticket = newTicket.get(); } else{ System.out.println("\n\tCustomer # " + cust.id + " did not get a ticket..."); } } finally{ tCounter2Lock.unlock(); } return ticket; } } class tCounterPrinter implements Callable<ticket>{ @Override public synchronized ticket call() throws Exception { //Only one counter has access to the ticket printer at a time int ticketID = (int )( 1 + Math.random() * 3); ticket ticket = new ticket(ticketID); return ticket; } } //Ways to handle customer queue: 1TMachine 1TCounter,Randomly here and there, //or based on the number in the queue of TM //Ticket passed to customer callable future with id 1,2, or 3 for waiting area //periodicaly break one down or Random rand = new Random (); //if it is true, we get a ticket //if false returns null and the ticket machine is down //should send customer to counter and vice versa //*All 3 of Ticket MC passed to a fixed thread pool of 3 (break them with intervals in each obj) //Ticket Counter (2 shared): Employee short toilet breaks (timer-task) //*Calable & Future to generate the tickets & based on ticket number returned (1+ (rand () %3)) go to
package cn.com.ykse.santa.service.impl; import cn.com.ykse.santa.repository.dao.ActivityDOMapper; import cn.com.ykse.santa.repository.entity.ActivityDO; import cn.com.ykse.santa.service.ActivityService; import cn.com.ykse.santa.service.convertor.BaseConvertor; import cn.com.ykse.santa.service.util.DateUtil; import cn.com.ykse.santa.service.vo.ActivityVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by youyi on 2016/2/15. */ @Service public class ActivityServiceImpl implements ActivityService { @Autowired ActivityDOMapper activityDOMapper; @Override public List<ActivityVO> getActivityListByDate(String date) throws Exception { Date beginDate=DateUtil.parseDateTime(date+" 00:00:00"); Date endDate=getNextDate(date); List<ActivityDO> list = activityDOMapper.selectActivitiesBetweenDate(beginDate,endDate); List<ActivityVO> vos=new ArrayList<>(); for(ActivityDO dO : list){ ActivityVO vo= BaseConvertor.convert(dO,ActivityVO.class); vo.setDateTime(DateUtil.formatDateTime(dO.getDate())); vos.add(vo); } return vos; } private Date getNextDate(String date) throws Exception{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); c.setTime(sdf.parse(date)); c.add(Calendar.DATE, 1); date = sdf.format(c.getTime()); return DateUtil.parseDateTime(date+" 00:00:00"); } @Override public boolean addActivity(String msg) { ActivityDO dO=new ActivityDO(); dO.setMsg(msg); int count=activityDOMapper.insert(dO); return count>0 ? true : false; } }