blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
sequencelengths
1
1
author
stringlengths
0
161
154147b8410f32e03f6e0747e4d43151602859a9
97bde7638a5d921903134b4902048866b89a6a9e
/app/src/main/java/com/shen/baidu/doglost/ui/dialog/FenceCreateDialog.java
4506a3884d51afac3c69554f55347514882b03b1
[]
no_license
sxysxys/doglost
640f70e883347d561dda7ab5436ace9363fc82b0
334aa06e24bd088361d1582a2f9bd7f098ad3a9a
refs/heads/master
2022-12-28T11:58:13.299988
2020-10-16T09:26:16
2020-10-16T09:26:16
294,704,378
3
0
null
null
null
null
UTF-8
Java
false
false
3,524
java
package com.shen.baidu.doglost.ui.dialog; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.shen.baidu.doglost.R; import com.shen.baidu.doglost.constant.FenceShape; /** * 围栏创建对话框 */ public class FenceCreateDialog extends Dialog implements View.OnClickListener { /** * 回调接口 */ private Callback callback; private View fenceRadiusLayout; private Button cancelBtn; private Button sureBtn; private TextView titleText; private EditText fenceRadiusText; private FenceShape fenceShape = FenceShape.circle; /** * 默认圆形围栏参数 */ private double radius = 100; public FenceCreateDialog(Context activity, Callback callback) { super(activity, android.R.style.Theme_Holo_Light_Dialog); this.callback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog_fence_create); fenceRadiusLayout = findViewById(R.id.layout_fenceCreate_radius); titleText = (TextView) findViewById(R.id.tv_fenceCreate_title); fenceRadiusText = (EditText) findViewById(R.id.edtTxt_fenceCreate_radius); cancelBtn = (Button) findViewById(R.id.btn_fenceCreate_cancel); sureBtn = (Button) findViewById(R.id.btn_fenceCreate_sure); cancelBtn.setOnClickListener(this); sureBtn.setOnClickListener(this); } /** * 在调用show()的时候进入这个方法。 */ @Override protected void onStart() { switch (fenceShape) { case circle: fenceRadiusLayout.setVisibility(View.VISIBLE); break; case polygon: titleText.setText(R.string.fence_create_polygon); fenceRadiusLayout.setVisibility(View.GONE); break; default: break; } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_fenceCreate_cancel: dismiss(); if (null != callback) { callback.onCancelCallback(); } break; case R.id.btn_fenceCreate_sure: String radiusStr = fenceRadiusText.getText().toString(); if (!TextUtils.isEmpty(radiusStr)) { try { radius = Double.parseDouble(radiusStr); } catch (Exception ex) { ex.printStackTrace(); } } if (null != callback) { callback.onSureCallback(radius); } dismiss(); break; default: break; } } public void setFenceShape(FenceShape fenceShape) { this.fenceShape = fenceShape; } /** * 创建回调接口 */ public interface Callback { /** * 确定回调 */ void onSureCallback(double radius); /** * 取消回调 */ void onCancelCallback(); } }
c639a8cc0483ff537f871ae3167bd2562c105013
c05ef7bb9cf5eeb50f233531ee63fae5a2e2210d
/15. 3Sum.java
176888dc51a97a3f4f96c679c908ca4be9b23ba6
[]
no_license
ck1994125/leetcode
0de3a4912ae515774ab05fb141c82beb9f3b4510
9e23af0eadece65ff8aa5e4f5f743b254daf4154
refs/heads/master
2021-09-06T08:34:35.734606
2018-02-04T10:57:27
2018-02-04T10:57:27
108,250,034
0
0
null
null
null
null
UTF-8
Java
false
false
1,629
java
/* 题目: 15. 3Sum Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 分析: 时间复杂度:O(n2) 先排序,然后两层循环 第一层循环依次遍历每个数; 第二次循环从两侧向中间夹逼遍历。 注意: 1.注意越过相等数值,否则结果会有重复(第一层和第二层都是) */ class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res_set = new ArrayList<>(); Arrays.sort(nums); for ( int i=0 ; i<nums.length ; i++ ){ if ( nums[i]>0 ) break; if ( i!=0 && nums[i] == nums[i-1]) continue; for ( int j=i+1 , k=nums.length-1 ; j<k ; ){ int obj = -nums[i]; List<Integer> res = new ArrayList<Integer>(); if( nums[j]+nums[k] > obj ){ k--; while( k>j && nums[k] == nums[k+1] ) k--; } else if( nums[j]+nums[k] < obj ){ j++; while( j<k && nums[j] == nums[j-1] ) j++; } else{ res.add(nums[i]); res.add(nums[j]); res.add(nums[k]); res_set.add(res); j++;k--; while( j<k && nums[k] == nums[k+1] && nums[j] == nums[j-1]){ j++;k--; } } } } return res_set; } }
16724e064beed813b70b5354120114daa49d0e94
6a54c399f150a14939b540129fe6ee13d65d8c3d
/server/src/main/java/com/ljy/mrg/ChannelWriteMrg.java
16c30be9379085b6acd648f06fb997da0c61b83c
[]
no_license
liujinyonggiyt/temperature
2b24871d1a9a87f783708a7ed097421052e60e8f
ad0418f185bb8479af811d6c37ba1a471b27dec6
refs/heads/master
2022-06-22T14:45:20.511815
2019-07-03T10:40:25
2019-07-03T10:40:25
182,944,999
0
1
null
2019-10-31T00:42:36
2019-04-23T06:06:23
Java
UTF-8
Java
false
false
1,084
java
package com.ljy.mrg; import com.google.inject.Inject; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; /** * Created by lishile * 写channel的管理器,作为向channel中发送消息的统一接口 */ public class ChannelWriteMrg { private long totalSendNum=0; private int onSecondSendNum =0; @Inject public ChannelWriteMrg() { } public ChannelFuture write(Channel channel, Object proto) { ++onSecondSendNum; ++totalSendNum; return channel.write(proto); } public ChannelFuture writeAndFlush(Channel channel, Object proto) { ++onSecondSendNum; ++totalSendNum; return channel.writeAndFlush(proto); } public long getTotalSendNum() { return totalSendNum; } public void setTotalSendNum(long totalSendNum) { this.totalSendNum = totalSendNum; } public int getOnSecondSendNum() { return onSecondSendNum; } public void setOnSecondSendNum(int onSecondSendNum) { this.onSecondSendNum = onSecondSendNum; } }
5b9e55922fba258415687ef772cafce2e54859c4
357901589108781b0885ee437971aeaa1b545b10
/app/src/main/java/com/cdt/bombeachguide/ui/HorizontalListView.java
caa86991f6c1d748b7eafa8e511722502c89e8a8
[]
no_license
trangminie/BomBeachGuide
3e43515ef5a79b4fdd47c893d2b9a329430f2a75
8c72d514c10eed664077669c2fc144e59eea86cc
refs/heads/master
2020-12-27T09:32:12.020095
2016-06-21T13:42:45
2016-06-21T13:42:45
58,939,586
0
0
null
null
null
null
UTF-8
Java
false
false
10,806
java
package com.cdt.bombeachguide.ui; /** * Created by Trang on 5/31/2015. */ import android.content.Context; import android.database.DataSetObserver; import android.graphics.Rect; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.Scroller; import java.util.LinkedList; import java.util.Queue; public class HorizontalListView extends AdapterView<ListAdapter> { public boolean mAlwaysOverrideTouch = true; protected ListAdapter mAdapter; private int mLeftViewIndex = -1; private int mRightViewIndex = 0; protected int mCurrentX; protected int mNextX; private int mMaxX = Integer.MAX_VALUE; private int mDisplayOffset = 0; protected Scroller mScroller; private GestureDetector mGesture; private Queue<View> mRemovedViewQueue = new LinkedList<View>(); private OnItemSelectedListener mOnItemSelected; private OnItemClickListener mOnItemClicked; private OnItemLongClickListener mOnItemLongClicked; private boolean mDataChanged = false; public HorizontalListView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private synchronized void initView() { mLeftViewIndex = -1; mRightViewIndex = 0; mDisplayOffset = 0; mCurrentX = 0; mNextX = 0; mMaxX = Integer.MAX_VALUE; mScroller = new Scroller(getContext()); mGesture = new GestureDetector(getContext(), mOnGesture); } @Override public void setOnItemSelectedListener(OnItemSelectedListener listener) { mOnItemSelected = listener; } @Override public void setOnItemClickListener(OnItemClickListener listener){ mOnItemClicked = listener; } @Override public void setOnItemLongClickListener(OnItemLongClickListener listener) { mOnItemLongClicked = listener; } private DataSetObserver mDataObserver = new DataSetObserver() { @Override public void onChanged() { synchronized(HorizontalListView.this){ mDataChanged = true; } invalidate(); requestLayout(); } @Override public void onInvalidated() { reset(); invalidate(); requestLayout(); } }; @Override public ListAdapter getAdapter() { return mAdapter; } @Override public View getSelectedView() { //TODO: implement return null; } @Override public void setAdapter(ListAdapter adapter) { if(mAdapter != null) { mAdapter.unregisterDataSetObserver(mDataObserver); } mAdapter = adapter; mAdapter.registerDataSetObserver(mDataObserver); reset(); } private synchronized void reset(){ initView(); removeAllViewsInLayout(); requestLayout(); } @Override public void setSelection(int position) { //TODO: implement } private void addAndMeasureChild(final View child, int viewPos) { LayoutParams params = child.getLayoutParams(); if(params == null) { params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); } addViewInLayout(child, viewPos, params, true); child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST)); } @Override protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if(mAdapter == null){ return; } if(mDataChanged){ int oldCurrentX = mCurrentX; initView(); removeAllViewsInLayout(); mNextX = oldCurrentX; mDataChanged = false; } if(mScroller.computeScrollOffset()){ int scrollx = mScroller.getCurrX(); mNextX = scrollx; } if(mNextX <= 0){ mNextX = 0; mScroller.forceFinished(true); } if(mNextX >= mMaxX) { mNextX = mMaxX; mScroller.forceFinished(true); } int dx = mCurrentX - mNextX; removeNonVisibleItems(dx); fillList(dx); positionItems(dx); mCurrentX = mNextX; if(!mScroller.isFinished()){ post(new Runnable(){ @Override public void run() { requestLayout(); } }); } } private void fillList(final int dx) { int edge = 0; View child = getChildAt(getChildCount()-1); if(child != null) { edge = child.getRight(); } fillListRight(edge, dx); edge = 0; child = getChildAt(0); if(child != null) { edge = child.getLeft(); } fillListLeft(edge, dx); } private void fillListRight(int rightEdge, final int dx) { while(rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) { View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this); addAndMeasureChild(child, -1); rightEdge += child.getMeasuredWidth(); if(mRightViewIndex == mAdapter.getCount()-1) { mMaxX = mCurrentX + rightEdge - getWidth(); } if (mMaxX < 0) { mMaxX = 0; } mRightViewIndex++; } } private void fillListLeft(int leftEdge, final int dx) { while(leftEdge + dx > 0 && mLeftViewIndex >= 0) { View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this); addAndMeasureChild(child, 0); leftEdge -= child.getMeasuredWidth(); mLeftViewIndex--; mDisplayOffset -= child.getMeasuredWidth(); } } private void removeNonVisibleItems(final int dx) { View child = getChildAt(0); while(child != null && child.getRight() + dx <= 0) { mDisplayOffset += child.getMeasuredWidth(); mRemovedViewQueue.offer(child); removeViewInLayout(child); mLeftViewIndex++; child = getChildAt(0); } child = getChildAt(getChildCount()-1); while(child != null && child.getLeft() + dx >= getWidth()) { mRemovedViewQueue.offer(child); removeViewInLayout(child); mRightViewIndex--; child = getChildAt(getChildCount()-1); } } private void positionItems(final int dx) { if(getChildCount() > 0){ mDisplayOffset += dx; int left = mDisplayOffset; for(int i=0;i<getChildCount();i++){ View child = getChildAt(i); int childWidth = child.getMeasuredWidth(); child.layout(left, 0, left + childWidth, child.getMeasuredHeight()); left += childWidth + child.getPaddingRight(); } } } public synchronized void scrollTo(int x) { mScroller.startScroll(mNextX, 0, x - mNextX, 0); requestLayout(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean handled = super.dispatchTouchEvent(ev); handled |= mGesture.onTouchEvent(ev); return handled; } protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { synchronized(HorizontalListView.this){ mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0); } requestLayout(); return true; } protected boolean onDown(MotionEvent e) { mScroller.forceFinished(true); return true; } private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return HorizontalListView.this.onDown(e); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return HorizontalListView.this.onFling(e1, e2, velocityX, velocityY); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { synchronized(HorizontalListView.this){ mNextX += (int)distanceX; } requestLayout(); return true; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { for(int i=0;i<getChildCount();i++){ View child = getChildAt(i); if (isEventWithinView(e, child)) { if(mOnItemClicked != null){ mOnItemClicked.onItemClick(HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i )); } if(mOnItemSelected != null){ mOnItemSelected.onItemSelected(HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i )); } break; } } return true; } @Override public void onLongPress(MotionEvent e) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (isEventWithinView(e, child)) { if (mOnItemLongClicked != null) { mOnItemLongClicked.onItemLongClick(HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i)); } break; } } } private boolean isEventWithinView(MotionEvent e, View child) { Rect viewRect = new Rect(); int[] childPosition = new int[2]; child.getLocationOnScreen(childPosition); int left = childPosition[0]; int right = left + child.getWidth(); int top = childPosition[1]; int bottom = top + child.getHeight(); viewRect.set(left, top, right, bottom); return viewRect.contains((int) e.getRawX(), (int) e.getRawY()); } }; }
2c5c8198f741a2228d1a2fa8276a582a80a53bc3
82535c75aa9756820b82921054ac9e138485fc81
/src/org/fkit/mapper/AllMapper.java
e419f8283ead036997c86621a2e6bb1c4ae0f4e1
[]
no_license
ganlulululu/6.13nyjd2
812bb53452035bf27d6dada88b599e1bc3bb8a7a
71bea94a4fb0a97f830aa3d2ee79a312ce51104c
refs/heads/master
2021-06-20T15:59:41.422945
2017-06-15T14:06:35
2017-06-15T14:06:35
94,445,406
0
0
null
null
null
null
UTF-8
Java
false
false
2,349
java
package org.fkit.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.fkit.domain.Module; import org.fkit.domain.Nav; import org.fkit.domain.ThirdPage; import org.fkit.domain.WebInfor; import org.fkit.domain.index; public interface AllMapper { @Select("select * from tb_index where name=#{name}") List<index> findWithname(@Param("name") String name); @Select("select * from tb_module where longtitle=#{longtitle}") Module findPictureWithlongtitle(@Param("longtitle") String longtitle); @Select("select * from tb_module where module_id=#{module_id} ORDER BY up_year desc ,up_date desc limit 10") List<Module> findIndexContent(@Param("module_id") String module_id); @Select("select * from tb_module where module_id=#{module_id} ORDER BY up_year desc ,up_date desc limit #{pages},#{pageSize}") List<Module> findPage(@Param("pages")int pages,@Param("pageSize")int pageSize,@Param("module_id")String module_id); @Select("select count(*) from tb_module where module_id=#{module_id}") Integer findModuleAll(@Param("module_id")String module_id); @Select("select * from tb_module where module_id=#{module_id}") List<Module> findWithModuleId(@Param("module_id")String module_id); @Select("select * from tb_module where content_id=#{content_id}") Module findWithContentId(@Param("content_id")Integer content_id); @Select("select *, count(distinct name) from tb_module where whole_name=#{whole_name} and name is not NULL group by name ORDER BY(module_id)") List<Module> findModuleWithWholeName(@Param("whole_name")String whole_name); @Select("select * from tb_nav where name=#{name}") List<Nav> findWithName(@Param("name")String name); @Select("select distinct name from tb_nav") List<String> findAllName(); @Select("select * from ThirdPage where module=#{module}") ThirdPage findWithModule(@Param("module")String module); @Select("select * from ThirdPage where whole_name=#{whole_name}") List<ThirdPage> findWithWholeName(@Param("whole_name")String whole_name); @Select("select * from tb_webInfor") WebInfor findWebInfor(); @Update("update tb_webInfor set online = #{online} WHERE total = #{total}") void updateWebInfor(@Param("online")int online,@Param("total")int total); }
30451e801cf693c26d73dec37552d49044b474a3
eccb54cfec122468d7323232a774c531f78e7962
/app/src/main/java/com/silicontechnnologies/propertymediator/utils/ConnectionDetector.java
fd696c6cce7786a314c7175545e4830ed7c07c0e
[]
no_license
rajajawahar/Property-Mediator-Android
5ebaf63d89b252819f1eec9e060881c38e67aad5
16a02a4829eadb5a8df690e74a61be445429aa6f
refs/heads/master
2020-12-02T06:44:23.586036
2017-07-11T12:55:17
2017-07-11T12:55:17
96,891,653
0
0
null
null
null
null
UTF-8
Java
false
false
932
java
package com.silicontechnnologies.propertymediator.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context){ this._context = context; } public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } return false; } }
f733646d0029df92c323f5a9b1b1bed2f19eed82
d864d9d358e35566a35ba800b81445eea0400a23
/HelloWorld/src/bussireisid/Reisija.java
fa2f006e7ecc2a5c157bee72a63253de7652adbc
[]
no_license
Ramses-Laursoo/java-KonsjaHar
12429d24c15a583dd265c793f51b20afcf7286db
edf1fb1c2eaf5fa2b669119654c98b6b8996f2a9
refs/heads/main
2023-07-25T18:23:54.129662
2021-09-02T10:50:11
2021-09-02T10:50:11
402,382,710
0
0
null
null
null
null
ISO-8859-2
Java
false
false
410
java
//Koostaja: Ramses Laursoo, IS20 //Konspekt: 10 //Ülesanne: Java - Klasside omavahelised seosed package bussireisid; public class Reisija { private String nimi; public Reisija() { nimi="<puudub>"; } public Reisija(String nimi) { this.nimi = nimi; } public String getNimi() { return nimi; } public void setNimi(String nimi) { this.nimi = nimi; } }
2c15de96321c96c3e2752e218af2d57e9da23a8d
9c3971280f440834e89062178a60134723edd310
/src/com/criconline/actions/ActionListener.java
87860b0ddd74e7599f4086052d55c9d69d986f57
[]
no_license
gitibeyonde/cricket
4463f123c0e7cbf45deb63353f4d8912a2fdc59d
8150fe0a1d1acd021c8107f5aec872faceda7802
refs/heads/master
2020-06-02T23:18:54.492758
2013-08-03T10:04:52
2013-08-03T10:04:52
191,340,809
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
package com.criconline.actions; import com.criconline.actions.Action; public interface ActionListener { /** * Invoked when an action occurs. */ public void actionPerformed(Action a); }
d2f941adc2c4bbb1dbcda3b0ca22ebb0292baf6d
a1a1e4e004e82f3798089099919054a0f3eda823
/app/src/main/java/com/englishapps/com/checkyourenglishvocabulary/YourStatistics.java
02f3c5e0142900165b75320d73658fb14ad43897
[]
no_license
mk148a/CheckYourEnglishVocabulary
155891f54bb8f1cbba7d4f6a608bfe50fc4a5d2d
9539038cad1db7c00a3c4cb0e1ee4f9ff29afa90
refs/heads/master
2020-04-08T23:06:59.120156
2018-12-22T22:37:35
2018-12-22T22:37:35
159,812,154
0
0
null
2018-12-22T22:37:36
2018-11-30T11:11:40
Java
UTF-8
Java
false
false
39,404
java
package com.englishapps.com.checkyourenglishvocabulary; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.provider.Settings; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.gson.Gson; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.ExecutionException; public class YourStatistics extends AppCompatActivity { public TextView totalscoretxt; public TextView totalknowtxt; public TextView totaluknowntxt; public TextView totalskipedtxt; public TextView goldtxt; public Integer index; private LinearLayout yourstatisticaltl; private String[] arraySpinner; private boolean goldbuttontiklama = false; private String msjsonuc = ""; private void sil(String sil) { Iterator<String> it = Soruekrani.cozulensoruindexleri.iterator(); while (it.hasNext()) { if (it.next().matches("(?i)(" + sil + ").*")) { it.remove(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_your_statistics); LinearLayout anasayfa = (LinearLayout) findViewById(R.id.yourstatisticlinear); goldtxt = (TextView) findViewById(R.id.sakirinkuzeni); EditText usertxt = (EditText) findViewById(R.id.sakirinamcasi); yourstatisticaltl = (LinearLayout) findViewById(R.id.yourstatisticaltlinear); AdView adView = (AdView) this.findViewById(R.id.adView1); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); try { yourstatisticaltl.addView(altview()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (MainActivity.giriscalisti == true) { goldtxt.setEnabled(true); goldtxt.setVisibility(View.VISIBLE); goldtxt.setText(Integer.toString(MainActivity.gold)); usertxt.setEnabled(true); usertxt.setVisibility(View.VISIBLE); usertxt.setText(MainActivity.kullaniciadi); anasayfa.setBackgroundDrawable(getResources().getDrawable(resimara(getString(R.string.yourstatisticbackground)))); } else { goldtxt.setEnabled(false); goldtxt.setVisibility(View.INVISIBLE); usertxt.setEnabled(false); usertxt.setVisibility(View.INVISIBLE); anasayfa.setBackgroundDrawable(getResources().getDrawable(resimara(getString(R.string.yourstatisticbackgrounduye)))); } final Spinner mulayim = (Spinner) findViewById(R.id.sakir); this.arraySpinner = new String[]{ getString(R.string.t1l1score), getString(R.string.t1l2score), getString(R.string.t1l3score), getString(R.string.t2l1score), getString(R.string.t2l2score), getString(R.string.t2l3score), getString(R.string.t3l1score), getString(R.string.t3l2score), getString(R.string.t3l3score), getString(R.string.generalscore) }; totalscoretxt = (TextView) findViewById(R.id.statistotaltxt); totalknowtxt = (TextView) findViewById(R.id.statictsdogrutxt); totaluknowntxt = (TextView) findViewById(R.id.statisticyanlistxt); totalskipedtxt = (TextView) findViewById(R.id.statisticskip); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item, arraySpinner); mulayim.setAdapter(adapter); mulayim.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { index = mulayim.getSelectedItemPosition(); Button button1 = (Button) findViewById(R.id.ResetChosenbtn); Button resetbtn = (Button) findViewById(R.id.ResetAllbtn); if (MainActivity.giriscalisti == true) { if (MainActivity.logout == false) { button1.setVisibility(View.VISIBLE); resetbtn.setVisibility(View.INVISIBLE); } } else { resetbtn.setVisibility(View.INVISIBLE); button1.setVisibility(View.INVISIBLE); } if (index == 0) { //task1 level1 if (MainActivity.task1.level1.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.logout == false) { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } } totalscoretxt.setText(Integer.toString(MainActivity.task1.level1.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task1.level1.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task1.level1.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task1.level1.gecilen)); } else if (index == 1) { //task1 level1 if (MainActivity.task1.level2.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task1.level2.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task1.level2.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task1.level2.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task1.level2.gecilen)); } else if (index == 2) { //task1 level1 if (MainActivity.task1.level3.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task1.level3.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task1.level3.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task1.level3.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task1.level3.gecilen)); } else if (index == 3) { //task1 level1 if (MainActivity.task2.level1.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task2.level1.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task2.level1.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task2.level1.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task2.level1.gecilen)); } else if (index == 4) { //task1 level1 if (MainActivity.task2.level2.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task2.level2.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task2.level2.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task2.level2.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task2.level2.gecilen)); } else if (index == 5) { //task1 level1 if (MainActivity.task2.level3.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task2.level3.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task2.level3.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task2.level3.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task2.level3.gecilen)); } else if (index == 6) { //task1 level1 if (MainActivity.task3.level1.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task3.level1.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task3.level1.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task3.level1.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task3.level1.gecilen)); } else if (index == 7) { //task1 level1 if (MainActivity.task3.level2.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task3.level2.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task3.level2.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task3.level2.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task3.level2.gecilen)); } else if (index == 8) { //task1 level1 if (MainActivity.task3.level3.pasif == true) { button1.setVisibility(View.INVISIBLE); } else { if (MainActivity.giriscalisti == true) { button1.setVisibility(View.VISIBLE); } } totalscoretxt.setText(Integer.toString(MainActivity.task3.level3.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task3.level3.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task3.level3.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task3.level3.gecilen)); } else if (index == 9) { //task1 level1 totalscoretxt.setText(Integer.toString((MainActivity.task1.level1.skor + MainActivity.task1.level2.skor + MainActivity.task1.level3.skor + MainActivity.task2.level1.skor + MainActivity.task2.level2.skor + MainActivity.task2.level3.skor + MainActivity.task3.level1.skor + MainActivity.task3.level2.skor + MainActivity.task3.level3.skor))); totalknowtxt.setText(Integer.toString((MainActivity.task3.level1.dogru + MainActivity.task3.level2.dogru + MainActivity.task3.level3.dogru + MainActivity.task2.level1.dogru + MainActivity.task2.level2.dogru + MainActivity.task2.level3.dogru + MainActivity.task1.level1.dogru + MainActivity.task1.level2.dogru + +MainActivity.task1.level3.dogru))); totaluknowntxt.setText(Integer.toString((MainActivity.task3.level1.yanlis + MainActivity.task3.level2.yanlis + MainActivity.task3.level3.yanlis + MainActivity.task2.level1.yanlis + MainActivity.task2.level2.yanlis + MainActivity.task2.level3.yanlis + MainActivity.task1.level1.yanlis + MainActivity.task1.level2.yanlis + +MainActivity.task1.level3.yanlis))); totalskipedtxt.setText(Integer.toString((MainActivity.task3.level1.gecilen + MainActivity.task3.level2.gecilen + MainActivity.task3.level3.gecilen + MainActivity.task2.level1.gecilen + MainActivity.task2.level2.gecilen + MainActivity.task2.level3.gecilen + MainActivity.task1.level1.gecilen + MainActivity.task1.level2.gecilen + +MainActivity.task1.level3.gecilen))); if (MainActivity.giriscalisti == true) { resetbtn.setVisibility(View.VISIBLE); button1.setVisibility(View.INVISIBLE); } } } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); } public String cpuId() { String android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID); return android_id; } void veritabaninayaz() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { if (MainActivity.logout == false) { if (MainActivity.giriscalisti == true) { Gson gson = new Gson(); String task1 = gson.toJson(MainActivity.task1); String task2 = gson.toJson(MainActivity.task2); String task3 = gson.toJson(MainActivity.task3); String cozulensoruindexleri = gson.toJson(Soruekrani.cozulensoruindexleri); int toplamskor = MainActivity.task1.level1.skor + MainActivity.task1.level2.skor + MainActivity.task1.level3.skor + MainActivity.task2.level1.skor + MainActivity.task2.level2.skor + MainActivity.task2.level3.skor + MainActivity.task3.level1.skor + MainActivity.task3.level2.skor + MainActivity.task3.level3.skor; SendData yenidata = new SendData(); yenidata.cpuid = cpuId(); yenidata.soruindex = cozulensoruindexleri; yenidata.task1 = task1; yenidata.task2 = task2; yenidata.task3 = task3; yenidata.skor = toplamskor; yenidata.gold = MainActivity.gold; gson = new Gson(); String data = gson.toJson(yenidata); try { String sonuc = new gonder().execute("http://hdtvapp.tk/checkyourenglishvocabulary/v1/kullaniciService1.svc/setskor", data).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } } void resetall() { if (MainActivity.gold >= 20) { MainActivity.gold += -20; goldtxt.setText(Integer.toString(MainActivity.gold)); goldbuttontiklama = true; Soruekrani.sorusayisi = 1; Soruekrani.cozulensoruindexleri.clear(); MainActivity.task1.bitis = false; MainActivity.task2.bitis = false; MainActivity.task3.bitis = false; MainActivity.task1.level1.bitis = false; MainActivity.task1.level2.bitis = false; MainActivity.task1.level3.bitis = false; MainActivity.task2.level1.bitis = false; MainActivity.task2.level2.bitis = false; MainActivity.task2.level3.bitis = false; MainActivity.task3.level1.bitis = false; MainActivity.task3.level2.bitis = false; MainActivity.task3.level3.bitis = false; MainActivity.task1.level1.dogru = 0; MainActivity.task1.level2.dogru = 0; MainActivity.task1.level3.dogru = 0; MainActivity.task2.level1.dogru = 0; MainActivity.task2.level2.dogru = 0; MainActivity.task2.level3.dogru = 0; MainActivity.task3.level1.dogru = 0; MainActivity.task3.level2.dogru = 0; MainActivity.task3.level3.dogru = 0; MainActivity.task1.level1.yanlis = 0; MainActivity.task1.level2.yanlis = 0; MainActivity.task1.level3.yanlis = 0; MainActivity.task2.level1.yanlis = 0; MainActivity.task2.level2.yanlis = 0; MainActivity.task2.level3.yanlis = 0; MainActivity.task3.level1.yanlis = 0; MainActivity.task3.level2.yanlis = 0; MainActivity.task3.level3.yanlis = 0; MainActivity.task1.level1.gecilen = 0; MainActivity.task1.level2.gecilen = 0; MainActivity.task1.level3.gecilen = 0; MainActivity.task2.level1.gecilen = 0; MainActivity.task2.level2.gecilen = 0; MainActivity.task2.level3.gecilen = 0; MainActivity.task3.level1.gecilen = 0; MainActivity.task3.level2.gecilen = 0; MainActivity.task3.level3.gecilen = 0; MainActivity.task1.level1.skor = 0; MainActivity.task1.level2.skor = 0; MainActivity.task1.level3.skor = 0; MainActivity.task2.level1.skor = 0; MainActivity.task2.level2.skor = 0; MainActivity.task2.level3.skor = 0; MainActivity.task3.level1.skor = 0; MainActivity.task3.level2.skor = 0; MainActivity.task3.level3.skor = 0; MainActivity.task1.level1.reset = false; MainActivity.task1.level2.reset = false; MainActivity.task1.level3.reset = false; MainActivity.task2.level1.reset = false; MainActivity.task2.level2.reset = false; MainActivity.task2.level3.reset = false; MainActivity.task3.level1.reset = false; MainActivity.task3.level2.reset = false; MainActivity.task3.level3.reset = false; MainActivity.task1.level1.pasif = true; MainActivity.task1.level2.pasif = true; MainActivity.task1.level3.pasif = true; MainActivity.task2.level1.pasif = true; MainActivity.task2.level2.pasif = true; MainActivity.task2.level3.pasif = true; MainActivity.task3.level1.pasif = true; MainActivity.task3.level2.pasif = true; MainActivity.task3.level3.pasif = true; if (MainActivity.sesdurumu == true) { MediaPlayer ses = MediaPlayer.create(YourStatistics.this, R.raw.resetstatistic); ses.start(); } goldtxt.setText(Integer.toString(MainActivity.gold)); try { veritabaninayaz(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } totalscoretxt.setText(Integer.toString(0)); totalknowtxt.setText(Integer.toString(0)); totaluknowntxt.setText(Integer.toString(0)); totalskipedtxt.setText(Integer.toString(0)); } else if (MainActivity.gold < 20) { msjsonuc = getString(R.string.yourstats4); AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(YourStatistics.this); alertDialogBuilder1.setTitle(R.string.yourstats3); alertDialogBuilder1 .setMessage(msjsonuc) .setCancelable(true) .setPositiveButton(R.string.okbutton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); goldbuttontiklama = false; AlertDialog a1 = alertDialogBuilder1.create(); // show it a1.show(); } } void resetchosen() { if (MainActivity.gold >= 5) { MainActivity.gold += -5; goldtxt.setText(Integer.toString(MainActivity.gold)); goldbuttontiklama = true; int x = index; goldtxt.setText(Integer.toString(MainActivity.gold)); Soruekrani.sorusayisi = 1; if (x == 0) { MainActivity.task1.level1.dogru = 0; MainActivity.task1.level1.gecilen = 0; MainActivity.task1.level1.yanlis = 0; MainActivity.task1.level1.skor = 0; if (MainActivity.task1.level1.bitis == true) { MainActivity.task1.level1.bitis = true; } sil("t1l1"); MainActivity.task1.level1.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task1.level1.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task1.level1.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task1.level1.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task1.level1.gecilen)); } else if (x == 1) { MainActivity.task1.level2.dogru = 0; MainActivity.task1.level2.gecilen = 0; MainActivity.task1.level2.yanlis = 0; MainActivity.task1.level2.skor = 0; if (MainActivity.task1.level2.bitis == true) { MainActivity.task1.level2.bitis = true; } sil("t1l2"); MainActivity.task1.level2.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task1.level2.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task1.level2.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task1.level2.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task1.level2.gecilen)); } else if (x == 2) { MainActivity.task1.level3.dogru = 0; MainActivity.task1.level3.gecilen = 0; MainActivity.task1.level3.yanlis = 0; MainActivity.task1.level3.skor = 0; if (MainActivity.task1.level3.bitis == true) { MainActivity.task1.level3.bitis = true; MainActivity.task1.bitis = true; } sil("t1l3"); MainActivity.task1.level3.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task1.level3.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task1.level3.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task1.level3.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task1.level3.gecilen)); } else if (x == 3) { MainActivity.task2.level1.dogru = 0; MainActivity.task2.level1.gecilen = 0; MainActivity.task2.level1.yanlis = 0; MainActivity.task2.level1.skor = 0; if (MainActivity.task2.level1.bitis == true) { MainActivity.task2.level1.bitis = true; } sil("t2l1"); MainActivity.task2.level1.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task2.level1.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task2.level1.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task2.level1.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task2.level1.gecilen)); } else if (x == 4) { MainActivity.task2.level2.dogru = 0; MainActivity.task2.level2.gecilen = 0; MainActivity.task2.level2.yanlis = 0; MainActivity.task2.level2.skor = 0; if (MainActivity.task2.level2.bitis == true) { MainActivity.task2.level2.bitis = true; } sil("t2l2"); MainActivity.task2.level2.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task2.level2.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task2.level2.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task2.level2.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task2.level2.gecilen)); } else if (x == 5) { MainActivity.task2.level3.dogru = 0; MainActivity.task2.level3.gecilen = 0; MainActivity.task2.level3.yanlis = 0; MainActivity.task2.level3.skor = 0; if (MainActivity.task2.level3.bitis == true) { MainActivity.task2.level3.bitis = true; MainActivity.task2.bitis = false; } sil("t2l3"); MainActivity.task2.level3.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task2.level3.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task2.level3.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task2.level3.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task2.level3.gecilen)); } else if (x == 6) { MainActivity.task3.level1.dogru = 0; MainActivity.task3.level1.gecilen = 0; MainActivity.task3.level1.yanlis = 0; MainActivity.task3.level1.skor = 0; if (MainActivity.task3.level1.bitis == true) { MainActivity.task3.level1.bitis = true; } sil("t3l1"); MainActivity.task3.level1.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task3.level1.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task3.level1.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task3.level1.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task3.level1.gecilen)); } else if (x == 7) { MainActivity.task3.level2.dogru = 0; MainActivity.task3.level2.gecilen = 0; MainActivity.task3.level2.yanlis = 0; MainActivity.task3.level2.skor = 0; if (MainActivity.task3.level2.bitis == true) { MainActivity.task3.level2.bitis = true; } sil("t3l2"); MainActivity.task3.level2.reset = true; totalscoretxt.setText(Integer.toString(MainActivity.task3.level2.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task3.level2.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task3.level2.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task3.level2.gecilen)); } else if (x == 8) { MainActivity.task3.level3.dogru = 0; MainActivity.task3.level3.gecilen = 0; MainActivity.task3.level3.yanlis = 0; MainActivity.task3.level3.skor = 0; if (MainActivity.task3.level3.bitis == true) { MainActivity.task3.level3.bitis = true; MainActivity.task3.bitis = false; } MainActivity.task3.level3.reset = true; sil("t3l3"); totalscoretxt.setText(Integer.toString(MainActivity.task3.level3.skor)); totalknowtxt.setText(Integer.toString(MainActivity.task3.level3.dogru)); totaluknowntxt.setText(Integer.toString(MainActivity.task3.level3.yanlis)); totalskipedtxt.setText(Integer.toString(MainActivity.task3.level3.gecilen)); } if (MainActivity.sesdurumu == true) { MediaPlayer ses = MediaPlayer.create(YourStatistics.this, R.raw.resetstatistic); ses.start(); } try { veritabaninayaz(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (MainActivity.gold < 5) { msjsonuc = getString(R.string.yourstats4); AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(YourStatistics.this); alertDialogBuilder1.setTitle(R.string.yourstats3); alertDialogBuilder1 .setMessage(msjsonuc) .setCancelable(true) .setPositiveButton(getString(R.string.okbutton), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); goldbuttontiklama = false; AlertDialog a1 = alertDialogBuilder1.create(); // show it a1.show(); goldbuttontiklama = false; } } void Goldkullan(String tür) { final String tur = tür; String mesaj = ""; if (tür == "resetchosen") { mesaj = getString(R.string.yourstats1); if (MainActivity.questiondurumu == false) { resetchosen(); } else { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(getString(R.string.yourstats3)); alertDialogBuilder .setMessage(mesaj) .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (tur.equals("resetchosen")) { resetchosen(); } else if (tur.equals("resetall")) { resetall(); } } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { goldbuttontiklama = false; msjsonuc = ""; dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } } else if (tür == "resetall") { mesaj = getString(R.string.yourstats2); if (MainActivity.questiondurumu == false) { resetall(); } else { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(getString(R.string.yourstats3)); alertDialogBuilder .setMessage(mesaj) .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (tur.equals("resetchosen")) { resetchosen(); } else if (tur.equals("resetall")) { resetall(); } } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { goldbuttontiklama = false; msjsonuc = ""; dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } } } public int resimara(String isim) { Context context = this; int id = context.getResources().getIdentifier(isim, "drawable", context.getPackageName()); return id; } public View altview() throws IllegalAccessException, InstantiationException, SQLException, ClassNotFoundException { ArrayList<String> adad = new ArrayList<String>(); adad.add("ResetChosen"); adad.add("ResetAll"); adad.add("BacktoMenu"); int marg = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics()); LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams pr = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); pr.setMargins(marg, 0, 0, 0); linearLayout.setLayoutParams(pr); TableLayout tableLayout = new TableLayout(this); tableLayout.setStretchAllColumns(false); TableLayout.LayoutParams tb = (new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT)); tableLayout.setLayoutParams(tb); tableLayout.setWeightSum(1); int k = 1; String[] value = null; for (int i = 0; i < 1; i++) { TableRow tableRow = new TableRow(this); tableRow.setGravity(Gravity.NO_GRAVITY); int marg1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics()); TableLayout.LayoutParams prr = new TableLayout.LayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, 1.0f)); tableRow.setLayoutParams(prr); for (int j = 0; j < 3; j++) { int yukarı = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()); int bosluk = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics()); int genislik = (int) ((getResources().getDisplayMetrics().widthPixels / 3.5)); int sol = (int) ((getResources().getDisplayMetrics().widthPixels / 2.8)); double oran = (float) 57 / (float) 155; int yukseklik = (int) (oran * genislik); //155x57 backto menu button TableRow.LayoutParams tb1 = new TableRow.LayoutParams(genislik, yukseklik); tb1.setMargins((int) (bosluk * 1.1), yukarı, 0, 0); Button button = new Button(this); switch (k) { case 1: button.setId(R.id.ResetChosenbtn); button.setTag("ResetChosen"); button.setBackgroundResource(resimara(getString(R.string.resetchosenbutton))); button.setVisibility(View.INVISIBLE); break; case 2: button.setId(R.id.ResetAllbtn); button.setTag("ResetAll"); button.setBackgroundResource(resimara(getString(R.string.resetyourstatisticsbutton))); button.setVisibility(View.INVISIBLE); break; case 3: button.setTag("BacktoMenu"); button.setBackgroundResource(resimara(getString(R.string.gobackbutton))); break; } button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { switch ((v.getTag().toString())) { case "ResetChosen": //seçileni resetle kodları Goldkullan("resetchosen"); break; case "ResetAll": //hepsini resetle kodları Goldkullan("resetall"); break; case "BacktoMenu": Intent i = new Intent(); i.setClass(YourStatistics.this, singleplayer.class); startActivity(i); break; } } }); tableRow.addView(button, tb1); k = k + 1; } tableLayout.addView(tableRow); } linearLayout.addView(tableLayout); return linearLayout; } @Override public void onBackPressed() { Intent i = new Intent(); i.setClass(this, singleplayer.class); startActivity(i); } }
24fd09adf5f9dbbe53f110ee3564d0c8d697ab12
03ff74cf94e8c8a77d47d260e2a47b38a21a3134
/app/src/main/java/com/kangce/finance/ui/fixedassets/FixedAssetsAdapter.java
88bfb889e08066e6cca69d5f0d50c297a5096852
[]
no_license
JinYanjie/finance-project-app
901fb62df80782f0f95bdd900ca19ff51d0c4496
8ca1676b83c0fcbf1624f6dfa3d52a310793b278
refs/heads/master
2020-05-20T03:29:31.686410
2019-04-18T11:43:46
2019-04-18T11:43:46
185,359,835
0
0
null
null
null
null
UTF-8
Java
false
false
2,042
java
package com.kangce.finance.ui.fixedassets; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.kangce.finance.R; import com.kangce.finance.bean.FixedAssetsEntity; import java.text.SimpleDateFormat; public class FixedAssetsAdapter extends BaseQuickAdapter<FixedAssetsEntity,BaseViewHolder> { private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public FixedAssetsAdapter() { super(R.layout.item_fixed_assets_curtly); } @Override protected void convert(BaseViewHolder helper, FixedAssetsEntity item) { helper.setText(R.id.tv_assetsName,item.getAssetsName()); helper.setText(R.id.tv_assetsCode,"编号: "+item.getAssetsCode()); helper.setText(R.id.tv_inputDate,"入账时间: "+simpleDateFormat.format(item.getInputTime())); helper.setText(R.id.tv_cash,item.getInitialAssetValue().toString()); switch (item.getChangeWay()){ case 1: helper.setText(R.id.tv_change,"购入"); break; case 2: helper.setText(R.id.tv_change,"接受投资"); break; case 3: helper.setText(R.id.tv_change,"接受捐赠"); break; case 4: helper.setText(R.id.tv_change,"自建"); break; case 5: helper.setText(R.id.tv_change,"盘盈"); break; case 6: helper.setText(R.id.tv_change,"出售"); break; case 7: helper.setText(R.id.tv_change,"报废"); break; case 8: helper.setText(R.id.tv_change,"盘亏"); break; case 9: helper.setText(R.id.tv_change,"其他减少"); break; case 10: helper.setText(R.id.tv_change,"其他增加"); break; } } }
af9e610a3cffcc56e4186d5b973c5a276110a609
dfe911b940673d2fecd9db7bbf07a071d0a176c4
/down/src/down/jframe.java
2761f19586f701b330f9e9fb3048abb6c12cf6b9
[]
no_license
sanchit-zeus/sanchit
03e3ca898880a0ede4b7b8356a59b61627783d22
4568a5ada8ef8d43db55a36201afdd8f8a1b2452
refs/heads/master
2021-05-12T12:55:34.385762
2020-07-11T17:01:02
2020-07-11T17:01:02
117,424,064
0
0
null
null
null
null
UTF-8
Java
false
false
257
java
/* * 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 down; /** * * @author Sahil Seewal */ class jframe { }
b513e1722c2fd8ce4f84af0ccc5b1565d822df76
21bdaed4646ff6847a3378f1202e7de314c85a9b
/test/ball/model/BounceTest.java
0f3f3a8feb5f6766adf161138068b6322d5efd5a
[]
no_license
rhuanhuan/BallBehavior
f2262948f813cbbb4a56f9a289577f850e1f1e7d
0dad854403bb1634f76cd6a996d76763142619aa
refs/heads/master
2021-01-11T04:10:40.447428
2016-10-18T10:35:58
2016-10-18T10:35:58
71,237,604
0
0
null
null
null
null
UTF-8
Java
false
false
1,413
java
//package ball.model; // //import ball.model.Ball; //import ball.ui.BallWorld; //import org.junit.Test; // //import static ball.BallTestHarness.*; // //public class BounceTest { // @Test // public void shouldGoDown() throws Exception { // Ball bouncingBall = BallFactory.Ball(0, 100,50, Bounce.DOWN); // // bouncingBall.update(); // // assertCenterYCoordinateIs(oneStepDownFrom(100), bouncingBall); // } // // @Test // public void shouldGoUpAfterHittingTheBottom() throws Exception { // int theBottomEdge = BallWorld.BOX_HEIGHT - Ball.DEFAULT_RADIUS; // Ball bouncingBall = BallFactory.bouncingBall(0, theBottomEdge, Bounce.DOWN); // // bouncingBall.update(); // // assertCenterYCoordinateIs(oneStepUpFrom(theBottomEdge), bouncingBall); // } // // @Test // public void shouldGoUp() throws Exception { // Ball bouncingBall = BallFactory.bouncingBall(0, 100, Bounce.UP); // // bouncingBall.update(); // // assertCenterYCoordinateIs(oneStepUpFrom(100), bouncingBall); // } // // @Test // public void shouldGoDownAfterHittingTheTop() throws Exception { // int theTopEdge = Ball.DEFAULT_RADIUS; // Ball bouncingBall = BallFactory.bouncingBall(0, theTopEdge, Bounce.UP); // // bouncingBall.update(); // // assertCenterYCoordinateIs(oneStepDownFrom(theTopEdge), bouncingBall); // } //}
7eb1ab02f2ebd1d654e528442b57407fd9a623c0
53d677a55e4ece8883526738f1c9d00fa6560ff7
/com/bumptech/glide/manager/e.java
8ccb1400cb608e78e49be1b7508b8946ff55da61
[]
no_license
0jinxing/wechat-apk-source
544c2d79bfc10261eb36389c1edfdf553d8f312a
f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d
refs/heads/master
2020-06-07T20:06:03.580028
2019-06-21T09:17:26
2019-06-21T09:17:26
193,069,132
9
4
null
null
null
null
UTF-8
Java
false
false
2,803
java
package com.bumptech.glide.manager; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.bumptech.glide.h.i; import com.tencent.matrix.trace.core.AppMethodBeat; final class e implements c { private boolean aGA; private final BroadcastReceiver aGB; final c.a aGy; boolean aGz; private final Context context; e(Context paramContext, c.a parama) { AppMethodBeat.i(92379); this.aGB = new e.1(this); this.context = paramContext.getApplicationContext(); this.aGy = parama; AppMethodBeat.o(92379); } @SuppressLint({"MissingPermission"}) static boolean isConnected(Context paramContext) { AppMethodBeat.i(92380); paramContext = (ConnectivityManager)i.d((ConnectivityManager)paramContext.getSystemService("connectivity"), "Argument must not be null"); try { paramContext = paramContext.getActiveNetworkInfo(); if ((paramContext != null) && (paramContext.isConnected())) { AppMethodBeat.o(92380); bool = true; return bool; } } catch (RuntimeException paramContext) { while (true) { Log.isLoggable("ConnectivityMonitor", 5); AppMethodBeat.o(92380); boolean bool = true; continue; bool = false; AppMethodBeat.o(92380); } } } public final void onDestroy() { } public final void onStart() { AppMethodBeat.i(92381); if (!this.aGA) this.aGz = isConnected(this.context); while (true) { try { Context localContext = this.context; BroadcastReceiver localBroadcastReceiver = this.aGB; IntentFilter localIntentFilter = new android/content/IntentFilter; localIntentFilter.<init>("android.net.conn.CONNECTIVITY_CHANGE"); localContext.registerReceiver(localBroadcastReceiver, localIntentFilter); this.aGA = true; AppMethodBeat.o(92381); return; } catch (SecurityException localSecurityException) { Log.isLoggable("ConnectivityMonitor", 5); } AppMethodBeat.o(92381); } } public final void onStop() { AppMethodBeat.i(92382); if (this.aGA) { this.context.unregisterReceiver(this.aGB); this.aGA = false; } AppMethodBeat.o(92382); } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes8-dex2jar.jar * Qualified Name: com.bumptech.glide.manager.e * JD-Core Version: 0.6.2 */
290251226e6234520fdffbdaac88c7c20a01c8f5
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/components/cronet/android/test/smoketests/src/org/chromium/net/smoke/Http2Test.java
17abeb0b55fff0a48f1a83c16676a63e51e5b2ef
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
Java
false
false
1,859
java
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.net.smoke; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.net.UrlRequest; /** * HTTP2 Tests. */ @RunWith(AndroidJUnit4.class) public class Http2Test { private TestSupport.TestServer mServer; @Rule public NativeCronetTestRule mRule = new NativeCronetTestRule(); @Before public void setUp() throws Exception { mServer = mRule.getTestSupport().createTestServer( InstrumentationRegistry.getTargetContext(), TestSupport.Protocol.HTTP2); } @After public void tearDown() throws Exception { mServer.shutdown(); } // Test that HTTP/2 is enabled by default but QUIC is not. @Test @SmallTest public void testHttp2() throws Exception { mRule.getTestSupport().installMockCertVerifierForTesting(mRule.getCronetEngineBuilder()); mRule.initCronetEngine(); Assert.assertTrue(mServer.start()); SmokeTestRequestCallback callback = new SmokeTestRequestCallback(); UrlRequest.Builder requestBuilder = mRule.getCronetEngine().newUrlRequestBuilder( mServer.getSuccessURL(), callback, callback.getExecutor()); requestBuilder.build().start(); callback.blockForDone(); CronetSmokeTestRule.assertSuccessfulNonEmptyResponse(callback, mServer.getSuccessURL()); Assert.assertEquals("h2", callback.getResponseInfo().getNegotiatedProtocol()); } }
71eceddbe52978f5c9e36ae94e5919ca22567692
1902dcf578e09449b75149b8525d46d9dabd7bfe
/encephalon/api/src/main/java/com/devonfw/application/encephalon/collaboratormanagement/logic/api/usecase/UcFindCollaborator.java
9c0873007da013aedff002b9acb909de97514429
[]
no_license
victord96/encephalon
32cc2611f13e08b3bd03891033d550d100df4488
2d9113b1a904bbf643b93ac60e2d80cf5cf46b9a
refs/heads/master
2023-03-29T03:20:57.706122
2020-06-19T12:14:01
2020-06-19T12:14:01
273,021,634
0
0
null
2021-03-31T22:12:29
2020-06-17T16:13:14
Java
UTF-8
Java
false
false
918
java
package com.devonfw.application.encephalon.collaboratormanagement.logic.api.usecase; import java.util.List; import org.springframework.data.domain.Page; import com.devonfw.application.encephalon.collaboratormanagement.logic.api.to.CollaboratorEto; import com.devonfw.application.encephalon.collaboratormanagement.logic.api.to.CollaboratorSearchCriteriaTo; public interface UcFindCollaborator { /** * Returns a Collaborator by its id 'id'. * * @param id The id 'id' of the Collaborator. * @return The {@link CollaboratorEto} with id 'id' */ CollaboratorEto findCollaborator(long id); /** * Returns a paginated list of Collaborators matching the search criteria. * * @param criteria the {@link CollaboratorSearchCriteriaTo}. * @return the {@link List} of matching {@link CollaboratorEto}s. */ Page<CollaboratorEto> findCollaborators(CollaboratorSearchCriteriaTo criteria); }
f6cbd4b8c739f07f40050211296a814081f2ef46
7a3b2503a14193c175e2e0b02261d6b8ab929c25
/01_java/src/lec15/Test04.java
da5f5242e4f5fa3d2e7c48d3b40fc47c2e9a1339
[]
no_license
qlccks789/Web-Study
0ff2f3453daae5dc18c4f598fdf1037aac16251c
06dfd1efad305078b33836c554240d06274fbca5
refs/heads/master
2022-12-22T13:47:09.479989
2019-07-28T07:21:28
2019-07-28T07:21:28
183,115,286
0
0
null
2022-12-16T00:26:19
2019-04-24T00:22:10
Java
UTF-8
Java
false
false
705
java
/** * Stack --> LIFO ( Last In First Out) * * push : 입력 * pop : 데이터를 꺼내고 삭제 * peek : 꺼내고 삭제X */ package lec15; import java.util.Stack; public class Test04 { public static void main(String[] args) { Stack<String> s = new Stack<>(); s.push("a"); s.push("b"); s.push("c"); s.push("d"); s.push("e"); System.out.println(s); System.out.println("pop : " + s.pop()); System.out.println(s); System.out.println("pop : " + s.pop()); System.out.println(s); System.out.println("pop : " + s.pop()); System.out.println(s); System.out.println("peek : " + s.peek()); System.out.println("peek : " + s.peek()); System.out.println(s); } }
2d4f5c7a636fc894eb1502098324c40234d38698
29345337bf86edc938f3b5652702d551bfc3f11a
/core/src/main/java/com/alibaba/alink/params/xgboost/HasLambda.java
41beaf666cb853cf18e868e72c9222134822908e
[ "Apache-2.0" ]
permissive
vacaly/Alink
32b71ac4572ae3509d343e3d1ff31a4da2321b6d
edb543ee05260a1dd314b11384d918fa1622d9c1
refs/heads/master
2023-07-21T03:29:07.612507
2023-07-12T12:41:31
2023-07-12T12:41:31
283,079,072
0
0
Apache-2.0
2020-07-28T02:46:14
2020-07-28T02:46:13
null
UTF-8
Java
false
false
734
java
package com.alibaba.alink.params.xgboost; import org.apache.flink.ml.api.misc.param.ParamInfo; import org.apache.flink.ml.api.misc.param.ParamInfoFactory; import org.apache.flink.ml.api.misc.param.WithParams; import com.alibaba.alink.common.annotation.DescCn; import com.alibaba.alink.common.annotation.NameCn; public interface HasLambda<T> extends WithParams <T> { @NameCn("L2 正则项") @DescCn("L2 正则项") ParamInfo <Double> LAMBDA = ParamInfoFactory .createParamInfo("lambda", Double.class) .setDescription("L2 regularization term on weights.") .setHasDefaultValue(1.0) .build(); default Double getLambda() { return get(LAMBDA); } default T setLambda(Double lambda) { return set(LAMBDA, lambda); } }
aa0a26f5b49030682f0f4fed7cbddb20b1ec92d3
54f97f2f6263c951cd475d91111cc4b7a18911f2
/src/main/java/com/incretio/creditmanager/demo/AnnuityCredit.java
7e06c2386aea8408e04f02489c700e67f49a877d
[]
no_license
Incretio/credit-manager
0a8ba968ae4e25bb1397bf24425a2b6ad73cf699
46a1a711608dbabdb811863d1993ec8c6e4606da
refs/heads/master
2022-05-25T02:15:37.612179
2020-05-02T10:35:35
2020-05-02T10:48:55
259,709,403
0
0
null
null
null
null
UTF-8
Java
false
false
2,963
java
package com.incretio.creditmanager.demo; import com.incretio.creditmanager.util.DateUtils; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class AnnuityCredit extends Credit { public AnnuityCredit(double objectPrice, double firstPayment, Date startDate, int payoutPeriod, double creditRate) { super(objectPrice, firstPayment, startDate, payoutPeriod, creditRate); } public AnnuityCredit(String objectPriceText, String firstPaymentText, String startDateText, String payoutPeriodText, String creditRateText) throws ParseException { this(Double.parseDouble(objectPriceText), Credit.convertStrToDoubleOrGetDefaultValue(firstPaymentText, 0.0d), DateUtils.convertStrToDateElseGetDefaultValue(startDateText, new Date()), Integer.parseInt(payoutPeriodText), Double.parseDouble(creditRateText)); } public double getMonthlyPayment(double principalBanalce, int monthNumber) { return (getMonthCreditRate() * principalBanalce) / (1.0d - Math.pow(getMonthCreditRate() + 1.0d, (double) (-((this.payoutPeriod - monthNumber) + 1)))); } public double getInterestPayment(double principalBalance) { return getMonthCreditRate() * principalBalance; } public static void main(String[] args) { Credit credit = new AnnuityCredit(2934000.0d, 800000.0d, new GregorianCalendar(2016, Calendar.OCTOBER, 18).getTime(), 180, 11.9d); System.out.println("Сумма кредита: " + Credit.formatDouble(credit.getCreditAmount())); System.out.println("Ежемесячный платёж: " + Credit.formatDouble(credit.getMonthlyPayment())); System.out.println("Общая сумма платежа: " + Credit.formatDouble(credit.getTotalAmountPayment())); System.out.println("Сумма переплаты: " + Credit.formatDouble(credit.getOverpaymentAmount())); System.out.println("Дата закрытия кредита: " + DateUtils.formatDate(credit.getStopDateCredit())); credit.creditGraphicCalculation(); for (CreditGraphicRecord creditGraphicRecord : credit.getCreditGraphic()) { System.out.println(String.format("%d\t%s\t%s\t%s\t%s\t%s\t%s", creditGraphicRecord.getMonthNumber(), DateUtils.formatDate(creditGraphicRecord.getPaymentDate()), Credit.formatDouble(creditGraphicRecord.getPrincipalPayment()), Credit.formatDouble(creditGraphicRecord.getInterestPayment()), Credit.formatDouble(creditGraphicRecord.getPartialEarlyPayment()), Credit.formatDouble(creditGraphicRecord.getMonthlyPayment()), Credit.formatDouble(creditGraphicRecord.getPrincipalBalance()))); } } }
41303b2147367979f0edd92d4804edb2b5e819e2
1be7f12b2d13e9e7bbd75444171a276802e0774f
/src/main/java/com/projectx/mvc/exception/repository/completeregister/UpdateMobileInDetailsAndAuthentionDetailsFailedException.java
209a1ecf403bb51887e307868fa7cc74c1b6f1f8
[]
no_license
DineshShende/MVC
eed992ea31a05c789c055f4254d2a655cacca528
9953a678b321039abca9f161047d03679742d0af
refs/heads/master
2020-03-26T20:16:19.447925
2015-05-25T09:22:35
2015-05-25T09:22:35
23,736,736
0
0
null
null
null
null
UTF-8
Java
false
false
616
java
package com.projectx.mvc.exception.repository.completeregister; public class UpdateMobileInDetailsAndAuthentionDetailsFailedException extends RuntimeException{ public UpdateMobileInDetailsAndAuthentionDetailsFailedException(Throwable cause) { super(cause); } public UpdateMobileInDetailsAndAuthentionDetailsFailedException(String message, Throwable cause) { super(message, cause); } public UpdateMobileInDetailsAndAuthentionDetailsFailedException(String message) { super(message); } public UpdateMobileInDetailsAndAuthentionDetailsFailedException() { } }
6ebe9ba61b227c88e840040eb207b8bad6b5cb78
75aeccc2ab54af8578460d7acfd6f3f3f9823122
/remotebundle/src/androidTest/java/com/horsege/remotebundle/ExampleInstrumentedTest.java
01cff08ff6b00f843dbe77a7dd91fddba68dc6a8
[]
no_license
mamingzhang/AtlasJavaTest
a44774edb70690939872aab9db16c2b62a74fc99
04faace6f168352dd8c9474163353d1344132575
refs/heads/master
2021-01-21T00:08:01.184006
2017-09-08T01:44:38
2017-09-08T01:44:38
101,861,064
0
0
null
null
null
null
UTF-8
Java
false
false
757
java
package com.horsege.remotebundle; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.horsege.remotebundle.test", appContext.getPackageName()); } }
6a79b0a0413765ae80d752bd6641f293f99564a9
3350694b33e2e065ce6902bd924bf0cf0c9d9dea
/lagou_edu_home_parent/ssm-dao/src/main/java/com/lagou/dao/PromotionAdMapper.java
a6852083c2e6a71a0de0e7df27274c490a55ee47
[]
no_license
lahayla/repo2
f2180746b16eacba8f9155f1571bdd5fb7a04053
4643bc12869fb5792c3fe7230dcc6f95ade223f9
refs/heads/master
2023-06-22T14:24:54.563882
2021-07-16T08:22:28
2021-07-16T08:22:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package com.lagou.dao; import com.lagou.domain.PromotionAd; import java.util.List; /** * @author liu * @description 广告Dao层接口 * @date 2021/7/13 20:44 */ public interface PromotionAdMapper { /* 分页查询广告信息 */ List<PromotionAd> findAllPromotionAdByPage(); /* 修改广告状态 */ void updatePromotionAdStatus(PromotionAd promotionAd); /* 保存广告信息 */ void savePromotionAd(PromotionAd promotionAd); /* 修改广告信息 */ void updatePromotionAd(PromotionAd promotionAd); /* 根据Id查询广告信息 */ PromotionAd findPromotionAdById(Integer id); }
da09eb17301859e90f6ccfea4cf42d87fa1d020f
61362251437056dec025b96785f2ef9fa040c584
/streams-core/src/main/java/org/apache/streams/core/StreamsFilter.java
11e9539c03007a3357884896020b2336822312f3
[ "Apache-2.0" ]
permissive
w2ogroup/incubator-streams
3dcf0b2ad70e671435fd6adff72610b7c55453fa
93a603c3e530b5a3b25f78a086d664c22136b786
refs/heads/master
2023-08-23T01:15:18.157221
2015-10-15T18:19:54
2015-10-15T18:19:54
19,159,644
0
1
Apache-2.0
2023-08-07T19:27:35
2014-04-25T20:26:15
Java
UTF-8
Java
false
false
1,257
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.streams.core; import java.util.List; import java.util.Queue; /** * Created by sblackmon on 12/13/13. */ public interface StreamsFilter { void start(); void stop(); public void setProcessorInputQueue(Queue<StreamsDatum> inputQueue); public Queue<StreamsDatum> getProcessorInputQueue(); public void setProcessorOutputQueue(Queue<StreamsDatum> outputQueue); public Queue<StreamsDatum> getProcessorOutputQueue(); public boolean filter(StreamsDatum entry); }
[ "sblackmon@unknown" ]
sblackmon@unknown
2a2f514991e8522aa2180591264c989bdab13f65
f54bf6528178972c4860c67689a07d0fdc9cd367
/src/main/java/com/openpojo/reflection/java/bytecode/asm/ASMService.java
0d4640f9a1848fc11dff78fc093be840c6c699eb
[ "Apache-2.0" ]
permissive
mustaphazorgati/openpojo
8701eefba1cd46249d33a50c00ed7cdcac43a18c
23678f8859bdc767c20861dd143a0af1f3f2fc9f
refs/heads/master
2023-04-20T13:20:33.336691
2021-05-16T00:08:22
2021-05-16T00:08:22
358,039,597
0
0
Apache-2.0
2021-05-17T01:05:59
2021-04-14T20:53:49
Java
UTF-8
Java
false
false
2,950
java
/* * Copyright (c) 2010-2018 Osman Shoukry * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package com.openpojo.reflection.java.bytecode.asm; import com.openpojo.cache.CacheStorage; import com.openpojo.cache.CacheStorageFactory; import com.openpojo.log.Logger; import com.openpojo.log.LoggerFactory; import com.openpojo.reflection.exception.ReflectionException; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; /** * @author oshoukry */ public class ASMService { private SimpleClassLoader simpleClassLoader = new SimpleClassLoader(); private Logger logger = LoggerFactory.getLogger(this.getClass()); private CacheStorage<Class<?>> alreadyGeneratedClasses = CacheStorageFactory.getPersistentCacheStorage(); private ASMService() { } public static ASMService getInstance() { return Instance.INSTANCE; } public <T> Class<? extends T> createSubclassFor(Class<T> clazz) { SubClassDefinition subClassDefinition = new DefaultSubClassDefinition(clazz); return createSubclassFor(clazz, subClassDefinition); } @SuppressWarnings("unchecked") public <T> Class<? extends T> createSubclassFor(Class<T> clazz, SubClassDefinition subClassDefinition) { Class<? extends T> generatedClass = (Class<? extends T>) alreadyGeneratedClasses.get(subClassDefinition.getGeneratedClassName()); if (generatedClass != null) { logger.info("Reusing already generated sub-class for class [{0}]", clazz.getName()); } else { try { generatedClass = (Class<? extends T>) simpleClassLoader.loadThisClass(getSubClassByteCode(subClassDefinition), subClassDefinition.getGeneratedClassName()); alreadyGeneratedClasses.add(subClassDefinition.getGeneratedClassName(), generatedClass); } catch (Throwable throwable) { throw ReflectionException.getInstance("Failed to create subclass for class: " + clazz, throwable); } } return generatedClass; } private byte[] getSubClassByteCode(SubClassDefinition subClassDefinition) { ClassReader classReader = subClassDefinition.getClassReader(); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); classReader.accept(new SubClassCreator(cw, subClassDefinition.getGeneratedClassNameAsJDKPath()), 0); cw.visitEnd(); return cw.toByteArray(); } private static class Instance { private static final ASMService INSTANCE = new ASMService(); } }
063dcafb485b926655db3d6b957d9e48151e6472
c6b0df8dfbe675dd3a7fa2fee296fcdff315e54a
/core/src/test/java/org/elasticsearch/search/slice/SliceBuilderTests.java
554b9436e58a7353654fbce4b38a347c3a7fb51c
[ "Apache-2.0" ]
permissive
arjungulzzz/elasticsearch
e70676797d1a47fef6281af047bb79d1465dd5c9
762bbdbd0c047321e1464bbbd88b76378c99d78f
refs/heads/master
2021-01-21T00:12:28.367366
2016-06-07T21:07:37
2016-06-07T21:07:37
60,669,837
1
0
null
2016-06-08T05:05:19
2016-06-08T05:05:19
null
UTF-8
Java
false
false
15,822
java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.slice; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.lucene.search.MatchNoDocsQuery; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParser; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.indices.query.IndicesQueriesRegistry; import org.elasticsearch.test.ESTestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.atomic.AtomicInteger; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SliceBuilderTests extends ESTestCase { private static final int MAX_SLICE = 20; private static NamedWriteableRegistry namedWriteableRegistry; private static IndicesQueriesRegistry indicesQueriesRegistry; /** * setup for the whole base test class */ @BeforeClass public static void init() { namedWriteableRegistry = new NamedWriteableRegistry(); indicesQueriesRegistry = new IndicesQueriesRegistry(); QueryParser<MatchAllQueryBuilder> parser = MatchAllQueryBuilder::fromXContent; indicesQueriesRegistry.register(parser, MatchAllQueryBuilder.QUERY_NAME_FIELD); } @AfterClass public static void afterClass() throws Exception { namedWriteableRegistry = null; indicesQueriesRegistry = null; } private final SliceBuilder randomSliceBuilder() throws IOException { int max = randomIntBetween(2, MAX_SLICE); if (max == 0) max++; int id = randomInt(max - 1); String field = randomAsciiOfLengthBetween(5, 20); return new SliceBuilder(field, id, max); } private static SliceBuilder serializedCopy(SliceBuilder original) throws IOException { try (BytesStreamOutput output = new BytesStreamOutput()) { original.writeTo(output); try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) { return new SliceBuilder(in); } } } public void testSerialization() throws Exception { SliceBuilder original = randomSliceBuilder(); SliceBuilder deserialized = serializedCopy(original); assertEquals(deserialized, original); assertEquals(deserialized.hashCode(), original.hashCode()); assertNotSame(deserialized, original); } public void testEqualsAndHashcode() throws Exception { SliceBuilder firstBuilder = randomSliceBuilder(); assertFalse("sliceBuilder is equal to null", firstBuilder.equals(null)); assertFalse("sliceBuilder is equal to incompatible type", firstBuilder.equals("")); assertTrue("sliceBuilder is not equal to self", firstBuilder.equals(firstBuilder)); assertThat("same searchFrom's hashcode returns different values if called multiple times", firstBuilder.hashCode(), equalTo(firstBuilder.hashCode())); SliceBuilder secondBuilder = serializedCopy(firstBuilder); assertTrue("sliceBuilder is not equal to self", secondBuilder.equals(secondBuilder)); assertTrue("sliceBuilder is not equal to its copy", firstBuilder.equals(secondBuilder)); assertTrue("equals is not symmetric", secondBuilder.equals(firstBuilder)); assertThat("sliceBuilder copy's hashcode is different from original hashcode", secondBuilder.hashCode(), equalTo(firstBuilder.hashCode())); SliceBuilder thirdBuilder = serializedCopy(secondBuilder); assertTrue("sliceBuilder is not equal to self", thirdBuilder.equals(thirdBuilder)); assertTrue("sliceBuilder is not equal to its copy", secondBuilder.equals(thirdBuilder)); assertThat("sliceBuilder copy's hashcode is different from original hashcode", secondBuilder.hashCode(), equalTo(thirdBuilder.hashCode())); assertTrue("equals is not transitive", firstBuilder.equals(thirdBuilder)); assertThat("sliceBuilder copy's hashcode is different from original hashcode", firstBuilder.hashCode(), equalTo(thirdBuilder.hashCode())); assertTrue("sliceBuilder is not symmetric", thirdBuilder.equals(secondBuilder)); assertTrue("sliceBuilder is not symmetric", thirdBuilder.equals(firstBuilder)); } public void testFromXContent() throws Exception { SliceBuilder sliceBuilder = randomSliceBuilder(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } builder.startObject(); sliceBuilder.innerToXContent(builder); builder.endObject(); XContentParser parser = XContentHelper.createParser(shuffleXContent(builder).bytes()); QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.STRICT); SliceBuilder secondSliceBuilder = SliceBuilder.fromXContent(context); assertNotSame(sliceBuilder, secondSliceBuilder); assertEquals(sliceBuilder, secondSliceBuilder); assertEquals(sliceBuilder.hashCode(), secondSliceBuilder.hashCode()); } public void testInvalidArguments() throws Exception { Exception e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", -1, 10)); assertEquals(e.getMessage(), "id must be greater than or equal to 0"); e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 10, -1)); assertEquals(e.getMessage(), "max must be greater than 1"); e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 10, 0)); assertEquals(e.getMessage(), "max must be greater than 1"); e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 10, 5)); assertEquals(e.getMessage(), "max must be greater than id"); e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 1000, 1000)); assertEquals(e.getMessage(), "max must be greater than id"); e = expectThrows(IllegalArgumentException.class, () -> new SliceBuilder("field", 1001, 1000)); assertEquals(e.getMessage(), "max must be greater than id"); } public void testToFilter() throws IOException { Directory dir = new RAMDirectory(); try (IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())))) { writer.commit(); } QueryShardContext context = mock(QueryShardContext.class); try (IndexReader reader = DirectoryReader.open(dir)) { MappedFieldType fieldType = new MappedFieldType() { @Override public MappedFieldType clone() { return null; } @Override public String typeName() { return null; } @Override public Query termQuery(Object value, @Nullable QueryShardContext context) { return null; } }; fieldType.setName(UidFieldMapper.NAME); fieldType.setHasDocValues(false); when(context.fieldMapper(UidFieldMapper.NAME)).thenReturn(fieldType); when(context.getIndexReader()).thenReturn(reader); SliceBuilder builder = new SliceBuilder(5, 10); Query query = builder.toFilter(context, 0, 1); assertThat(query, instanceOf(TermsSliceQuery.class)); assertThat(builder.toFilter(context, 0, 1), equalTo(query)); try (IndexReader newReader = DirectoryReader.open(dir)) { when(context.getIndexReader()).thenReturn(newReader); assertThat(builder.toFilter(context, 0, 1), equalTo(query)); } } try (IndexReader reader = DirectoryReader.open(dir)) { MappedFieldType fieldType = new MappedFieldType() { @Override public MappedFieldType clone() { return null; } @Override public String typeName() { return null; } @Override public Query termQuery(Object value, @Nullable QueryShardContext context) { return null; } }; fieldType.setName("field_doc_values"); fieldType.setHasDocValues(true); fieldType.setDocValuesType(DocValuesType.SORTED_NUMERIC); when(context.fieldMapper("field_doc_values")).thenReturn(fieldType); when(context.getIndexReader()).thenReturn(reader); IndexNumericFieldData fd = mock(IndexNumericFieldData.class); when(context.getForField(fieldType)).thenReturn(fd); SliceBuilder builder = new SliceBuilder("field_doc_values", 5, 10); Query query = builder.toFilter(context, 0, 1); assertThat(query, instanceOf(DocValuesSliceQuery.class)); assertThat(builder.toFilter(context, 0, 1), equalTo(query)); try (IndexReader newReader = DirectoryReader.open(dir)) { when(context.getIndexReader()).thenReturn(newReader); assertThat(builder.toFilter(context, 0, 1), equalTo(query)); } // numSlices > numShards int numSlices = randomIntBetween(10, 100); int numShards = randomIntBetween(1, 9); Map<Integer, AtomicInteger> numSliceMap = new HashMap<>(); for (int i = 0; i < numSlices; i++) { for (int j = 0; j < numShards; j++) { SliceBuilder slice = new SliceBuilder("_uid", i, numSlices); Query q = slice.toFilter(context, j, numShards); if (q instanceof TermsSliceQuery || q instanceof MatchAllDocsQuery) { AtomicInteger count = numSliceMap.get(j); if (count == null) { count = new AtomicInteger(0); numSliceMap.put(j, count); } count.incrementAndGet(); if (q instanceof MatchAllDocsQuery) { assertThat(count.get(), equalTo(1)); } } else { assertThat(q, instanceOf(MatchNoDocsQuery.class)); } } } int total = 0; for (Map.Entry<Integer, AtomicInteger> e : numSliceMap.entrySet()) { total += e.getValue().get(); } assertThat(total, equalTo(numSlices)); // numShards > numSlices numShards = randomIntBetween(3, 100); numSlices = randomInt(numShards-1); List<Integer> targetShards = new ArrayList<>(); for (int i = 0; i < numSlices; i++) { for (int j = 0; j < numShards; j++) { SliceBuilder slice = new SliceBuilder("_uid", i, numSlices); Query q = slice.toFilter(context, j, numShards); if (q instanceof MatchNoDocsQuery == false) { assertThat(q, instanceOf(MatchAllDocsQuery.class)); targetShards.add(j); } } } assertThat(targetShards.size(), equalTo(numShards)); assertThat(new HashSet<>(targetShards).size(), equalTo(numShards)); // numShards == numSlices numShards = randomIntBetween(2, 10); numSlices = numShards; for (int i = 0; i < numSlices; i++) { for (int j = 0; j < numShards; j++) { SliceBuilder slice = new SliceBuilder("_uid", i, numSlices); Query q = slice.toFilter(context, j, numShards); if (i == j) { assertThat(q, instanceOf(MatchAllDocsQuery.class)); } else { assertThat(q, instanceOf(MatchNoDocsQuery.class)); } } } } try (IndexReader reader = DirectoryReader.open(dir)) { MappedFieldType fieldType = new MappedFieldType() { @Override public MappedFieldType clone() { return null; } @Override public String typeName() { return null; } @Override public Query termQuery(Object value, @Nullable QueryShardContext context) { return null; } }; fieldType.setName("field_without_doc_values"); when(context.fieldMapper("field_without_doc_values")).thenReturn(fieldType); when(context.getIndexReader()).thenReturn(reader); SliceBuilder builder = new SliceBuilder("field_without_doc_values", 5, 10); IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> builder.toFilter(context, 0, 1)); assertThat(exc.getMessage(), containsString("cannot load numeric doc values")); } } }
7d5226139b6ec3b407ce1105fcbb6f57008f0d4e
d0cdb298c4ff691cd71f2cdb7900dcdeb6156cad
/app/src/main/java/com/flickerapp/database/FlickerDbTableSchema.java
34b7167c19dc5447bdf3cb19246046969253e63e
[]
no_license
anup316/FlickrApp
5275ba2c7dac15db2e5c2e2eb3172cbf5dfa12c1
dba78cc500b6dcc3f37d94041fdbce3aea7dde56
refs/heads/master
2020-03-27T03:27:03.039107
2018-08-24T12:06:37
2018-08-24T12:06:37
145,863,389
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package com.flickerapp.database; import com.flickerapp.utility.Constants; public class FlickerDbTableSchema { public static final String DATABASE_CREATE_PLATE_INFO = "create table if not exists " + Constants.FLICKER_PHOTO_TABLE + "(" + Constants.V_ID + " string PRIMARY KEY null, " + Constants.V_IMAGE_PATH + " string " + ")"; }
d76e112dffe999712b9a9bd2491ea07a2e76345f
aecc16a768cfdc487760e30872ee4a5076fb6b89
/3 course/1 semester/Course/projects/1/project/ServerCourseWork/src/database/AbstractFactory.java
3f4ad8737e27118507a9b591dce20547a3a64eef
[]
no_license
SKupreeva/University
30e0e6d2f8c40a7e3b8b0d1430e78a4df89a93da
70c4fff1f352585e771a6ac3a6850731c030fb1e
refs/heads/master
2023-08-15T04:36:24.523246
2021-09-29T21:00:19
2021-09-29T21:00:19
306,969,486
1
1
null
null
null
null
UTF-8
Java
false
false
474
java
package database; public abstract class AbstractFactory { public abstract SQLUsers getUsers(); public abstract SQLPlane getPlane(); public abstract SQLSchedule getSchedule(); public abstract SQLRout getRout(); public abstract SQLDate getDate(); public abstract SQLIndexOfPrice getIndexOfPrice(); public abstract SQLTicketsInSale getTicketsInSale(); public abstract SQLPassengers getPassengers(); public abstract SQLTicket getTicket(); }
5bb80a8da9e7e3354aeaa6bedae98bbdd6dd76fa
fa93c9be2923e697fb8a2066f8fb65c7718cdec7
/sources/com/yandex/mobile/ads/impl/mn.java
02cdce2d31e291155e4a6a285528b7f8527bade4
[]
no_license
Auch-Auch/avito_source
b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b
76fdcc5b7e036c57ecc193e790b0582481768cdc
refs/heads/master
2023-05-06T01:32:43.014668
2021-05-25T10:19:22
2021-05-25T10:19:22
370,650,685
0
0
null
null
null
null
UTF-8
Java
false
false
1,680
java
package com.yandex.mobile.ads.impl; import android.support.annotation.NonNull; import com.yandex.mobile.ads.nativeads.MediaView; public final class mn extends mf { @NonNull private final ml<es, ov> a; public mn(@NonNull MediaView mediaView, @NonNull mh mhVar) { super(mediaView); this.a = new ml<>(mhVar); } /* JADX DEBUG: Method arguments types fixed to match base method, original types: [android.view.View] */ @Override // com.yandex.mobile.ads.impl.mk public final /* bridge */ /* synthetic */ void a(@NonNull MediaView mediaView) { this.a.a(); super.a((mn) mediaView); } @Override // com.yandex.mobile.ads.impl.mf public final void a(@NonNull ow owVar) { } /* JADX DEBUG: Method arguments types fixed to match base method, original types: [android.view.View, java.lang.Object] */ @Override // com.yandex.mobile.ads.impl.mk public final /* synthetic */ void b(@NonNull MediaView mediaView, @NonNull ow owVar) { ow owVar2 = owVar; if (owVar2.a() != null) { this.a.a(owVar2.a()); } } /* JADX DEBUG: Method arguments types fixed to match base method, original types: [android.view.View, java.lang.Object] */ @Override // com.yandex.mobile.ads.impl.mk public final /* synthetic */ boolean a(@NonNull MediaView mediaView, @NonNull ow owVar) { ow owVar2 = owVar; if (owVar2.a() != null) { return this.a.b(owVar2.a()); } return false; } @Override // com.yandex.mobile.ads.impl.mk public final void a(@NonNull oq oqVar, @NonNull mq mqVar) { this.a.a(oqVar, mqVar); } }
0522b0b69c8fed47bee14aa5a704139c0ef3938c
20f098a5364c0dcd2e1ce6871dc5801a89283f38
/SmartScreenLock_Branch/src/com/cc/huangmabisheng/model/AppIntroMap.java
4ad27a4d47c01ae9508d2c34d170adac9c77c51d
[]
no_license
kingzqwang/my_hackathon
c4a8969250a35259e7cf55378b20cf021e067afc
1e77f6a402fecd78f23b1fbe9d8c936e18ec1f7d
refs/heads/master
2020-04-11T03:01:21.724450
2014-08-07T07:34:07
2014-08-07T07:34:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,959
java
package com.cc.huangmabisheng.model; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; import com.cc.huangmabisheng.constant.Constant; import com.cc.huangmabisheng.constant.Constant.Scene; import com.cc.huangmabisheng.constant.Constant.SizeType; import com.cc.huangmabisheng.constant.Constant.TimeQuantum; import com.cc.huangmabisheng.utils.TimeUtil; /** * 本身就囊括了所有最近打开的app */ public class AppIntroMap extends HashMap<String, AppDataForList> { Context context; public ArrayList<AppDataForList> appDatas = new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN);//最常开启的应用 //public Map<TimeQuantum, ArrayList<AppDataForList>> appDatasNowMap = new HashMap<Constant.TimeQuantum, ArrayList<AppDataForList>>();//本时间段最常开启6个开启的应用 public ArrayList<AppDataForList> appDatasScene = new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN);//场景推荐 ValueComparator vc = new ValueComparator(); public AppIntroMap(Context context) { this.context = context; // appDatasNowMap.put(TimeQuantum.BEFORE_SLEEP, new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN)); // appDatasNowMap.put(TimeQuantum.REST, new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN)); // appDatasNowMap.put(TimeQuantum.SLEEPING, new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN)); // appDatasNowMap.put(TimeQuantum.WORKING_MORNING, new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN)); // appDatasNowMap.put(TimeQuantum.WORKING_AFTERNOON, new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN)); // appDatasNowMap.put(TimeQuantum.WORKING_NIGHT, new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN)); } private void updateAppDatasScene(Scene scene) { appDatasScene = new ArrayList<AppDataForList>(Constant.NUM_ON_SCREEN); switch (scene) { case EARPHONE: PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_VIEW); Uri u = Uri.parse("file:///test.mp3"); intent.setDataAndType(u, "audio/*"); List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities( intent, 0); Log.d("updateAppDatasScene", resolveInfo.size()+""); for (int i=0;i<resolveInfo.size();i++) { if (i==Constant.NUM_ON_SCREEN) { break; } appDatasScene.add(new AppDataForList(resolveInfo.get(i).activityInfo.packageName, null)); } break; default: break; } } public void updateData(String packageName,TimeQuantum timeQuantum) { Log.e("updateData","共统计app"+this.size()); AppDataForList app = this.get(packageName); if (appDatas.contains(app)) { Log.e("updateData","appDatas.contains"); int no = appDatas.indexOf(app); appDatas.remove(no); insertAndSort(no-1,app); // Collections.sort(appDatas,vc); }else if (appDatas.size() == Constant.NUM_ON_SCREEN) {//已满 Log.e("updateData","已满"); if (appDatas.get(appDatas.size()-1).size() <= app.size()) { appDatas.remove(appDatas.size()-1); insertAndSort(appDatas.size()-1,app); // Collections.sort(appDatas,vc); } }else {//未满 insertAndSort(appDatas.size()-1, app); // appDatas.add(app); // Collections.sort(appDatas,vc); } //updateDataNow(packageName,timeQuantum); } private void insertAndSort(int i,AppDataForList app) { for (;i >= 0; i--) { if (appDatas.get(i).size()>app.size()) { appDatas.add(i+1, app); break; } } if (-1 == i) { appDatas.add(0,app); } } // private void updateDataNow(String packageName,TimeQuantum timeQuantum) { // AppDataForList appData = this.get(packageName); // int i = 0; // AppDataForList[] appDatasNow = appDatasNowMap.get(timeQuantum); // for (; i < Constant.NUM_ON_SCREEN; i++) { // if (appDatasNow[i] == null) { // break; // } // if (appDatasNow[i].packageName.equals(appData.packageName)) { // shiftDown(appDatasNow, i,timeQuantum); // return; // } // } // if (i < Constant.NUM_ON_SCREEN) { // appDatasNow[i] = appData; // shiftUp(appDatasNow, i,timeQuantum); // }else if (appDatasNow[0].size(timeQuantum) < appData.size(timeQuantum)) { // appDatasNow[0] = appData; // shiftDown(appDatasNow, 0,timeQuantum); // } // } class ValueComparator implements Comparator<AppDataForList> { @Override public int compare(AppDataForList lhs, AppDataForList rhs) { // TODO Auto-generated method stub return rhs.size()-lhs.size(); } } }
e1a1d88d36d16b9e648b863a043b038c1d8d4bf1
76910e26b7074963372fc3d4dd0a318f4830bfcd
/Hashmap/src/java_hashmap/TipeLain.java
aca47c4f3b4ff8956f6903559738613d80c9efb0
[]
no_license
syahrulridho/TUGAS-AKHIR-OOP
a6561d3fe2b7c35de0701cd73554bed88be01d08
d36fec17d7dfb173b7fd3832c32382bdc3f2c97a
refs/heads/master
2020-12-11T03:02:53.978898
2020-01-14T07:09:17
2020-01-14T07:09:17
233,773,435
0
0
null
null
null
null
UTF-8
Java
false
false
758
java
/* * 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 java_hashmap; /** * * @author windows */ // Import the HashMap class import java.util.HashMap; public class TipeLain { public static void main(String[] args) { // Create a HashMap object called people HashMap<String, Integer> people = new HashMap<String, Integer>(); // Add keys and values (Name, Age) people.put("John", 32); people.put("Steve", 30); people.put("Angie", 33); for (String i : people.keySet()) { System.out.println("key: " + i + " value: " + people.get(i)); } } }
10c6b8098a2ef275242460d00bd0a7a278e20ca8
cbc90a04b310a2d619a417f3904298a23794c7e5
/Android/AndroidFlowerDetection-0618/app/src/main/java/com/test/flowerdetection/Config.java
d7db8d7c53ea7b2241981ef3903bfc554a10fcd5
[]
no_license
xinseesea/Android_Flower_Detection
5284f5442146bb8d60e478a9c662fd6b5d0dcf7c
6809cbd1c19b626faa5d1fca10eefd0db77963af
refs/heads/master
2022-11-28T06:20:55.372889
2020-08-04T04:25:47
2020-08-04T04:25:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
136
java
package com.test.flowerdetection; public class Config { public static final String IMAGE_DIRECTORY_NAME = "Android File Upload"; }
eb039b39b1271fbdcb4d932c837d357cad74e1b5
74b47b895b2f739612371f871c7f940502e7165b
/aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/DetectProtectiveEquipmentRequest.java
d87e630d853c6360838692a132c30aa326d14201
[ "Apache-2.0" ]
permissive
baganda07/aws-sdk-java
fe1958ed679cd95b4c48f971393bf03eb5512799
f19bdb30177106b5d6394223a40a382b87adf742
refs/heads/master
2022-11-09T21:55:43.857201
2022-10-24T21:08:19
2022-10-24T21:08:19
221,028,223
0
0
Apache-2.0
2019-11-11T16:57:12
2019-11-11T16:57:11
null
UTF-8
Java
false
false
6,308
java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.rekognition.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DetectProtectiveEquipmentRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or you can * reference an image stored in an Amazon S3 bucket. * </p> */ private Image image; /** * <p> * An array of PPE types that you want to summarize. * </p> */ private ProtectiveEquipmentSummarizationAttributes summarizationAttributes; /** * <p> * The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or you can * reference an image stored in an Amazon S3 bucket. * </p> * * @param image * The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or * you can reference an image stored in an Amazon S3 bucket. */ public void setImage(Image image) { this.image = image; } /** * <p> * The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or you can * reference an image stored in an Amazon S3 bucket. * </p> * * @return The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or * you can reference an image stored in an Amazon S3 bucket. */ public Image getImage() { return this.image; } /** * <p> * The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or you can * reference an image stored in an Amazon S3 bucket. * </p> * * @param image * The image in which you want to detect PPE on detected persons. The image can be passed as image bytes or * you can reference an image stored in an Amazon S3 bucket. * @return Returns a reference to this object so that method calls can be chained together. */ public DetectProtectiveEquipmentRequest withImage(Image image) { setImage(image); return this; } /** * <p> * An array of PPE types that you want to summarize. * </p> * * @param summarizationAttributes * An array of PPE types that you want to summarize. */ public void setSummarizationAttributes(ProtectiveEquipmentSummarizationAttributes summarizationAttributes) { this.summarizationAttributes = summarizationAttributes; } /** * <p> * An array of PPE types that you want to summarize. * </p> * * @return An array of PPE types that you want to summarize. */ public ProtectiveEquipmentSummarizationAttributes getSummarizationAttributes() { return this.summarizationAttributes; } /** * <p> * An array of PPE types that you want to summarize. * </p> * * @param summarizationAttributes * An array of PPE types that you want to summarize. * @return Returns a reference to this object so that method calls can be chained together. */ public DetectProtectiveEquipmentRequest withSummarizationAttributes(ProtectiveEquipmentSummarizationAttributes summarizationAttributes) { setSummarizationAttributes(summarizationAttributes); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getImage() != null) sb.append("Image: ").append(getImage()).append(","); if (getSummarizationAttributes() != null) sb.append("SummarizationAttributes: ").append(getSummarizationAttributes()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DetectProtectiveEquipmentRequest == false) return false; DetectProtectiveEquipmentRequest other = (DetectProtectiveEquipmentRequest) obj; if (other.getImage() == null ^ this.getImage() == null) return false; if (other.getImage() != null && other.getImage().equals(this.getImage()) == false) return false; if (other.getSummarizationAttributes() == null ^ this.getSummarizationAttributes() == null) return false; if (other.getSummarizationAttributes() != null && other.getSummarizationAttributes().equals(this.getSummarizationAttributes()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getImage() == null) ? 0 : getImage().hashCode()); hashCode = prime * hashCode + ((getSummarizationAttributes() == null) ? 0 : getSummarizationAttributes().hashCode()); return hashCode; } @Override public DetectProtectiveEquipmentRequest clone() { return (DetectProtectiveEquipmentRequest) super.clone(); } }
[ "" ]
c41496c69d1bc20cf68eeb529f0d4490e7b46827
b2ba372b18a4c758a65eb1dfa5b1ac24ed2f0311
/Framework/GamePad.java
48a43a89afcd5fa0508f05ca25477b708ec4f613
[]
no_license
Atomatrons/VirtualAtomobot
1721cb848c4ea7f79cf6ff5d313a95b3442c3599
3bd651a2478c25ca0b3fbbd196cf1a95f100448b
refs/heads/master
2023-08-11T11:22:08.833917
2021-09-28T03:57:05
2021-09-28T03:57:05
411,130,363
0
0
null
null
null
null
UTF-8
Java
false
false
2,889
java
package shiva.virtualatomobot; import java.util.*; public class GamePad { private String name; public float left_stick_x; public float left_stick_y; public boolean left_stick_button; public float right_stick_x; public float right_stick_y; public boolean right_stick_button; public boolean a; public boolean b; public boolean x; public boolean y; public boolean right_bumper; public float right_trigger; public boolean start; public boolean back; public boolean guide; public boolean left_bumper; public float left_trigger; public boolean dpad_left; public boolean dpad_down; public boolean dpad_right; public boolean dpad_up; public GamePad(String _name) { name = _name; } // FOr the command interpreter public void setValue(String controlName, String value) { switch (controlName) { case "left_stick_x": left_stick_x = valueAsFloat(value); break; case "left_stick_y": left_stick_y = valueAsFloat(value); break; case "left_stick_button": left_stick_button = valueAsBoolean(value); break; case "right_stick_x": right_stick_x = valueAsFloat(value); break; case "right_stick_y": right_stick_y = valueAsFloat(value); break; case "right_stick_button": right_stick_button = valueAsBoolean(value); break; case "a": a = valueAsBoolean(value); break; case "b": b = valueAsBoolean(value); break; case "x": x = valueAsBoolean(value); break; case "y": y = valueAsBoolean(value); break; case "right_bumper": right_bumper = valueAsBoolean(value); break; case "right_trigger": right_trigger = valueAsFloat(value); break; case "start": start = valueAsBoolean(value); break; case "back": back = valueAsBoolean(value); break; case "guide": guide = valueAsBoolean(value); break; case "left_bumper": left_bumper = valueAsBoolean(value); break; case "left_trigger": left_trigger = valueAsFloat(value); break; case "dpad_left": dpad_left = valueAsBoolean(value); break; case "dpad_down": dpad_down = valueAsBoolean(value); break; case "dpad_right": dpad_right = valueAsBoolean(value); break; case "dpad_up": dpad_up = valueAsBoolean(value); break; default: System.out.println("Unrecognized control '" + controlName + "'"); } } private boolean valueAsBoolean(String value) { var result = Boolean.parseBoolean(value); return result; } private float valueAsFloat(String value) { var result = Float.parseFloat(value); return result; } }
86759b8d71149d6f93daf75d445fe01b1eac92bf
2a9988d4e3e6517ee62b68efd3319546e58ad2bc
/book-service/src/main/java/io/github/wellingtoncosta/sescomp/bookservice/app/web/controller/BookController.java
d8d0d1a51b24c0913adb7f152999f7a7501dc8b1
[ "MIT" ]
permissive
wellingtoncosta/spring-cloud-microservices
16a3e87bf6f52e4a7eb141e950460a2839ff79f4
d686fc94063b4fd66bac332cd7820579be682ebd
refs/heads/master
2020-08-11T03:34:17.150592
2019-10-11T16:54:24
2019-10-11T16:54:24
214,482,994
2
0
null
null
null
null
UTF-8
Java
false
false
2,055
java
package io.github.wellingtoncosta.sescomp.bookservice.app.web.controller; import io.github.wellingtoncosta.sescomp.bookservice.app.web.dto.BookDto; import io.github.wellingtoncosta.sescomp.bookservice.domain.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; import static io.github.wellingtoncosta.sescomp.bookservice.app.web.dto.mapper.BookDtoMapper.toEntity; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; @RestController @RequestMapping("/books") public class BookController { private final BookService service; @Autowired public BookController(BookService service) { this.service = service; } @ResponseStatus(HttpStatus.OK) @GetMapping(produces = APPLICATION_JSON_UTF8_VALUE) public List<BookDto> findAll() { return service.findAll().stream().map(BookDto::new).collect(Collectors.toList()); } @ResponseStatus(HttpStatus.OK) @GetMapping(value = "/{id}", produces = APPLICATION_JSON_UTF8_VALUE) public BookDto findById(@PathVariable("id") Long id) { return new BookDto(service.findById(id)); } @ResponseStatus(HttpStatus.CREATED) @PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) public BookDto save(@RequestBody BookDto dto) { return new BookDto(service.save(toEntity(dto))); } @ResponseStatus(HttpStatus.OK) @PutMapping(value = "/{id}", consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) public BookDto update(@PathVariable("id") Long id, @RequestBody BookDto dto) { return new BookDto(service.update(id, toEntity(dto))); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping(value = "/{id}", produces = APPLICATION_JSON_UTF8_VALUE) public void delete(@PathVariable("id") Long id) { service.delete(id); } }
e1ca3700bf51976223670be436d381771de99628
6e57bdc0a6cd18f9f546559875256c4570256c45
/cts/hostsidetests/deviceidle/src/com/android/cts/deviceidle/DeviceIdleWhitelistTest.java
bdba196e1e777df53510cd3568a4a2f1719f605d
[]
no_license
dongdong331/test
969d6e945f7f21a5819cd1d5f536d12c552e825c
2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e
refs/heads/master
2023-03-07T06:56:55.210503
2020-12-07T04:15:33
2020-12-07T04:15:33
134,398,935
2
1
null
2022-11-21T07:53:41
2018-05-22T10:26:42
null
UTF-8
Java
false
false
3,910
java
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts.deviceidle; import static org.junit.Assert.*; import com.android.tradefed.device.DeviceNotAvailableException; import com.android.tradefed.log.LogUtil; import com.android.tradefed.testtype.DeviceJUnit4ClassRunner; import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; /** * Tests that it is possible to remove apps from the system whitelist */ @RunWith(DeviceJUnit4ClassRunner.class) public class DeviceIdleWhitelistTest extends BaseHostJUnit4Test { private static final String DEVICE_IDLE_COMMAND_PREFIX = "cmd deviceidle sys-whitelist "; private static final String RESET_SYS_WHITELIST_COMMAND = "cmd deviceidle sys-whitelist reset"; private static final String SHOW_SYS_WHITELIST_COMMAND = DEVICE_IDLE_COMMAND_PREFIX; private List<String> mOriginalSystemWhitelist; @Before public void setUp() throws Exception { getDevice().executeShellCommand(RESET_SYS_WHITELIST_COMMAND); mOriginalSystemWhitelist = getSystemWhitelist(); if (mOriginalSystemWhitelist.size() < 1) { LogUtil.CLog.w("No packages found in system whitelist"); Assume.assumeTrue(false); } } @After public void tearDown() throws Exception { getDevice().executeShellCommand(RESET_SYS_WHITELIST_COMMAND); } @Test public void testRemoveFromSysWhitelist() throws Exception { final String packageToRemove = mOriginalSystemWhitelist.get(0); getDevice().executeShellCommand(DEVICE_IDLE_COMMAND_PREFIX + "-" + packageToRemove); final List<String> newWhitelist = getSystemWhitelist(); assertFalse("Package " + packageToRemove + " not removed from whitelist", newWhitelist.contains(packageToRemove)); } @Test public void testRemovesPersistedAcrossReboots() throws Exception { for (int i = 0; i < mOriginalSystemWhitelist.size(); i+=2) { // remove odd indexed packages from the whitelist getDevice().executeShellCommand( DEVICE_IDLE_COMMAND_PREFIX + "-" + mOriginalSystemWhitelist.get(i)); } final List<String> whitelistBeforeReboot = getSystemWhitelist(); Thread.sleep(10_000); // write to disk happens after 5 seconds getDevice().reboot(); Thread.sleep(5_000); // to make sure service is initialized final List<String> whitelistAfterReboot = getSystemWhitelist(); assertEquals(whitelistBeforeReboot.size(), whitelistAfterReboot.size()); for (int i = 0; i < whitelistBeforeReboot.size(); i++) { assertTrue(whitelistAfterReboot.contains(whitelistBeforeReboot.get(i))); } } private List<String> getSystemWhitelist() throws DeviceNotAvailableException { final String output = getDevice().executeShellCommand(SHOW_SYS_WHITELIST_COMMAND).trim(); final List<String> packages = new ArrayList<>(); for (String line : output.split("\n")) { final int i = line.indexOf(','); packages.add(line.substring(0, i)); } return packages; } }
5908567e008dacfc0242bc0a3f29815ccbe650ca
6dacfdf63b1aee9f5afc166c83c5b4b46304b5e4
/orderFood/src/main/java/com/niit/foodorder/rest/UserRestController.java
64ec2d402f265c6f218007cd0c6b70787372aab6
[]
no_license
Vartika8/AngularMeal-Spring
331919ba86345cf2f6739809328549e1dd377fdf
8027c5a9f80ce34baec2957486d8cd24b664322a
refs/heads/master
2022-09-21T11:18:58.799116
2020-06-03T13:19:52
2020-06-03T13:19:52
256,936,302
0
0
null
null
null
null
UTF-8
Java
false
false
1,733
java
package com.niit.foodorder.rest; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.niit.foodorder.model.Customer; import com.niit.foodorder.model.Restaurant; import com.niit.foodorder.model.Users; import com.niit.foodorder.repository.CustomerRepository; import com.niit.foodorder.repository.RestaurantRepository; import com.niit.foodorder.repository.UserRepository; @RestController @CrossOrigin(origins="http://localhost:4200") @RequestMapping(value="/api") public class UserRestController { @Autowired private UserRepository urepo; @Autowired private CustomerRepository crepo; @Autowired private RestaurantRepository rrepo; @PostMapping("/userRegistration") public Users userregistration(@RequestBody Users user) { Customer customer = null; Restaurant restaurant = null; user.setRestaurant(null); user.setCustomer(null); if (user.getRole().equalsIgnoreCase("Customer")) { customer = new Customer(); customer.setUser(urepo.save(user)); crepo.save(customer); } else { restaurant = new Restaurant(); restaurant.setUser(urepo.save(user)); rrepo.save(restaurant); } return user; } @PostMapping("/login") public Users userLogin(@RequestBody Map<String,String> users) { return urepo.findByPhoneAndPassword(users.get("phone") ,users.get("password")); } }
c4dcb6c0928c5644570cb8a3249441939df0bbec
c8aae03321bcef1b219fb17c015503becd52085c
/cdi/exercise1/src/test/java/com/mitrais/bootcamp/cdi/exercise1/Test1.java
08207567e12a6ac60ad9ffd6404515aa364c273e
[]
no_license
made-susantho/exercises
d0c12ba32543532498b3922a8690632f2e73b0ec
0a961895f7d4adb0ac0208b5ff488772196d64b8
refs/heads/master
2021-01-17T21:02:20.114711
2016-04-28T09:25:14
2016-04-28T09:25:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,110
java
package com.mitrais.bootcamp.cdi.exercise1; import com.mitrais.bootcamp.cdi.common.payment.BitCoinGateway; import com.mitrais.bootcamp.cdi.common.payment.CashGateway; import com.mitrais.bootcamp.cdi.common.payment.GenericPaymentService; import com.mitrais.bootcamp.cdi.common.payment.PaymentService; import com.mitrais.bootcamp.cdi.common.payment.PayPalGateway; import org.junit.Test; import static org.assertj.core.api.Assertions.*; /** * 4/27/2016 * * @author [email protected] */ public class Test1 { @Test public void testPaymentUsingPaypal(){ PaymentService service = new GenericPaymentService(new PayPalGateway()); assertThat(3).isEqualTo(service.completePayment()); } @Test public void testPaymentUsingBitCoin(){ PaymentService service = new GenericPaymentService(new BitCoinGateway()); assertThat(2).isEqualTo(service.completePayment()); } @Test public void testPaymentUsingCash(){ PaymentService service = new GenericPaymentService(new CashGateway()); assertThat(1).isEqualTo(service.completePayment()); } }
6a302a2b94c2af2702b81793a3e210b6f0bf10c7
52d3dbe2ce681b0489776c00026cf6914bf6314e
/demo-service-consumer-ribbon/src/main/java/jj/fly/spring/cloud/demo/consumer/ribbon/ConsumerRibbonCustomApplication.java
5472ebfa673a8b4e886aefa79edd0616bf668662
[]
no_license
jiangjun0130/spring-cloud-demo
5596729ef4a80d9945d7c3a31e7d8e253a299a9c
4e7b362f3f811d3ca682fdbfefa1177acbca067a
refs/heads/master
2021-09-01T19:21:05.583581
2017-12-28T12:03:53
2017-12-28T12:03:53
115,619,153
0
0
null
null
null
null
UTF-8
Java
false
false
1,037
java
package jj.fly.spring.cloud.demo.consumer.ribbon; import jj.fly.spring.cloud.demo.consumer.config.TestConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; /** * @author jiangjun * @create 2017/11/27 */ @SpringBootApplication @EnableEurekaClient @RibbonClient(name = "eureka-provider", configuration = TestConfiguration.class) public class ConsumerRibbonCustomApplication { @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } public static void main(String[] args) { new SpringApplicationBuilder(ConsumerRibbonCustomApplication.class).web(true).run(args); } }
[ "jiangjun@guozi" ]
jiangjun@guozi
80d1ee9af2cee6f5dc3c54a783f5a1042a0a30c7
5808754e06773ee35ce51e7d6f15830dcaa1f610
/data/src/main/java/com/kramar/data/dbo/UserDbo.java
9f11a173cc9e73a88b88877593ec89ef96bcc2a3
[]
no_license
KramerIT/baraholka
0aebc25e61acee2ca25290bbb39e43e63d0a1653
3b7a6c79479939648cfcfcc1ed5a361939b6a57b
refs/heads/master
2021-07-18T18:59:41.161409
2017-10-24T17:27:17
2017-10-24T17:27:17
104,470,126
0
0
null
null
null
null
UTF-8
Java
false
false
1,224
java
package com.kramar.data.dbo; import com.kramar.data.type.UserRole; import com.kramar.data.type.UserStatus; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; import java.util.UUID; @Entity @Table(name = "users") @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class UserDbo extends AbstractAuditableEntity { private static final long serialVersionUID = -1803488657443938487L; @Column(name = "email") private String email; @Column(name = "password") private String password; @Column(name = "user_name") private String userName; @Column(name = "user_surname") private String userSurname; @Column(name = "user_status") @Enumerated(EnumType.STRING) private UserStatus status; @Column(name = "image_id") private ImageDbo image; @ElementCollection @CollectionTable(name = "user2roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) @Column(name = "role") @Enumerated(EnumType.STRING) private List<UserRole> userRoles; public UserDbo(UUID id) { this.setId(id); this.version = 0L; } }
aaab191d9483a3b6d905dd30f8fba106fc26f51f
64549db26c8409600023a13ad566126eda265e77
/AppProgrammer.java
28c6c7e9cea528b17db5b2d17de7cd1430fd0e19
[]
no_license
p0drickpayne/ITHS-uppgifter
8bfc203398a28e8c60fb35d247d11b9f7d0e6fb2
42a9fff6c00a4d9b1721ae0a6bb05f8f5a66f1d5
refs/heads/master
2020-07-15T23:16:28.349415
2019-09-19T17:51:15
2019-09-19T17:51:15
205,669,759
0
0
null
2019-09-19T17:55:10
2019-09-01T11:56:01
Java
UTF-8
Java
false
false
82
java
package com.company; public class AppProgrammer extends DotNetProgrammer { }
917dfdb9eb71fd57e258b85819b201d926ba4816
eed172282d200f26109766a6eff9cf8e60000d32
/src/test/java/br/com/pedrosa/api/SaleServiceTest.java
8d3ea91c2b1125b7afee4034de5d71076894dc8c
[]
no_license
fabiopedrosa1980/api-demo
a0d0f6ca51dadeb5146815a1a531347d45cf2b2f
61d60ff864d40d696b079ac02b142d45beb9405a
refs/heads/master
2020-04-29T09:24:56.562064
2019-06-15T16:17:54
2019-06-15T16:17:54
176,024,018
0
0
null
null
null
null
UTF-8
Java
false
false
1,361
java
package br.com.pedrosa.api; import static org.junit.Assert.assertNotNull; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import br.com.pedrosa.api.dto.AlbumDTO; import br.com.pedrosa.api.dto.SaleDTO; import br.com.pedrosa.api.dto.SaleInDTO; import br.com.pedrosa.api.exception.ResourceNotFoundException; import br.com.pedrosa.api.service.AlbumService; import br.com.pedrosa.api.service.SaleService; @RunWith(SpringRunner.class) @SpringBootTest public class SaleServiceTest { @Autowired private SaleService saleService; @Autowired private AlbumService albumService; @Test public void sellTest() throws ResourceNotFoundException { SaleInDTO venda = new SaleInDTO(); Set<AlbumDTO> albums = new HashSet<>(); albums.add(albumService.findById(1L)); albums.add(albumService.findById(2L)); albums.add(albumService.findById(3L)); albums.add(albumService.findById(4L)); venda.setAlbuns(albums); SaleDTO vendaDTO = saleService.sell(venda); assertNotNull(vendaDTO); assertNotNull(vendaDTO.getTotalOrder()); assertNotNull(vendaDTO.getCashBack()); assertNotNull(vendaDTO.getDateSale()); } }
597478d77bc06341a630eab161b511e56260902c
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/orientechnologies--orientdb/7eee8cbbfecaf3345a7a80a55b74f2225ffbd60f/before/ODistributedWorker.java
01182e542b092c662ee6ef6306134f9a1ff208d5
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
15,747
java
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.server.distributed.impl; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.spi.exception.DistributedObjectDestroyedException; import com.orientechnologies.common.concur.OTimeoutException; import com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.exception.OConfigurationException; import com.orientechnologies.orient.core.exception.OStorageException; import com.orientechnologies.orient.core.metadata.security.OSecurityUser; import com.orientechnologies.orient.core.metadata.security.OUser; import com.orientechnologies.orient.server.distributed.*; import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION; import com.orientechnologies.orient.server.distributed.task.ORemoteTask; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicLong; /** * Hazelcast implementation of distributed peer. There is one instance per database. Each node creates own instance to talk with * each others. * * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public class ODistributedWorker extends Thread { protected final ODistributedDatabaseImpl distributed; protected final ODistributedServerManager manager; protected final ODistributedMessageServiceImpl msgService; protected final String localNodeName; protected final String databaseName; protected final ArrayBlockingQueue<ODistributedRequest> localQueue; protected final int id; protected volatile ODatabaseDocumentInternal database; protected volatile OUser lastUser; protected volatile boolean running = true; private AtomicLong processedRequests = new AtomicLong(0); private static final long MAX_SHUTDOWN_TIMEOUT = 5000l; public ODistributedWorker(final ODistributedDatabaseImpl iDistributed, final String iDatabaseName, final int i) { id = i; setName("OrientDB DistributedWorker node=" + iDistributed.getLocalNodeName() + " db=" + iDatabaseName + " id=" + i); distributed = iDistributed; localQueue = new ArrayBlockingQueue<ODistributedRequest>(OGlobalConfiguration.DISTRIBUTED_LOCAL_QUEUESIZE.getValueAsInteger()); databaseName = iDatabaseName; manager = distributed.getManager(); msgService = distributed.msgService; localNodeName = manager.getLocalNodeName(); } public void processRequest(final ODistributedRequest request) { try { localQueue.put(request); } catch (InterruptedException e) { ODistributedServerLog.warn(this, localNodeName, null, ODistributedServerLog.DIRECTION.NONE, "Received interruption signal, closing distributed worker thread (worker=%d)", id); shutdown(); } } @Override public void run() { for (long processedMessages = 0; running; processedMessages++) { ODistributedRequestId reqId = null; ODistributedRequest message = null; try { message = readRequest(); if (message != null) { message.getId(); reqId = message.getId(); onMessage(message); } } catch (InterruptedException e) { // EXIT CURRENT THREAD Thread.currentThread().interrupt(); break; } catch (DistributedObjectDestroyedException e) { Thread.currentThread().interrupt(); break; } catch (HazelcastInstanceNotActiveException e) { Thread.currentThread().interrupt(); break; } catch (Throwable e) { try { if (e.getCause() instanceof InterruptedException) Thread.currentThread().interrupt(); else ODistributedServerLog.error(this, localNodeName, reqId != null ? manager.getNodeNameById(reqId.getNodeId()) : "?", ODistributedServerLog.DIRECTION.IN, "Error on executing distributed request %s: (%s) worker=%d", e, message != null ? message.getId() : -1, message != null ? message.getTask() : "-", id); } catch (Throwable t) { ODistributedServerLog.error(this, localNodeName, "?", ODistributedServerLog.DIRECTION.IN, "Error on executing distributed request %s: (%s) worker=%d", e, message != null ? message.getId() : -1, message != null ? message.getTask() : "-", id); } } } ODistributedServerLog.debug(this, localNodeName, null, DIRECTION.NONE, "End of reading requests for database %s", databaseName); } /** * Opens the database. */ public void initDatabaseInstance() { if (database == null) { for (int retry = 0; retry < 100; ++retry) { try { database = distributed.getDatabaseInstance(); // OK break; } catch (OStorageException e) { // WAIT FOR A WHILE, THEN RETRY if (!dbNotAvailable(retry)) return; } catch (OConfigurationException e) { // WAIT FOR A WHILE, THEN RETRY if (!dbNotAvailable(retry)) return; } } if (database == null) { ODistributedServerLog.info(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "Database '%s' not present, shutting down database manager", databaseName); distributed.shutdown(); throw new ODistributedException("Cannot open database '" + databaseName + "'"); } } else if (database.isClosed()) { // DATABASE CLOSED, REOPEN IT database.close(); database = distributed.getDatabaseInstance(); } } protected boolean dbNotAvailable(int retry) { try { ODistributedServerLog.info(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "Database '%s' not present, waiting for it (retry=%d/%d)...", databaseName, retry, 100); Thread.sleep(300); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); return false; } return true; } public void shutdown() { running = false; final int pendingMsgs = localQueue.size(); if (pendingMsgs > 0) ODistributedServerLog.info(this, localNodeName, null, ODistributedServerLog.DIRECTION.NONE, "Received shutdown signal, waiting for distributed worker queue is empty (pending msgs=%d)...", pendingMsgs); interrupt(); try { if (pendingMsgs > 0) try { join(MAX_SHUTDOWN_TIMEOUT); } catch (Exception e) { ODistributedServerLog.debug(this, localNodeName, null, ODistributedServerLog.DIRECTION.NONE, "Interrupted shutdown of distributed worker thread"); } ODistributedServerLog .debug(this, localNodeName, null, ODistributedServerLog.DIRECTION.NONE, "Shutdown distributed worker '%s' completed", getName()); localQueue.clear(); if (database != null) { database.activateOnCurrentThread(); database.close(); } } catch (Exception e) { ODistributedServerLog .warn(this, localNodeName, null, ODistributedServerLog.DIRECTION.NONE, "Error on shutting down distributed worker '%s'", e, getName()); } } public ODatabaseDocumentInternal getDatabase() { return database; } protected ODistributedRequest readRequest() throws InterruptedException { // GET FROM DISTRIBUTED QUEUE. IF EMPTY WAIT FOR A MESSAGE ODistributedRequest req = nextMessage(); if (manager.isOffline()) waitNodeIsOnline(); if (ODistributedServerLog.isDebugEnabled()) { final String senderNodeName = manager.getNodeNameById(req.getId().getNodeId()); ODistributedServerLog .debug(this, localNodeName, senderNodeName, DIRECTION.IN, "Processing request=(%s) sourceNode=%s worker=%d", req, senderNodeName, id); } return req; } protected ODistributedRequest nextMessage() throws InterruptedException { final ODistributedRequest req = localQueue.take(); processedRequests.incrementAndGet(); return req; } /** * Execute the remote call on the local node and send back the result */ protected void onMessage(final ODistributedRequest iRequest) { String senderNodeName = null; for (int retry = 0; retry < 10; retry++) { senderNodeName = manager.getNodeNameById(iRequest.getId().getNodeId()); if (senderNodeName != null) break; try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ODistributedException("Execution has been interrupted"); } } if (senderNodeName == null) { ODistributedServerLog.warn(this, localNodeName, senderNodeName, DIRECTION.IN, "Sender server id %d is not registered in the cluster configuration, discard the request: (%s) (worker=%d)", iRequest.getId().getNodeId(), iRequest, id); sendResponseBack(iRequest, new ODistributedException("Sender server id " + iRequest.getId().getNodeId() + " is not registered in the cluster configuration, discard the request")); return; } final ORemoteTask task = iRequest.getTask(); if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog .debug(this, localNodeName, senderNodeName, DIRECTION.IN, "Received request: (%s) (worker=%d)", iRequest, id); // EXECUTE IT LOCALLY Object responsePayload = null; OSecurityUser origin = null; try { task.setNodeSource(senderNodeName); waitNodeIsOnline(); if (task.isUsingDatabase()) initDatabaseInstance(); // keep original user in database, check the username passed in request and set new user in DB, after document saved, // reset to original user if (database != null) { database.activateOnCurrentThread(); origin = database.getUser(); try { if (iRequest.getUserRID() != null && iRequest.getUserRID().isValid() && (lastUser == null || !(lastUser.getIdentity()) .equals(iRequest.getUserRID()))) { lastUser = database.getMetadata().getSecurity().getUser(iRequest.getUserRID()); database.setUser(lastUser);// set to new user } else origin = null; } catch (Throwable ex) { OLogManager.instance().error(this, "Failed on user switching database. " + ex.getMessage()); } } // EXECUTE THE TASK for (int retry = 1; running; ++retry) { responsePayload = manager.executeOnLocalNode(iRequest.getId(), iRequest.getTask(), database); if (responsePayload instanceof OModificationOperationProhibitedException) { // RETRY try { ODistributedServerLog.info(this, localNodeName, senderNodeName, DIRECTION.IN, "Database is frozen, waiting and retrying. Request %s (retry=%d, worker=%d)", iRequest, retry, id); Thread.sleep(1000); } catch (InterruptedException e) { } } else { // OPERATION EXECUTED (OK OR ERROR), NO RETRY NEEDED if (retry > 1) ODistributedServerLog .info(this, localNodeName, senderNodeName, DIRECTION.IN, "Request %s succeed after retry=%d", iRequest, retry); break; } } } catch (RuntimeException e) { sendResponseBack(iRequest, e); throw e; } finally { if (database != null && !database.isClosed()) { database.activateOnCurrentThread(); if (!database.isClosed()) { database.rollback(); database.getLocalCache().clear(); if (origin != null) database.setUser(origin); } } } sendResponseBack(iRequest, responsePayload); } protected String getLocalNodeName() { return localNodeName; } private void sendResponseBack(final ODistributedRequest iRequest, Object responsePayload) { sendResponseBack(this, manager, iRequest, responsePayload); } static void sendResponseBack(final Object current, final ODistributedServerManager manager, final ODistributedRequest iRequest, Object responsePayload) { if (iRequest.getId().getMessageId() < 0) // INTERNAL MSG return; final String localNodeName = manager.getLocalNodeName(); final String senderNodeName = manager.getNodeNameById(iRequest.getId().getNodeId()); final ODistributedResponse response = new ODistributedResponse(iRequest.getId(), localNodeName, senderNodeName, responsePayload); try { // GET THE SENDER'S RESPONSE QUEUE final ORemoteServerController remoteSenderServer = manager.getRemoteServer(senderNodeName); ODistributedServerLog .debug(current, localNodeName, senderNodeName, ODistributedServerLog.DIRECTION.OUT, "Sending response %s back", response); remoteSenderServer.sendResponse(response); } catch (Exception e) { ODistributedServerLog.debug(current, localNodeName, senderNodeName, ODistributedServerLog.DIRECTION.OUT, "Error on sending response '%s' back: %s", response, e.toString()); } } private void waitNodeIsOnline() throws OTimeoutException { // WAIT THE NODE IS ONLINE AGAIN final ODistributedServerManager mgr = manager.getServerInstance().getDistributedManager(); if (mgr != null && mgr.isEnabled() && mgr.isOffline()) { for (int retry = 0; running; ++retry) { if (mgr != null && mgr.isOffline()) { // NODE NOT ONLINE YET, REFUSE THE CONNECTION ODistributedServerLog.info(this, localNodeName, null, DIRECTION.NONE, "Node is not online yet (status=%s), blocking the command until it is online (retry=%d, queue=%d worker=%d)", mgr.getNodeStatus(), retry + 1, localQueue.size(), id); if (localQueue.size() >= OGlobalConfiguration.DISTRIBUTED_LOCAL_QUEUESIZE.getValueAsInteger()) { // QUEUE FULL, EMPTY THE QUEUE, IGNORE ALL THE NEXT MESSAGES UNTIL A DELTA SYNC IS EXECUTED ODistributedServerLog.warn(this, localNodeName, null, DIRECTION.NONE, "Replication queue is full (retry=%d, queue=%d worker=%d), replication could be delayed", retry + 1, localQueue.size(), id); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } else // OK, RETURN return; } } } public long getProcessedRequests() { return processedRequests.get(); } public void sendShutdown() { running = false; this.interrupt(); } }
2f56ecca2a6c5062ee38847485f739050e80d028
62c86862658badb07b92e5b304f012f675f6a14a
/src/java/Controller/OdemeController.java
4512e0cd243f8aa85b76a3d7593794392f0c2a2b
[]
no_license
beyanerrahim/otel
df105ea164d1ccf8999e4b805fc65e32d74f63bd
381d0601421572d35db8a95b38c632d820c627b9
refs/heads/master
2022-10-22T02:30:17.166186
2020-06-16T19:51:11
2020-06-16T19:51:11
272,798,186
0
0
null
null
null
null
UTF-8
Java
false
false
3,268
java
package Controller; import Dao.OdemeDAO; import Dao.musteriDao; import Entity.Musteri; import Entity.Odeme; import java.io.Serializable; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named @SessionScoped public class OdemeController implements Serializable{ private Odeme odeme; private List<Odeme> odemelist; private OdemeDAO odemeDao; private musteriDao musteridao; private List<Musteri> musterilist; private int page=1; private int pagesize=10; private int pagecount; public void next(){ if(this.page==this.getPagecount()) this.page=1; else this.page++; } public void previous(){ if(this.page==1) this.page=this.getPagecount(); else this.page--; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public int getPagecount() { this.pagecount=(int)Math.ceil(this.getOdemeDao().count()/(double)pagesize); return pagecount; } public void setPagecount(int pagecount) { this.pagecount = pagecount; } public String deleteConfirm(Odeme odeme){ return "confirm_delete2"; } public String delete(){ this.getOdemeDao().remove(this.odeme); this.clearForm(); return "Odeme"; } public void clearForm(){ this.odeme=new Odeme(); } public void updateForm(Odeme odeme){ this.odeme=odeme; } public void update(){ this.getOdemeDao().edit(this.odeme); this.clearForm(); } public void create(){ this.getOdemeDao().create(this.odeme); this.clearForm(); } public Odeme getOdeme() { if(this.odeme==null) this.odeme=new Odeme(); return odeme; } public void setOdeme(Odeme odeme) { this.odeme = odeme; } public List<Odeme> getOdemelist() { this.odemelist=this.getOdemeDao().findAll(page,pagesize); return odemelist; } public void setOdemelist(List<Odeme> odemelist) { this.odemelist = odemelist; } public OdemeDAO getOdemeDao() { if(this.odemeDao==null) this.odemeDao=new OdemeDAO(); return odemeDao; } public void setOdemeDao(OdemeDAO odemeDao) { this.odemeDao = odemeDao; } public musteriDao getMusteridao() { if(this.musteridao==null) this.musteridao=new musteriDao(); return musteridao; } public void setMusteridao(musteriDao musteridao) { this.musteridao = musteridao; } public List<Musteri> getMusterilist() { this.musterilist=this.getMusteridao().findAl(); return musterilist; } public void setMusterilist(List<Musteri> musterilist) { this.musterilist = musterilist; } }
f27ed0caa94740d6ef69e8fb9fb96bed934bd4da
74153e5d64194897940bd4dce572687312780d52
/TenableInterview/backend/src/main/java/tenable/interview/ApplicationStartup/ServletInitializer.java
271fb8c51ba4ee65bda18871e6c428fb8c6c5606
[]
no_license
danlesko/Tenable-Challenge
6d1ef23cc40d535fc75f61341313e9ecddbace1b
cf4cfe27dd08b2c6602ecc2d94d6e32e75416d4e
refs/heads/master
2021-06-17T20:12:38.631989
2017-05-02T04:30:23
2017-05-02T04:30:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
448
java
package tenable.interview.ApplicationStartup; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(GethostsApplication.class); } }
129b23a129dd2047f5e13738277e9a3d82481f2e
e7e497b20442a4220296dea1550091a457df5a38
/java_workplace/sns-xiaonei/xiaonei-guide/branches/shuguo.zhang/trunk/src/main/java/com/xiaonei/reg/guide/action/NoStageFillInfoAction.java
0148ea93c48b63577e506eecdb214cc503e2daf1
[]
no_license
gunner14/old_rr_code
cf17a2dedf8dfcdcf441d49139adaadc770c0eea
bb047dc88fa7243ded61d840af0f8bad22d68dee
refs/heads/master
2021-01-17T18:23:28.154228
2013-12-02T23:45:33
2013-12-02T23:45:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,575
java
/** * */ package com.xiaonei.reg.guide.action; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.dodoyo.opt.DodoyoResource; import com.xiaonei.admin.biz.model.school.SchoolType; import com.xiaonei.antispam.model.CheckResult; import com.xiaonei.platform.core.model.NetworkStatus; import com.xiaonei.platform.core.model.University; import com.xiaonei.platform.core.model.User; import com.xiaonei.platform.core.model.UserBasic; import com.xiaonei.platform.core.opt.base.BaseThreadUtil; import com.xiaonei.platform.core.opt.base.chain.impl.struts.util.BaseActionUtil; import com.xiaonei.reg.common.constants.Globals; import com.xiaonei.reg.guide.action.base.GuideFlowBaseAction; import com.xiaonei.reg.guide.form.NoStageFillInfoForm; import com.xiaonei.reg.guide.logic.FillInfoLogic; import com.xiaonei.reg.guide.logic.StepStatusLogic; import com.xiaonei.reg.guide.util.GuideLogger; import com.xiaonei.reg.register.constants.IRegCheckCodeDef; import com.xiaonei.reg.register.dao.IpTableDAO; import com.xiaonei.reg.register.logic.additional.BirthdayLogic; import com.xiaonei.reg.register.logic.pretreatment.validate.Antispam; import com.xiaonei.reg.register.logic.pretreatment.validate.CheckUniversity; import com.xiaonei.sns.platform.core.opt.ice.impl.SnsAdapterFactory; /** * 无阶段的fillinfo * * @author wangtai * */ public class NoStageFillInfoAction extends GuideFlowBaseAction { // public class NoStageFillInfoAction extends BaseAnonymousAction { private static final String FORWARD_SUCC = "succ"; private static final int CurrentNet = NetworkStatus.CURRENT_NETWORK; private static final int PassNet = NetworkStatus.PASS_NETWORK; private static final int NotNet = 9999999; private static final FillInfoLogic userinfoLogic = FillInfoLogic .getInstance(); /** * 成功后跳转 * * @param request * @param form * @param mapping * @param response * * @param host * * @return */ @Override protected ActionForward succ(HttpServletRequest request, ActionForm form, ActionMapping mapping, HttpServletResponse response) { String rt = check(form, request); if (rt != null) { return err(rt, request, mapping, response); } rt = sb(request, form, mapping, response); if (rt != null) { return err(rt, request, mapping, response); } return null; } /** * 出错流程 * * @param msg * @param request * @param mapping * @param response * @return */ private ActionForward err(String msg, HttpServletRequest request, ActionMapping mapping, HttpServletResponse response) { BaseActionUtil.addErr(request, msg); return initPage(request, mapping); } /** * 检查用户提交数据 * * @param form * @param request * * @return */ private String check(ActionForm form, HttpServletRequest request) { NoStageFillInfoForm fform = (NoStageFillInfoForm) form; User host = BaseThreadUtil.currentHost(request); String rt = null; // switch (fform.getSchoolType()) { // case 0: // if (StringUtils.isEmpty(fform.getHighSchoolName())) { // return "请填写中学"; // } // break; // case 1: // if (StringUtils.isEmpty(fform.getHighSchoolName())) { // return "请填写中学"; // } // break; // case 2: // if (StringUtils.isEmpty(fform.getHighSchoolName())) { // return "请填写中学"; // } // break; // default: // return "请填写中学"; // } // if (0 == fform.getHighschoolyear()) { // return "清填写中学年份"; // } // if (!less17age(request)) { // rt = new CheckHomecity().checkHomecity(String.valueOf(fform // .getHomecityCode()), fform.getHomecityName(), fform // .getHomeprovince()); // if (!IRegCheckCodeDef.OK.equals(rt)) { // return rt; // } // } rt = new CheckUniversity().checkUniversity("1", fform.getUniversityId(), fform.getUniversityname()); if (!IRegCheckCodeDef.OK.equals(rt) && !IRegCheckCodeDef.ERR_NO_INPUT_UNIV.equals(rt)) { return rt; } // if ((fform.getHighschoolyear() >= fform.getUniversityyear()) // || (fform.getHighschoolyear() <= 0 || fform.getUniversityyear() <= // 0)) { // return "日期不合法"; // } // antispam List<String> antispamList = new ArrayList<String>(); antispamList.add(fform.getCompany()); antispamList.add(fform.getDepartment()); antispamList.add(fform.getHighSchoolName()); antispamList.add(fform.getHomecityName()); antispamList.add(fform.getHomeprovince()); antispamList.add(fform.getUniversityname()); for (String antispamStr : antispamList) { if (StringUtils.isEmpty(antispamStr)) continue; CheckResult cr = Antispam.checkAndFilterCR(host.getId(), antispamStr); switch (cr.getFlag()) { case CheckResult.SAFE: break; case CheckResult.PROHIBITED: return DodoyoResource.getString("errors.anti.web"); default: break; } } return null; } /** * 处理用户提交数据 * * @param response * @param mapping * @param request * @param form * * @return */ private String sb(HttpServletRequest request, ActionForm form, ActionMapping mapping, HttpServletResponse response) { int[] netSign = { NotNet, NotNet, NotNet }; NoStageFillInfoForm fform = (NoStageFillInfoForm) form; if (!"".equals(fform.getUniversityname())) { netSign[0] = checkUnivNet(fform, request) ? CurrentNet : PassNet; } if (checkCityNet(fform)) { netSign[1] = (netSign[0] == NotNet) ? CurrentNet : PassNet; } if (checkMsNet(fform)) { netSign[2] = (netSign[1] == NotNet && netSign[0] == NotNet) ? CurrentNet : PassNet; } System.out.println("netSign " + netSign[0] + ", " + netSign[1] + ", " + netSign[2] + ", "); User host = BaseThreadUtil.currentHost(request); GuideLogger.printLog(" host:"+host.getId()+" NOHERE! ",GuideLogger.ERROR); if (netSign[0] != NotNet) saveUniv(fform, netSign[0], host); if (netSign[1] != NotNet) saveCity(fform, netSign[1], host); if (netSign[2] != NotNet) saveMs(fform, netSign[2], host); saveWork(fform,host); return null; } private void saveWork(NoStageFillInfoForm fform, User host) { if ("".equals(StringUtils.trimToEmpty(fform.getCompany()))) { return; } userinfoLogic.saveCompany(host, fform.getCompany()); } /**r * 保存中学网络 * * @param fform * @param netSign */ private void saveMs(NoStageFillInfoForm fform, int netSign, User host) { switch (fform.getSchoolType()) { case SchoolType.TYPE_HIGHSCHOOL: userinfoLogic.saveHighSchool(host, fform.getHighSchoolCode(), fform .getHighschoolyear(), fform.getHighSchoolName(), netSign == CurrentNet, netSign); break; case SchoolType.TYPE_JUNIORSCHOOL: userinfoLogic.saveJuniorSchool(host, fform.getJuniorHighSchoolId(), fform.getHighschoolyear(), fform.getJuniorHighSchoolName(), netSign == CurrentNet, netSign); break; case SchoolType.TYPE_COLLEGESCHOOL: userinfoLogic.saveTechSchool(host, fform.getTechHighSchoolId(), fform.getHighschoolyear(), fform.getTechHighSchoolName(), netSign == CurrentNet, netSign); break; } } /** * 保存地域网络 * * @param fform * @param netSign * @param host */ private void saveCity(NoStageFillInfoForm fform, int netSign, User host) { userinfoLogic.saveLocation(host, fform.getHomeprovince(), fform .getHomecityName(), fform.getHomecityCode(), netSign); } /** * 保存大学网络 * * @param fform * @param netSign * @param host */ private void saveUniv(NoStageFillInfoForm fform, int netSign, User host) { userinfoLogic.saveUniv(host, fform.getUniversityyear(), fform .getUniversityId(), fform.getUniversityname(), "", fform .getDepartment(), netSign); } /** * 判断时候可以加入大学网络 * * @param fform * @param request * @return */ private boolean checkUnivNet(NoStageFillInfoForm fform, HttpServletRequest request) { List<University> univList = null; try { String ip = BaseActionUtil.getClientIP(request); univList = IpTableDAO.getInstance().getUnivByIp(ip); } catch (SQLException e) { e.printStackTrace(); return false; } // 搞ip if (univList != null && univList.size() > 0) { for (int i = 0; i < univList.size(); i++) { if (fform.getUniversityId() == univList.get(i).getId()) { return true; } } } return false; } /** * 判断时候可以加入地域网络 * * @param fform * @return */ private boolean checkCityNet(NoStageFillInfoForm fform) { if (StringUtils.isNotEmpty(fform.getHomecityName()) || StringUtils.isNotEmpty(fform.getHomeprovince())) { return true; } return false; } /** * 判断时候可以加入中学网络 * * @param fform * @return */ private boolean checkMsNet(NoStageFillInfoForm fform) { switch (fform.getSchoolType()) { case SchoolType.TYPE_HIGHSCHOOL: if (StringUtils.isNotEmpty(fform.getHighSchoolName())) return true; break; case SchoolType.TYPE_JUNIORSCHOOL: if (StringUtils.isNotEmpty(fform.getJuniorHighSchoolName())) return true; break; case SchoolType.TYPE_COLLEGESCHOOL: if (StringUtils.isNotEmpty(fform.getTechHighSchoolName())) return true; break; } return false; } /** * 用户年龄是否小于17 * * @param request * @return */ private boolean less17age(HttpServletRequest request) { return BirthdayLogic.getInstance().less17age(request); } @Override protected ActionForward initPage(HttpServletRequest request, ActionMapping mapping) { User host = BaseThreadUtil.currentHost(request); GuideLogger.printLog(" host:"+host.getId()+" NOHERE! ",GuideLogger.ERROR); UserBasic ub = SnsAdapterFactory.getUserBasicAdapter().get(host.getId()); request.setAttribute("age_less_17", less17age(request)); request.setAttribute("user_age", ub.getBirthYear()); return mapping.findForward(FORWARD_SUCC); } @Override protected boolean shouldInit(HttpServletRequest request) { return !"post".equalsIgnoreCase(request.getMethod()); } @Override protected String thisUrl() { return Globals.urlGuide + "/fill-info-ns.do"; } @Override protected int thisStatus() { return StepStatusLogic.STEP_FILLINFO; } @Override protected String nextUrl() { return Globals.urlGuide + "/preview-ns.do"; } }
e7c1c97a74c100476b87e7413d7b57098846bd50
708f214c079455baf1c25d2e5bb16920e7b4d436
/Game_01/src/com/pa/world/FloorTile.java
4170de4807c90f21ecb38e286ae40f9391cc2f72
[]
no_license
LostReny/Zelda_clone
5d1547184dbf56f57de3543a972729693389cd63
d2b7f0562c3332ca2aba2827b46c310dd5ee0a36
refs/heads/main
2023-07-02T18:45:35.837592
2021-07-28T23:14:32
2021-07-28T23:14:32
351,219,944
0
0
null
null
null
null
UTF-8
Java
false
false
185
java
package com.pa.world; import java.awt.image.BufferedImage; public class FloorTile extends Tile { public FloorTile(int x, int y, BufferedImage sprite) { super(x, y, sprite); } }
35c35b9378e0402995301b78aabdfa77b9eb6c7f
fe5c89d2bbeb16546f490b1ec71068f466d1363a
/blog/src/test/java/cn/fenrana/blog/BlogApplicationTests.java
2c822458927949eabe6f3d71f8be97bcf48b8b29
[]
no_license
Fenranaa/fenrana-blog
8ed26c3e0ddc5f4be8aa41930db63178374432d2
327fd457fc230f9580b3ab68539c966f1bae591b
refs/heads/master
2023-01-20T11:02:38.828312
2021-03-14T06:20:34
2021-03-14T06:20:34
238,834,118
0
0
null
2023-01-06T02:32:16
2020-02-07T03:15:13
Vue
UTF-8
Java
false
false
1,459
java
package cn.fenrana.blog; import cn.fenrana.blog.entity.Tag; import cn.fenrana.blog.mapper.ArticleCategoryMapper; import cn.fenrana.blog.mapper.ArticleMapper; import cn.fenrana.blog.mapper.ArticleTagMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import javax.annotation.Resource; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest class BlogApplicationTests { @Resource private ArticleCategoryMapper articleCategoryMapper; @Resource private ArticleTagMapper articleTagMapper; @Resource private ArticleMapper articleMapper; @Test void contextLoads() { // List<Map<String, Object>> maps = articleCategoryMapper.selectCategoryCount(); // System.out.println(maps); // List<Map<String, Object>> maps = articleTagMapper.selectTagCount(); // System.out.println(maps); // List<Map<String, Object>> maps = articleMapper.selectArchiveCount(); // System.out.println(maps); // List<Tag> tags = articleTagMapper.selectTagByArticleId(6L); // System.out.println(tags); Map<String, String> map = new HashMap<>(); map.put("asd", "111"); map.forEach((k,v) -> { System.out.println(k + ":" + v); }); } }
8d6cc1641093d2d34b72c3cb83b3d405da0b8d23
4ff94b58cf007b64e8d7f01214f9ba4200123c44
/src/test/groovy/com/docutools/assignees/AssigneesRequests.java
12542fc79cfcf3e7d2446aad22b1d693a024d17e
[]
no_license
8secz-johndpope/users
82908fffa6d4b5fc6ef2397265bb9e48b582cba6
53903317283964090dd69fb914d8533e88f00b90
refs/heads/master
2022-01-19T03:26:50.225437
2019-07-22T11:33:14
2019-07-22T11:33:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,781
java
package com.docutools.assignees; import com.docutools.users.DocutoolsUser; import com.docutools.team.MembershipState; import com.docutools.contacts.ProjectContact; import com.docutools.team.TeamMembership; import com.docutools.contacts.ProjectContactRepository; import com.docutools.team.TeamMembershipRepo; import com.docutools.roles.PermissionManager; import com.docutools.test.DocutoolsTestUser; import com.docutools.test.TestUserHelper; import io.restassured.RestAssured; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Arrays; import java.util.UUID; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.trustStore; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.when; @Tag("integration") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles({"dev"}) @ExtendWith(SpringExtension.class) public class AssigneesRequests { @LocalServerPort private int port; @Autowired private ProjectContactRepository contactRepository; @Autowired private TeamMembershipRepo membershipRepository; @MockBean private PermissionManager permissionManager; @Autowired private TestUserHelper testUserHelper; private DocutoolsTestUser user; private String token; @BeforeEach public void setup() { RestAssured.port = port; user = testUserHelper.newTestUser(); token = testUserHelper.login(user, port); when(permissionManager.isMember(any())).thenReturn(true); } @Test @DisplayName("List all Assignees.") public void listAllAssignees() { // Arrange UUID projectId = UUID.randomUUID(); // Team Members from Same Company DocutoolsUser userA = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(userA, projectId, MembershipState.Active)); DocutoolsUser userB = testUserHelper.newTestUser(userA.getOrganisation()); membershipRepository.save(new TeamMembership(userB, projectId, MembershipState.Active)); DocutoolsUser userC = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(userC, projectId, MembershipState.Active)); DocutoolsUser removedMember = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(removedMember, projectId, MembershipState.Removed)); ProjectContact contact1 = new ProjectContact(projectId); contact1.setCompanyName("Teuner AV"); contactRepository.save(contact1); ProjectContact contact2 = new ProjectContact(projectId); contact2.setFirstName("Maximilian Vladimir"); contact2.setLastName("Allmayer-Beck"); contactRepository.save(contact2); // Act Assignee[] assignees = given() .accept("application/json") .auth().oauth2(token) .log().all() // .when() .get("/api/v2/projects/{projectId}/assignees/all", projectId) // .then() .log().all() .statusCode(200) .extract().as(Assignee[].class); // Assert assertThat(Arrays.asList(assignees), containsInAnyOrder(new Assignee(userA), new Assignee(userB), new Assignee(userC), new Assignee(contact1), new Assignee(contact2))); assertThat(assignees.length, is(5)); } @Test @DisplayName("List User Assignees from Company.") public void listUserAssigneesFromCompany() { // Arrange UUID projectId = UUID.randomUUID(); DocutoolsUser userA = testUserHelper.newTestUser(); UUID company = userA.getOrganisation().getId(); membershipRepository.save(new TeamMembership(userA, projectId, MembershipState.Active)); DocutoolsUser userB = testUserHelper.newTestUser(userA.getOrganisation()); membershipRepository.save(new TeamMembership(userB, projectId, MembershipState.Active)); DocutoolsUser userC = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(userC, projectId, MembershipState.Active)); ProjectContact contact = new ProjectContact(projectId); contact.setCompanyName("Toys 'R Us"); contactRepository.save(contact); // Act Assignee[] assignees = given() .accept("application/json") .queryParam("company", company) .auth().oauth2(token) .log().all() .when() .get("/api/v2/projects/{projectId}/assignees/all", projectId) .then() .log().all() .statusCode(200) .extract().as(Assignee[].class); // Assert assertThat(Arrays.asList(assignees), containsInAnyOrder(new Assignee(userA), new Assignee(userB))); assertThat(assignees.length, is(2)); } @Test @DisplayName("List Contact Assignees from Company.") public void listContactAssigneesFromCompany() { // Arrange UUID projectId = UUID.randomUUID(); DocutoolsUser removedMember = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(removedMember, projectId, MembershipState.Removed)); ProjectContact contact1 = new ProjectContact(projectId); contact1.setCompanyName("Teuner AV"); contactRepository.save(contact1); ProjectContact contact2 = new ProjectContact(projectId); contact2.setFirstName("Maximilian Vladimir"); contact2.setLastName("Allmayer-Beck"); contactRepository.save(contact2); // Act Assignee[] assignees = given() .accept("application/json") .queryParam("company", contact1.getId()) .auth().oauth2(token) .log().all() .when() .get("/api/v2/projects/{projectId}/assignees/all", projectId) .then() .log().all() .statusCode(200) .extract().as(Assignee[].class); // Assert assertThat(Arrays.asList(assignees), contains(new Assignee(contact1))); assertThat(assignees.length, is(1)); } @Test @DisplayName("List companies.") public void listCompanies() { // Arrange UUID projectId = UUID.randomUUID(); DocutoolsUser userA = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(userA, projectId, MembershipState.Active)); DocutoolsUser userB = testUserHelper.newTestUser(userA.getOrganisation()); membershipRepository.save(new TeamMembership(userB, projectId, MembershipState.Active)); DocutoolsUser userC = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(userC, projectId, MembershipState.Active)); DocutoolsUser removedMember = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(removedMember, projectId, MembershipState.Removed)); ProjectContact contact1 = new ProjectContact(projectId); contact1.setCompanyName("Teuner AV"); contactRepository.save(contact1); ProjectContact contact2 = new ProjectContact(projectId); contact2.setFirstName("Maximilian Vladimir"); contact2.setLastName("Allmayer-Beck"); contactRepository.save(contact2); // Act AssigneeCompany[] companies = given() .accept("application/json") .auth().oauth2(token) .log().all() .when() .get("/api/v2/projects/{projectId}/companies/all", projectId) .then() .log().all() .statusCode(200) .extract().as(AssigneeCompany[].class); // Assert assertThat(Arrays.asList(companies), containsInAnyOrder(new AssigneeCompany(userA.getOrganisation(), userA), new AssigneeCompany(userC.getOrganisation(), userC), new AssigneeCompany(contact1), new AssigneeCompany(contact2))); } @Test @DisplayName("Include removed assignees.") public void includeRemovedAssignees() { // Arrange UUID projectId = UUID.randomUUID(); DocutoolsUser userA = testUserHelper.newTestUser(); membershipRepository.save(new TeamMembership(userA, projectId, MembershipState.Active)); DocutoolsUser userB = testUserHelper.newTestUser(userA.getOrganisation()); membershipRepository.save(new TeamMembership(userB, projectId, MembershipState.Removed)); // Act Assignee[] assignees = given() .accept("application/json") .auth().oauth2(token) .log().all() .when() .get("/api/v2/projects/{projectId}/assignees/all", projectId) .then() .log().all() .statusCode(200) .extract().as(Assignee[].class); assertThat(Arrays.asList(assignees), containsInAnyOrder(new Assignee(userA, MembershipState.Active), new Assignee(userB, MembershipState.Removed))); } }
63dd9685711188b9bfff53af51a57843f6a425ba
8493769ffcb33aa4e70e57e76619b8d82d7c0788
/starting/src/main/java/ru/example/lesson1/Main.java
ab50e8761ee8c482c1dcaebaeae94ad2c8c8948a
[]
no_license
MarsMoldobekov/AlgorithmsAndDataStructures
a18f7c32b1dc1393b5b49c4645222bf5ecc551cc
18936717c8f9e4730ad6c1f9b3fa38d07cb16ca8
refs/heads/master
2023-04-04T03:47:03.324189
2021-04-16T12:27:22
2021-04-16T12:27:22
350,084,690
0
0
null
null
null
null
UTF-8
Java
false
false
8,022
java
package ru.example.lesson1; import java.util.Arrays; import java.util.Random; public class Main { private static record Person(String name) { } private static final int ARRAY_SIZE = 400; public static void main(String[] args) { /* Задание 2.1 На основе программного кода из задания №1 реализуйте массив на основе существующих примитивных или ссылочных типов данных. Выполните обращение к массиву и базовые операции класса Arrays. */ String[] lines = { "Hello, world!", "True", "False", "Cat", "Dog" }; String[] newLines = copyArray(lines); int[] numbers = { 9, 3, 2, 8, 4, 5, 6, 7, 1, 0 }; Person[] persons = { new Person("Mars"), new Person("Andrey"), new Person("Nikita"), new Person("Konstantin") }; printArray(newLines); printArray(persons); compareArrays(lines, newLines); quickSort(createArray()); bubbleSort(createArray()); sortBySelectionMethod(createArray()); sortByInsertion(createArray()); int[] copyNumbers = copyArray(numbers); int[] copyNumbers2 = copyArray(numbers); int[] copyNumbers3 = copyArray(numbers); quickSort(numbers); bubbleSort(copyNumbers); sortBySelectionMethod(copyNumbers2); sortByInsertion(copyNumbers3); printArray(numbers); printArray(copyNumbers); printArray(copyNumbers2); printArray(copyNumbers3); } private static int[] copyArray(int[] array) { return Arrays.copyOf(array, array.length); } private static <T> T[] copyArray(T[] array) { return Arrays.copyOf(array, array.length); } private static void printArray(int[] array) { System.out.println(Arrays.toString(array)); } private static <T> void printArray(T[] array) { System.out.println(Arrays.toString(array)); } private static <T> void compareArrays(T[] array, T[] anotherArray) { System.out.println(Arrays.equals(array, anotherArray)); } /* Задание 2.2 На основе написанного кода в задании 2.1 реализуйте линейный и двоичный поиск. Оценить алгоритмы линейного и двоичного поиска с помощью базового класса System.nanoTime(). */ private static <T> int find(T[] array, T obj) { long l = System.nanoTime(); for (int i = 0; i < array.length; i++) { if (array[i].equals(obj)) { System.out.println("Время выполнения линейного поиска: " + (System.nanoTime() - l)); return i; } } return -1; } private static int binarySearch(int[] array, int element) { int begin = 0; int end = array.length - 1; long l = System.nanoTime(); while (begin <= end) { int middle = (begin + end) / 2; if (array[middle] == element) { System.out.println("Время выполнения бинарного поиска: " + (System.nanoTime() - l)); return middle; } else if (array[middle] < element) { begin = middle + 1; } else { end = middle - 1; } } return -1; } /* Задание 2.3 Создайте массив размером 400 элементов. Выполните сортировку с помощью метода sort(). Оцените сортировку с помощью базового класса System.nanoTime(). */ private static void quickSort(int[] array) { long l = System.nanoTime(); Arrays.sort(array); System.out.println("Время выполнения метода Arrays.sort() для массива с " + array.length + " элеметами: " + (System.nanoTime() - l)); } /* Задание 2.4 На основе существующего массива данных из задания 2.3 реализуйте алгоритм сортировки пузырьком. Оцените сортировку с помощью базового класса System.nanoTime(). Сравните время выполнения алгоритмы сортировки методом sort() из задания 2.1 и сортировку пузырьком. */ private static void bubbleSort(int[] array) { long l = System.nanoTime(); int length = array.length; for (int i = 0; i < length; i++) { for (int j = 1; j < (length - i); j++) { if (array[j - 1] > array[j]) { int temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; } } } System.out.println("Время выполнения пузырьковой сортировки для массива с " + array.length + " элеметами: " + (System.nanoTime() - l)); } /* Задание 2.5 На основе массива данных из задания 2.3 реализуйте алгоритм сортировки методом выбора. Оцените сортировку с помощью базового класса System.nanoTime(). Сравните с временем выполнения алгоритмов сортировки из прошлых заданий 2.3 и 2.4. */ private static void sortBySelectionMethod(int[] array) { long l = System.nanoTime(); for (int min = 0; min < array.length-1; min++) { int least = min; for (int j = min + 1; j < array.length; j++) { if (array[j] < array[least]) { least = j; } } int tmp = array[min]; array[min] = array[least]; array[least] = tmp; } System.out.println("Время выполнения сортировки методом выбора для массива с " + array.length + " элеметами: " + (System.nanoTime() - l)); } /* Задание 2.6 На основе массива данных из задания 2.3 реализуйте алгоритм сортировки методом вставки. Оцените сортировку с помощью базового класса System.nanoTime(). Сравните с временем выполнения алгоритмов сортировки из прошлых заданий 2.3, 2.4 и 2.5. */ private static void sortByInsertion(int[] array) { long l = System.nanoTime(); for (int i = 1; i < array.length; i++) { int key = array[i]; int j = i - 1; while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } System.out.println("Время выполнения сортировки методом вставки для массива с " + array.length + " элеметами: " + (System.nanoTime() - l)); } private static int[] createArray() { int[] array = new int[ARRAY_SIZE]; Random random = new Random(); for (int i = 0; i < ARRAY_SIZE; i++) { array[i] = random.nextInt(100); } return array; } }
1d5fd3e34526d035d32184384ee5547ab51b37da
52dd0f65135edc1aa57e36d5d4de5db9fde51c3b
/TwitterExtractor/src/persistence/entities/hibernate/RegularRecommendationID.java
811eb3418c56cb09c762e69eda21153c373d8d46
[]
no_license
mitchbr91/Semantic-Recommendation---Master
a380ce61418db16e6369d04001864318b293a962
c7893252fdbd882a74183ceaa8ef41fffd404a39
refs/heads/master
2021-01-19T03:51:41.864417
2016-12-06T01:12:30
2016-12-06T01:12:30
50,472,778
0
0
null
null
null
null
UTF-8
Java
false
false
1,517
java
package persistence.entities.hibernate; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class RegularRecommendationID implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 1L; @Column(name = "user_id") private Long userID; @Column(name = "recommendation_id") private Long recommendationID; public RegularRecommendationID(){ } public RegularRecommendationID(Long userID, Long recommendationID){ this.userID = userID; this.recommendationID = recommendationID; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((userID == null) ? 0 : userID.hashCode()); result = prime * result + ((recommendationID == null) ? 0 : recommendationID.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RegularRecommendationID other = (RegularRecommendationID) obj; if (userID == null) { if (other.userID != null) return false; } else if (!userID.equals(other.userID)) return false; if (recommendationID == null) { if (other.recommendationID != null) return false; } else if (!recommendationID.equals(other.recommendationID)) return false; return true; } }
5d0cec37db86d9859c023792cf8fdd458b316bfd
c34c16c923802c7bd63ba7666da7406ea179c8db
/百联-android-20210807/az/skWeiChatBaidu/src/main/java/com/ydd/im/audio/MessageEventVoice.java
b70c132aa7a6420ce25b417b942c0949f8c40a0b
[]
no_license
xeon-ye/bailian
36f322b40a4bc3a9f4cc6ad76e95efe3216258ed
ec84ac59617015a5b7529845f551d4fa136eef4e
refs/heads/main
2023-06-29T06:12:53.074219
2021-08-07T11:56:38
2021-08-07T11:56:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
304
java
package com.ydd.im.audio; /** * Created by Administrator on 2017/6/26 0026. */ public class MessageEventVoice { public final String event; public final long timelen; public MessageEventVoice(String event, long timelen) { this.event = event; this.timelen = timelen; } }
0c2af10148bb5e94ebb63633a707c4f20d98b781
0a9ea6bf15b0899c6ff851f0c80e3646f09d2cac
/src/vrpApp/Main.java
e380a6561d7e9f80a42025ee3e156a9b7ea88e0b
[]
no_license
ecobost/VRPTec
6f5a401d0ef8835fc9f6d56ddf581b8c96cf63c2
dd45c26b751eb2f270c6d68cd437b0b2581c6fc6
refs/heads/master
2021-01-24T23:01:00.944870
2015-09-26T08:50:41
2015-09-26T08:50:41
27,244,879
1
1
null
null
null
null
UTF-8
Java
false
false
282
java
package vrpApp; public class Main { public static void main(String[] args) { Controller controller = new Controller(); final GUI gui = new GUI(controller); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { gui.setVisible(true); } }); } }
b024254a07a06ea8ce78d0152df96e92c3e884c8
9c66f726a3f346fe383c5656046a2dbeea1caa82
/myrobotlab/src/org/myrobotlab/oculus/lwjgl/models/RawModel.java
c7386259478e6a64033a1a182886b5d3e0edba5b
[ "Apache-2.0" ]
permissive
Navi-nk/Bernard-InMoov
c6c9e9ba22a13aa5cbe812b4c1bf5f9f9b03dd21
686fa377141589a38d4c9bed54de8ddd128e2bca
refs/heads/master
2021-01-21T10:29:28.949744
2017-05-23T05:39:28
2017-05-23T05:39:28
91,690,887
0
5
null
null
null
null
UTF-8
Java
false
false
686
java
package org.myrobotlab.oculus.lwjgl.models; /** * Object representing an untextured model. * * @author kwatters * */ public class RawModel { // the vertex array object id private int vaoID; // count of vertices private int vertexCount; // constructor public RawModel(int vaoID, int vertexCount) { super(); this.vaoID = vaoID; this.vertexCount = vertexCount; } // getters and setters public int getVaoID() { return vaoID; } public void setVaoID(int vaoID) { this.vaoID = vaoID; } public int getVertexCount() { return vertexCount; } public void setVertexCount(int vertexCount) { this.vertexCount = vertexCount; } }
a57baddd1187dd34572ba5a2b82c70d593e975e7
d2e042565654b3e75cc710b6b9c64a6b73d36fbf
/springboot/src/main/java/com/ustglobal/springboot/service/EmployeeServiceImpl.java
cfc1f1d61345946dd40b2cc31dc63906a618cb04
[]
no_license
Abhipsha8/USTGlobal-16Sep19-Abhipsha-Satpathy
97cda1f944c781f809b7f69da21b1fb33d064c67
52836cd16c3370950da2241e313e6577214255d0
refs/heads/master
2023-01-09T00:38:44.198535
2019-12-21T14:06:46
2019-12-21T14:06:46
215,537,537
0
0
null
2023-01-07T17:14:22
2019-10-16T12:01:01
JavaScript
UTF-8
Java
false
false
1,137
java
package com.ustglobal.springboot.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ustglobal.springboot.dao.EmployeeDAO; import com.ustglobal.springboot.dto.EmployeeBean; //@Service public class EmployeeServiceImpl implements EmployeeService{ // @Autowired private EmployeeDAO dao; @Override public boolean addEmployee(EmployeeBean bean) { if(bean.getName()==null||bean.getPassword()==null) { return false; }else if(bean.getPassword().length()<8) { return false; } return dao.addEmployee(bean); } @Override public boolean modifyEmployee(EmployeeBean bean) { if(bean.getName()==null||bean.getPassword()==null) { return false; }else if(bean.getPassword().length()<8) { return false; } return dao.modifyEmployee(bean); } @Override public boolean deleteEmployee(int id) { return dao.deleteEmployee(id); } @Override public EmployeeBean getEmployee(int id) { return dao.getEmployee(id); } @Override public List<EmployeeBean> getAllEmployee() { return dao.getAllEmployee(); } }
4c117398530759f78dd7f017349c2e4c369d61f3
42b6141554181cda2db10f5b74be5b3a06af0456
/src/main/java/duke/Storage/TaskListEncoder.java
001c60c40a0d82c4962a8400c2347402867943ea
[]
no_license
franceneee/ip
97e803b574ef0ba1e30bd70c7727b49bfe9e2e02
76d98438ce83345cd091ddfa58de5bd3adefe40c
refs/heads/master
2022-12-27T01:26:40.899653
2020-09-28T04:04:04
2020-09-28T04:04:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,149
java
package duke.Storage; import duke.task.Deadline; import duke.task.Event; import duke.task.Task; import duke.task.ToDo; /** * Encodes TaskList data into a data file for storage. */ public class TaskListEncoder { /** * Formats the task to be printed in text file. * * @param task task to be formatted. * @return the string in the format for the .txt file. */ static String formatTaskForFile(Task task) { String stringToPrint; String doneSymbol = (task.isDone() ? "o" : "x"); if (task instanceof Deadline) { stringToPrint = "D-" + doneSymbol + "-" + ((Deadline) task).getTaskDescription() + "-" + ((Deadline) task).getDueDate(); } else if (task instanceof Event) { stringToPrint = "E-" + doneSymbol + "-" + ((Event) task).getTaskDescription() + "-" + ((Event) task).getTime(); } else { //(task instanceof To-Do) stringToPrint = "T-" + doneSymbol + "-" + ((ToDo) task).getTaskDescription(); } return stringToPrint; } }
6349be8cbd4c2bf9c02c411ddb21286f31f1566a
e769b94e358f154a0364ff98b68b453ceb41933a
/src/main/java/com/course/model/dataCase.java
f7a54025024cfe698758a09221f340b79557b1af
[]
no_license
Lvt-f/InterFaceAutomation
bb0338469049615fd8df99a3a8d44c90b8f570e1
51e6bab802bdff460cc7067390040034d710ebc4
refs/heads/master
2020-04-28T00:55:37.914651
2019-03-10T14:31:23
2019-03-10T14:31:23
174,834,247
1
0
null
null
null
null
UTF-8
Java
false
false
1,757
java
package com.course.model; //解绑时所需的数据 public class dataCase { private String fsseed; private String fsshopguid; private String fsshopstauts; private String fstoken; private String fsupdatetime; public String getFsseed() { return fsseed; } public void setFsseed(String fsseed) { this.fsseed = fsseed; } public String getFsshopguid() { return fsshopguid; } public void setFsshopguid(String fsshopguid) { this.fsshopguid = fsshopguid; } public String getFsshopstauts() { return fsshopstauts; } public void setFsshopstauts(String fsshopstauts) { this.fsshopstauts = fsshopstauts; } public String getFstoken() { return fstoken; } public void setFstoken(String fstoken) { this.fstoken = fstoken; } public String getFsupdatetime() { return fsupdatetime; } public void setFsupdatetime(String fsupdatetime) { this.fsupdatetime = fsupdatetime; } public dataCase(String fsseed, String fsshopguid, String fsshopstauts, String fstoken, String fsupdatetime) { this.fsseed = fsseed; this.fsshopguid = fsshopguid; this.fsshopstauts = fsshopstauts; this.fstoken = fstoken; this.fsupdatetime = fsupdatetime; } @Override public String toString() { return "dataCase{" + "fsseed='" + fsseed + '\'' + ", fsshopguid='" + fsshopguid + '\'' + ", fsshopstauts='" + fsshopstauts + '\'' + ", fstoken='" + fstoken + '\'' + ", fsupdatetime='" + fsupdatetime + '\'' + '}'; } }
c9e7c020390743f14d129a8568e3be64fc71fd95
c7981c1d8d3398a0a3a6f8a10fe6aeae89368550
/spring-boot/spring-boot-payment/src/main/java/tw/waterball/ddd/waber/springboot/payment/presenters/PaymentPresenter.java
27010ba8ebaa27155e2cddc562633a249f03b878
[]
no_license
trend-ouki-wang/Waber
0974e7a57baf8bd482de13598cdf292ae7a7ffcb
bae73379baf18a3a47188e21c344f4725cd0117b
refs/heads/master
2023-06-10T07:35:43.761588
2021-06-29T08:50:09
2021-06-29T08:50:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
589
java
package tw.waterball.ddd.waber.springboot.payment.presenters; import tw.waterball.ddd.model.payment.Payment; import tw.waterball.ddd.waber.api.payment.PaymentView; import tw.waterball.ddd.waber.pricing.usecases.CheckoutPayment; /** * @author Waterball ([email protected]) */ public class PaymentPresenter implements CheckoutPayment.Presenter { private PaymentView paymentView; @Override public void present(Payment payment) { paymentView = PaymentView.toViewModel(payment); } public PaymentView getPaymentView() { return paymentView; } }
f348e308a20ef5b40a1182d304dccf3caf8bc377
fc180e591e97ac0bd02c345570c3bd66a1c0de64
/lms/lms-spi/src/main/java/com/github/shimonxin/lms/spi/subscriptions/Token.java
bdb103efbfa16fd2274c77720790eb7d99042172
[ "Apache-2.0" ]
permissive
shimonxin/light-mqtt-server
e9ff870faa8f72f71782b0f24ab4aa69b78ff2ca
2a28fe74b75f8ab63e4ad467ba1d816537579729
refs/heads/master
2021-01-23T07:30:08.160788
2021-01-12T23:47:52
2021-01-12T23:47:52
15,390,496
10
10
null
2021-01-12T23:38:49
2013-12-23T07:54:13
Java
UTF-8
Java
false
false
1,217
java
package com.github.shimonxin.lms.spi.subscriptions; public class Token { public static final Token EMPTY = new Token(""); public static final Token MULTI = new Token("#"); public static final Token SINGLE = new Token("+"); String name; public Token(String s) { name = s; } public String name() { return name; } public boolean match(Token t) { if (t == MULTI || t == SINGLE) { return false; } if (this == MULTI || this == SINGLE) { return true; } return equals(t); } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Token other = (Token) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public String toString() { return name; } }
6076f3f48bcce7816f0fa247f8a1717abe815493
43067c59ecd06c166c65c3a03252dbc5877aaa34
/src/main/java/repository/jdbc/util/actions/impl/ProjectDeleteAction.java
37dded6a4a5923df6f65b6bd1cbba25062a69572
[]
no_license
agarkovand/pms
47ed59f4f0ef0433b619119dc23a41082f2bb694
40dfb7bae994bc9c50548cd2e57efc4259bdf873
refs/heads/master
2020-03-21T04:02:17.483561
2018-07-07T17:39:10
2018-07-07T17:39:10
138,087,084
0
0
null
2018-07-07T17:39:11
2018-06-20T21:21:00
null
UTF-8
Java
false
false
534
java
package repository.jdbc.util.actions.impl; import java.sql.Connection; import model.Project; import repository.exception.DAOException; import repository.jdbc.util.actions.ProjectAction; public class ProjectDeleteAction extends ProjectAction { public ProjectDeleteAction(Project existingProject) { this.project = existingProject; } @Override public Object[] perform(Connection conn) throws DAOException { dao.set(conn); int affectedRowsCount = dao.delete(project); return new Object[] { affectedRowsCount }; } }
3a32a3384f136017c0f7563e5d5076cd418864ee
f8b745ef5159a9cb496508fd3bf6d7cdd4c487bb
/spring/src/main/java/com/zhaolin81/spring/framework/configproperties/annotation/bean/IBean.java
420a6c01784dcc607129bb7f66ee31ec0737f4ee
[ "Apache-2.0" ]
permissive
zhaolin81/tutorial
73078e0ec95b45dca44efd5e05651279a96f17c5
6841586186e510550deacbb5744cc2a214f38b2d
refs/heads/master
2020-03-11T01:39:02.143282
2018-04-26T11:34:52
2018-04-26T11:34:52
129,697,614
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package com.zhaolin81.spring.framework.configproperties.annotation.bean; /** * Created by zhaolin on 4/16/2018. */ public interface IBean { public String getData(); public void setData(String data); public int getNum(); public void setNum(int num); }
6bc8b3ab508f8454f09cd18f38534865c4487481
39e32f672b6ef972ebf36adcb6a0ca899f49a094
/dcm4jboss-all/tags/DCM4CHEE_2_9_4/dcm4jboss-sar/src/java/org/dcm4chex/archive/util/XSLTUtils.java
bd030f8e2b38d48b0ed7a5f29a1b1b0b0210379c
[ "Apache-2.0" ]
permissive
medicayun/medicayundicom
6a5812254e1baf88ad3786d1b4cf544821d4ca0b
47827007f2b3e424a1c47863bcf7d4781e15e814
refs/heads/master
2021-01-23T11:20:41.530293
2017-06-05T03:11:47
2017-06-05T03:11:47
93,123,541
0
2
null
null
null
null
UTF-8
Java
false
false
4,226
java
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <[email protected]> * Franz Willer <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmObjectFactory; import org.dcm4che.dict.DictionaryFactory; import org.dcm4che.dict.TagDictionary; /** * @author [email protected] * @version $Revision: 2638 $ $Date: 2006-07-19 21:36:59 +0800 (周三, 19 7月 2006) $ * @since Dec 5, 2005 */ public class XSLTUtils { public static Dataset coerce(Dataset ds, Templates tpl, Map xsltParams) throws TransformerConfigurationException, IOException { Dataset coerced = DcmObjectFactory.getInstance().newDataset(); SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler th = tf.newTransformerHandler(tpl); if (xsltParams != null) { Transformer t = th.getTransformer(); for (Iterator iter = xsltParams.entrySet().iterator(); iter.hasNext();) { Map.Entry e = (Map.Entry) iter.next(); t.setParameter((String) e.getKey(), e.getValue()); } } th.setResult(new SAXResult(coerced.getSAXHandler2(null))); ds.writeDataset2(th, null, null, 64, null); ds.putAll(coerced, Dataset.MERGE_ITEMS); return coerced; } public static void writeTo(Dataset ds, File f) throws TransformerConfigurationException, IOException { SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler th = tf.newTransformerHandler(); th.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(f); TagDictionary dict = DictionaryFactory.getInstance().getDefaultTagDictionary(); try { th.setResult(new StreamResult(out)); ds.writeDataset2(th, dict, null, 64, null); } finally { out.close(); } } }
0b7536e2f6f54a145f94d9f275be82013e9ea047
e8b5267df0d6c0b0a0c7135baa9e4b39a3c458f5
/cashbackapp/src/main/java/ma/cashback/app/service/AuditEventService.java
9a153e228c7811aacaad73e9a29c2acc1df61f3c
[]
no_license
zarrouq/cashback
ca47b9f1b71bfd79386dc987c5185c1140a7363d
9cda321fba058fd27e0d1e0b3496a313a70dba4d
refs/heads/master
2021-04-30T15:54:58.320661
2018-02-13T10:53:48
2018-02-13T10:53:48
121,251,726
0
0
null
2020-09-18T14:39:42
2018-02-12T13:45:59
Java
UTF-8
Java
false
false
1,773
java
package ma.cashback.app.service; import ma.cashback.app.config.audit.AuditEventConverter; import ma.cashback.app.repository.PersistenceAuditEventRepository; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.Optional; /** * Service for managing audit events. * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository */ @Service @Transactional public class AuditEventService { private final PersistenceAuditEventRepository persistenceAuditEventRepository; private final AuditEventConverter auditEventConverter; public AuditEventService( PersistenceAuditEventRepository persistenceAuditEventRepository, AuditEventConverter auditEventConverter) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; } public Page<AuditEvent> findAll(Pageable pageable) { return persistenceAuditEventRepository.findAll(pageable) .map(auditEventConverter::convertToAuditEvent); } public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) { return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) .map(auditEventConverter::convertToAuditEvent); } public Optional<AuditEvent> find(Long id) { return Optional.ofNullable(persistenceAuditEventRepository.findOne(id)).map (auditEventConverter::convertToAuditEvent); } }
4b6e09f799448e59dc62aefcdf0b365cf3ee4bec
b9a7e4fb23eb305ceb905acb98ba5c952a9a3e94
/src/main/java/sk/tsystems/akademia/VideoArt/Dao/GenreDao.java
5f2d313cb98b1d4abafe53eaa40e4e318e8c6d45
[]
no_license
TSSKDevAcademy1/MMarek1_VideoArt
be879c9f1143f571deaa7c381cd67d2eddaf5fdc
1c3f7926beba158a5b0fc7343ab5d6a23df8c85f
refs/heads/master
2016-09-05T22:23:46.555769
2015-08-26T07:14:23
2015-08-26T07:14:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
673
java
package sk.tsystems.akademia.VideoArt.Dao; import java.util.List; import sk.tsystems.akademia.VideoArt.JpaHelper; import sk.tsystems.akademia.VideoArt.Model.Genre; public class GenreDao { public void saveGenre(Genre genre) { JpaHelper.beginTransaction(); JpaHelper.getEntityManager().persist(genre); JpaHelper.getEntityManager().flush(); JpaHelper.commitTransaction(); } public void listAllGenres() { JpaHelper.beginTransaction(); List<Genre> genres = JpaHelper.getEntityManager().createQuery("select c from Company c", Genre.class) .getResultList(); for (Genre c : genres) { System.out.println(c); } JpaHelper.commitTransaction(); } }
92010775c183cad0eebe2e2e85eb3a5c71df9a7c
9a964deb156e8b4b822f34387ef97232a6011f0f
/src/main/java/com/kronosad/projects/twitter/kronostwit/data/Version.java
f4929503f57d879e44554dfd700f6c5a7b6ef0b4
[]
no_license
russjr08/KronosTwit
46c14cd23c6b74fbd8feb162367ea7873dec1e17
09c6dbdc6986df9d743984d03e6ba17cda281fd6
refs/heads/master
2016-09-05T14:06:26.102304
2014-03-30T22:45:17
2014-03-30T22:45:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,392
java
package com.kronosad.projects.twitter.kronostwit.data; import com.kronosad.projects.twitter.kronostwit.enums.ReleaseType; import java.net.MalformedURLException; import java.net.URL; /** * User: russjr08 * Date: 12/27/13 * Time: 4:44 PM */ public class Version { private Double version; private String downloadURL; private ReleaseType releaseType; private boolean resetLogin = false; private String changelog; public Version(Double version, String downloadURL, String releaseType, boolean resetLogin, String changelog) { this.version = version; this.downloadURL = downloadURL; this.releaseType = ReleaseType.valueOf(releaseType); this.resetLogin = resetLogin; this.changelog = changelog; } public Double getVersionNumber() { return version; } public URL getDownloadURL() { try { return new URL(downloadURL); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public ReleaseType getReleaseType() { return releaseType; } public boolean needsResetLogin() { return resetLogin; } public URL getChangeLog(){ try { return new URL(changelog); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } }
86741619dc54bfb6e4da3839ab82215f04ae3b7a
4d4450e26c7fabfb126935044cb23979325a2659
/src/communication/test8/MyThread1.java
373269d2e90b3e1124dc9503f6ff35ba9ee182bd
[]
no_license
918273244/hello-word
5e6e8d121b3b25d8a20660c23b109f60b511d7fe
cfb3c2955cf67f9b8600a82a9ca2c54848374e99
refs/heads/master
2020-05-22T15:17:40.029008
2017-03-14T06:15:00
2017-03-14T06:15:02
84,698,197
0
0
null
null
null
null
UTF-8
Java
false
false
267
java
package communication.test8; public class MyThread1 extends Thread{ private Object list; public MyThread1(Object list) { this.list = list; } @Override public void run() { super.run(); Service service = new Service(); service.testMethod(list); } }
b9a52112d65f03b961b596860cfdd9cf3dae6d99
f8237f7807715f7c947f2d87aafb652a8d07c170
/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusContainer.java
713bb0973369320e9559cc85457461b690bbc9ae
[ "Apache-2.0" ]
permissive
TeigLevingston/afc
04ebe94d857ee0c8543a019531867804fa5f124b
45d14d73c288fef6c7da9ce72cb2d2dfa5c8e0d1
refs/heads/master
2023-08-25T03:33:36.320679
2021-10-10T19:46:33
2021-10-10T19:46:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,418
java
/* * $Id$ * This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc * * Copyright (c) 2000-2012 Stephane GALLAND. * Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports, * Universite de Technologie de Belfort-Montbeliard. * Copyright (c) 2013-2020 The original authors, and other authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arakhne.afc.gis.bus.network; import org.arakhne.afc.gis.primitive.GISContainer; /** * BusContainer provides the interface of a container of bus primitives. * * @param <CONTENT> is the type of the object inside this container. * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 14.0 */ public interface BusContainer<CONTENT extends BusPrimitive<?>> extends GISContainer<CONTENT>, BusChangeListener { // }
8dc74fec00a4923e3cfaaab061516dc4ec282714
31a18060483c4f22437361fdcb4fb7a19e7c5557
/cloud-consumeropenfeign-order80/src/main/java/com/mlz/sprigncloud/controller/OrderFeignController.java
5efb2355e28b1eef1ea10a2d023fb3fd286769f3
[]
no_license
malingzhao/cloud-mage
2a4a60a19bd678cc7c1d3befb31eeae0eee36cfb
a69af69782919b129dfe7f1c5dc7d97f77cd13b6
refs/heads/master
2022-06-25T07:42:06.405683
2020-03-25T09:48:15
2020-03-25T09:48:15
249,853,458
0
0
null
2022-06-21T03:03:43
2020-03-25T00:56:34
Java
UTF-8
Java
false
false
1,026
java
package com.mlz.sprigncloud.controller; import com.mlz.sprigncloud.service.PaymentFeignService; import com.mlz.springcloud.entities.CommonResult; import com.mlz.springcloud.entities.Payment; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author mage * @date 2020-03-24 15:56 */ @RestController @Slf4j public class OrderFeignController { @Resource private PaymentFeignService paymentFeignService; @GetMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") long id){ return paymentFeignService.getPaymentById(id); } @GetMapping(value="/consumer/payment/feign/timeout") public String paymentFeignTimeout(){ //openfeign 客户端一般默认等待1s return paymentFeignService.paymentFeignTimeout(); } }
5f7a1378b5cd172291bf321c81f3ad59b95a5b31
72a29294de4ddffe25b537ee7d00fe038ee10a81
/ShoeProjectDemo/src/main/java/com/project/repository/ProductRepository.java
9c7266aa36f231a055ebe051da3d7bec8ec8be89
[]
no_license
tuan15199/finalProjectRepo
d170137ef1b96a8b01b435c2e09d47775e7b41f2
9db0a41b95131f62681fc0f5c4eb8e6e7c8bf592
refs/heads/master
2022-12-26T14:56:28.131677
2020-10-08T17:14:03
2020-10-08T17:14:03
302,334,330
0
0
null
null
null
null
UTF-8
Java
false
false
5,361
java
package com.project.repository; import java.util.List; import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.project.dtos.CatalogDto; import com.project.dtos.ProductDto; import com.project.dtos.ProductReturnDto; import com.project.model.Product; import com.project.model.Status; public interface ProductRepository extends JpaRepository<Product, Integer> { // get all product detail of a product by ID @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE p.id = :id") List<ProductReturnDto> getDetailByProductId(int id); // get a specific product detail of a product by detail ID @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE p.id = :id AND pd.id = :dtid") List<ProductReturnDto> getDetailById(int id, int dtid); // get all product detail of a product which by status @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE pd.status = :status AND p.id = :id") List<ProductReturnDto> getAvailableProductById(Status status, int id); // get all product detail of a product by specific size @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE pd.size = :size AND p.id = :id") List<ProductReturnDto> getProductBySize(int id, int size); // get all product detail that still available by specific size @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE pd.size = :size AND pd.status = :status AND p.id = :id") List<ProductReturnDto> getAvailableProductBySize(int id, int size, Status status); // get info of all product with no detail include @Query("SELECT new com.project.dtos.ProductDto(p.id, p.name, c.type, p.price, b.name, c.id, b.id) " + "FROM Product p JOIN p.catalog c JOIN p.brand b") List<ProductDto> getAll(); // get all product that belong to a specific brand @Query("SELECT new com.project.dtos.ProductDto(p.id, p.name, c.type, p.price, b.name, c.id, b.id) " + "FROM Product p JOIN p.catalog c JOIN p.brand b WHERE b.id = :id") List<ProductDto> getByBrand(int id); // get all product that belong to a specific brand and catalog @Query("SELECT new com.project.dtos.ProductDto(p.id, p.name, c.type, p.price, b.name, c.id, b.id) " + "FROM Product p JOIN p.catalog c JOIN p.brand b WHERE b.id = :brandID AND c.id = :cataId") List<ProductDto> getByBrandAndCatalog(int brandID, int cataId); // get all size of a product @Query(value = "SELECT size FROM product_detail pd join product p on p.id = pd.product_id where p.id = ?", nativeQuery = true) Set<Integer> getSize(@Param("id") int id); // get all catalog of a brand @Query("SELECT new com.project.dtos.CatalogDto(c.type, b.id, c.id) FROM Product p JOIN p.catalog c JOIN p.brand b") List<CatalogDto> getCatalogByBrand(); // get product by id @Query("SELECT new com.project.dtos.ProductDto(p.id, p.name, c.type, p.price, b.name, c.id, b.id) " + "FROM Product p JOIN p.catalog c JOIN p.brand b WHERE p.id = :id") ProductDto getByProID(int id); // get all product details @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b") List<ProductReturnDto> getAllDetail(); // get product details by product detail ID @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE pd.id =:id") ProductReturnDto getDetailByID(int id); // get product details by color @Query("SELECT new com.project.dtos.ProductReturnDto(p.id, pd.id, b.name, p.name, p.price, pd.color, pd.size, pd.genderType, " + "pd.star, pd.status, pd.picture1, pd.picture2, pd.picture3, c.id, c.type) " + "FROM Product p JOIN p.productDetails pd JOIN p.catalog c JOIN p.brand b WHERE pd.color = :color") ProductReturnDto getDetailByColor(String color); }
102e2b7c4d83a469d9ab7eb48acc0e39f9129286
77119929cf14702d557e9bc352909ac04d1516c2
/byh-api/src/main/java/FhirModel/Device.java
3326885c98363fd747a6e065c88eda22bc511ba1
[]
no_license
CheyenneJirout/BookYourHospitalTest
563feb49512da80870cb810cbf84d8a7f17d7c4b
40d1f68686df09b1962e58f326f1c0de929cbcaf
refs/heads/master
2023-03-12T01:08:19.556707
2021-02-27T17:29:25
2021-02-27T17:29:25
342,913,568
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
package FhirModel; public class Device { public Reference owner; public Reference getOwner() { return owner; } public void setOwner(Reference owner) { this.owner = owner; } public DeviceName getDeviceName() { return deviceName; } public void setDeviceName(DeviceName deviceName) { this.deviceName = deviceName; } public DeviceName deviceName; }
6a1c7a0d94fb955b600af24fdeefa48b716b0a72
8d09b4410bd574cc4e4b37c7e6008d9d6d821244
/Hotel Management System/src/DBOperations/Room.java
dc6e3e1d88785ad296b4cf938edc8c39d4fc2264
[]
no_license
MHWije/Hotel-System
b9372201aeaa8286d840347d8eef5b0ddfb83f9f
50e12d8c7d768a1553bd837ba53d4fb14d9dc1ed
refs/heads/master
2021-05-05T09:18:39.490548
2017-11-04T03:51:12
2017-11-04T03:51:12
105,867,987
0
0
null
null
null
null
UTF-8
Java
false
false
4,280
java
/* * 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 DBOperations; import Classes.RoomModel; import Connection.MySQLConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author mhWiJe */ public class Room { //connection Connection conn; PreparedStatement ps=null; ResultSet rs=null; public Room() { conn = MySQLConnection.createConnection(); } //retrieve room table records public ResultSet RoomRecords() { try { String str="SELECT * FROM `room` WHERE isActive=1"; ps=conn.prepareStatement(str); rs=ps.executeQuery(); } catch (Exception e) { System.err.println(e); } return rs; } //retrieve room table records public ResultSet AvailableRoomRecords() { try { String str="SELECT * FROM `room` WHERE isActive=1 AND isAvailable=1"; ps=conn.prepareStatement(str); rs=ps.executeQuery(); } catch (Exception e) { System.err.println(e); } return rs; } //Add Room details public boolean addRoom(RoomModel R){ boolean status = false; try { String insert = "INSERT INTO `room`(roomName,roomCategory,price,numberOfBeds,isAvailable,isActive) " + "VALUES('"+R.getName()+"','"+R.getCategory()+"','"+R.getPrice()+"','"+R.getNoOfBeds()+"','"+1+"','"+1+"')"; ps = conn.prepareStatement(insert); ps.execute(); status = true; } catch (SQLException e) { System.err.println(e); } return status; } //Update Room details public boolean updateRoom(RoomModel R){ boolean status = false; try { String str = "Update `room` set roomName='"+R.getName()+"',roomCategory='"+R.getCategory()+"',price='"+R.getPrice()+"', " + "numberOfBeds='"+R.getNoOfBeds()+"' WHERE idRoom="+R.getId()+" "; ps = conn.prepareStatement(str); ps.execute(); status = true; } catch (SQLException e) { System.err.println(e); } return status; } //Delete Room details public boolean deleteRoom(int id){ boolean status = false; try { String str = "Update `room` set isActive='"+0+"' WHERE idRoom="+id+" "; ps = conn.prepareStatement(str); ps.execute(); status = true; } catch (SQLException e) { System.err.println(e); } return status; } //Retrieve Name for given id public String RoomName(int id) { String name=null; try { String str="SELECT roomName FROM `room` WHERE idRoom='"+id+"'"; ps=conn.prepareStatement(str); rs=ps.executeQuery(); while(rs.next()){ name = rs.getString("roomName"); } } catch (Exception e) { System.err.println(e); } return name; } //get room price public Double RoomPrice(int id) { Double name=null; try { String str="SELECT price FROM `room` WHERE idRoom='"+id+"'"; ps=conn.prepareStatement(str); rs=ps.executeQuery(); while(rs.next()){ name = rs.getDouble("price"); } } catch (Exception e) { System.err.println(e); } return name; } //set availability of room when reserving public boolean RoomAvailability(int id) { boolean status=false; try { String str="Update `room` set isAvailable=0 WHERE idRoom='"+id+"'"; ps=conn.prepareStatement(str); ps.execute(); status=true; } catch (Exception e) { System.err.println(e); } return status; } }//end of class
cd91fddc2646154983fff0a6206e582c9fa633d4
537fb6f51d2ab46a46f3ab451378887fbb5417f2
/src/subject/Pro68.java
89f1cbfb97944f823c03196a7a919a80c526ebb9
[]
no_license
defineYIDA/offer
40b9ab14aff8ad1fc14ec793c01987f4b8913485
41801fcdbf2e41acc3f150962b7aa2e7f53d295c
refs/heads/master
2020-04-26T05:16:18.019780
2019-11-05T13:31:19
2019-11-05T13:31:19
173,328,906
2
0
null
null
null
null
UTF-8
Java
false
false
1,368
java
package subject; import stack.Stack; /** * @Author: zl * @Date: 2019/6/6 16:46 */ public class Pro68 { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || p == null || q == null) { return null; } while (root != null) { if (root.val == p.val || root.val == q.val) { return root; } else if(isExist(root.left, p, q)) { root = root.left; } else if (isExist(root.right, p, q)) { root = root.right; } else { return root; } } return null; } //判断子树中是否存在node节点 private boolean isExist(TreeNode root, TreeNode node, TreeNode node1) { Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; boolean e = false; boolean e1 = false; while (cur != null || !stack.isEmpty()) { if (cur != null) { stack.push(cur.right); if (cur.val == node.val) { e = true; } if (cur.val == node1.val) { e1 = true; } cur = cur.left; } else { cur = stack.pop(); } } return e && e1; } }
0fbc30b832240a8fcbea871f78d78b523d46c2bf
30b34e048aeb2c86dccc3f537841e491e657508e
/src/com/example/Kekeo/util/HttpRequest.java
82a95d6ddb36dc8a307af980be4dda266ace3a14
[]
no_license
gkpoter/Tuling
f6d64749f3e44c054814aa8bb909904ba59128a4
93ca6c26f46367429e6fb684112211af568e33b4
refs/heads/master
2020-12-25T15:09:06.059783
2016-09-03T08:56:23
2016-09-03T08:56:23
67,206,805
0
0
null
null
null
null
UTF-8
Java
false
false
1,702
java
package com.example.Kekeo.util; /** * Created by dy on 2016/8/31. */ import android.content.Context; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; /** * @author HUPENG * 网络访问辅助类 * @version 1.0.1 */ public class HttpRequest { /** * 服务器地,端口号与应用名组成的基本的URL * */ private static final String BASE_URL = "http://183.175.14.250:5002/"; private static AsyncHttpClient client = new AsyncHttpClient(); /** * 发送get请求的方法<br/> * @param context 上下文 * @param url 部分url地址 * @param params 封装了请求参数的类 * @param responseHandler 回调接口 * */ public static void get(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { client.get(context,getAbsoluteUrl(url), params, responseHandler); } /** * 发送post请求的方法<br/> * @param context 上下文 * @param url 部分url地址 * @param params 封装了请求参数的类 * @param responseHandler 回调接口 * */ public static void post(Context context,String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { client.post(context,getAbsoluteUrl(url), params, responseHandler); } /** * 由基本的url+部分url 所组成的完整的url地址</br> * @param relativeUrl 部分url地址 * @return 组成的完整的请求用的url地址 * */ private static String getAbsoluteUrl(String relativeUrl) { return BASE_URL + relativeUrl; } }
05f50a07772d9f77ab18b66f5063130064182af8
dc1e9b70062d3635fef2b42a1db16544081ee299
/Project-Andoird/app/src/main/java/com/example/quananvat/obj/DonHang.java
f66f5904f897ca1284e714dd82619a4f8eb57bc1
[]
no_license
nvdtrieu99/Project-HCI
371da14f9dd39c53a2b9201b2fadbb26f366d9c2
0a8ca928b52219ac69bbeedd1428f2545740dc55
refs/heads/main
2023-02-26T11:00:59.648824
2021-01-30T03:16:40
2021-01-30T03:16:40
334,308,080
0
0
null
null
null
null
UTF-8
Java
false
false
2,849
java
package com.example.quananvat.obj; import java.io.Serializable; import java.util.ArrayList; public class DonHang implements Serializable { private String idnguoidathang; private String tennguoinhan; private String sdtnguoinhan; private String diachinguoinhan; private String thoigiandathang; private String madonhang; private double tongtien; private boolean trangthaithanhtoan; private boolean trangthaigiaohang; private int loaithanhtoan; //0. Vidientu 1. Thanhtoankhinhanhang private ArrayList<ChiTietDonHang> chitietdonhang; public DonHang(){ } public DonHang(String madonhang, boolean trangthaigiaohang) { this.madonhang = madonhang; this.trangthaigiaohang = trangthaigiaohang; } public String getIdnguoidathang() { return idnguoidathang; } public void setIdnguoidathang(String idnguoidathang) { this.idnguoidathang = idnguoidathang; } public int getLoaithanhtoan() { return loaithanhtoan; } public void setLoaithanhtoan(int loaithanhtoan) { this.loaithanhtoan = loaithanhtoan; } public String getTennguoinhan() { return tennguoinhan; } public void setTennguoinhan(String tennguoinhan) { this.tennguoinhan = tennguoinhan; } public String getSdtnguoinhan() { return sdtnguoinhan; } public void setSdtnguoinhan(String sdtnguoinhan) { this.sdtnguoinhan = sdtnguoinhan; } public String getDiachinguoinhan() { return diachinguoinhan; } public void setDiachinguoinhan(String diachinguoinhan) { this.diachinguoinhan = diachinguoinhan; } public String getThoigiandathang() { return thoigiandathang; } public void setThoigiandathang(String thoigiandathang) { this.thoigiandathang = thoigiandathang; } public String getMadonhang() { return madonhang; } public void setMadonhang(String madonhang) { this.madonhang = madonhang; } public double getTongtien() { return tongtien; } public void setTongtien(double tongtien) { this.tongtien = tongtien; } public boolean isTrangthaithanhtoan() { return trangthaithanhtoan; } public void setTrangthaithanhtoan(boolean trangthaithanhtoan) { this.trangthaithanhtoan = trangthaithanhtoan; } public boolean isTrangthaigiaohang() { return trangthaigiaohang; } public void setTrangthaigiaohang(boolean trangthaigiaohang) { this.trangthaigiaohang = trangthaigiaohang; } public ArrayList<ChiTietDonHang> getChitietdonhang() { return chitietdonhang; } public void setChitietdonhang(ArrayList<ChiTietDonHang> chitietdonhang) { this.chitietdonhang = chitietdonhang; } }
11f860b3027273e6fd1ce5d2b6ad230a221ca92d
347a0e5f0e19ca6c2706450b2ecd15813d94b574
/src/main/java/com/acme/tvshows/video/api/v1/model/NavigationAction.java
bfd867a3be9a469e523323060fbb676416f984ee
[]
no_license
mrtxema/tvshows
2e22f0e07f669afca2ac37897d02beb990af3d17
b17b0cca53fb79654aed4ca600c692fc63109970
refs/heads/master
2020-04-16T13:17:51.155707
2017-02-11T23:16:47
2017-02-11T23:16:47
28,198,063
1
0
null
null
null
null
UTF-8
Java
false
false
375
java
package com.acme.tvshows.video.api.v1.model; public class NavigationAction { final String uri; final String postData; public NavigationAction(String uri, String postData) { this.uri = uri; this.postData = postData; } public String getUri() { return uri; } public String getPostData() { return postData; } }
5cf623a4cd1e02f8d837f583d6155b9f0918addc
b4a17bb5aaacfa292420dbd8097d8d62646122ed
/app/src/main/java/info/expensemanager/expfile/activity/AddingFragment.java
defa060b1c6c294d505fbe72926300d59be05b59
[]
no_license
eashwerks/MaterialDesign
bb003202cffe964836c973fdce985799898b5477
a9954bd5268eb961747639bfe76c510d94fe9970
refs/heads/master
2020-06-14T14:44:25.370082
2016-11-30T09:24:16
2016-11-30T09:24:16
75,059,892
0
0
null
null
null
null
UTF-8
Java
false
false
1,024
java
package info.expensemanager.expfile.activity; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import info.expensemanager.expfile.R; /** * Created by Rahul on 10/31/2015. */ public class AddingFragment extends Fragment { public AddingFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_addform, container, false); // Inflate the layout for this fragment return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); } }
8fb5ca5c6dfc4dac534b9df40e0d3835ab939c2b
1e8b4a3fe2945d1d61a8382f7bae59eb847a0cf8
/hamcrest-matchers/java7-hamcrest-matchers/src/main/java/it/ozimov/cirneco/hamcrest/java7/collect/IsIterableContainingInRelativeOrder.java
ebea8ba794ebba86b28498e233344beda7678ef4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
cortilia/cirneco
ed6ce5f073a746b41bf6d7edf22e3974eae78082
35715bcb2fe8888ba977382d5837f03f4ee188b8
refs/heads/master
2020-12-25T03:41:02.062941
2016-01-29T21:40:22
2016-01-29T21:40:22
50,934,514
0
0
null
2016-02-02T16:31:27
2016-02-02T16:31:26
null
UTF-8
Java
false
false
1,670
java
package it.ozimov.cirneco.hamcrest.java7.collect; import static org.hamcrest.Matchers.equalTo; import static it.ozimov.cirneco.hamcrest.java7.collect.utils.IterableUtils.listCopy; import java.util.ArrayList; import java.util.Collection; import org.hamcrest.Matcher; /** * {@inheritDoc} */ public class IsIterableContainingInRelativeOrder<T> extends org.hamcrest.collection.IsIterableContainingInRelativeOrder<T> { public IsIterableContainingInRelativeOrder(final Iterable<Matcher<? super T>> matchers) { super(listCopy(matchers)); } /** * Creates a matcher for {@linkplain Iterable}s that matches when a single pass over the examined * {@linkplain Iterable} yields a series of items, that contains items logically equal to the corresponding item in * the specified items, in the same relative order For example:<br /> * * <p> * <p> * <pre> //Arrange Iterable<String> actual = Arrays.asList("a", "b", "c", "d"); Iterable<String> expected = Arrays.asList("a", "c"); //Assert assertThat(actual, containsInRelativeOrder(expected)); * </pre> * * @param items the items that must be contained within items provided by an examined {@linkplain Iterable} in the * same relative order */ public static <T> Matcher<Iterable<? extends T>> containsInRelativeOrder(final Iterable<T> items) { final Collection<Matcher<? super T>> matchers = new ArrayList<>(); for (final T item : items) { matchers.add(equalTo(item)); } return new IsIterableContainingInRelativeOrder<T>(matchers); } }
7366ffa8ae60a59c5174878b0d9e29eb6fb619ba
a853656ca294e0c6d852542d75e42e0802cc7d37
/src/main/java/com/wxd/my_mall/services/OmsOrderReturnApplyService.java
23ee745786f6314dc8323de761f12ad25a5e11e8
[]
no_license
wxd123456789/first_spring
d3546d909d7ec9b4054b7d86f1923c286ffcd9d9
345c90fdeffaa263fd6c8c2121fb5249f00d0fc7
refs/heads/master
2023-02-05T18:49:15.439025
2020-12-31T08:38:59
2020-12-31T08:38:59
291,776,463
1
0
null
null
null
null
UTF-8
Java
false
false
786
java
package com.wxd.my_mall.services; import com.wxd.my_mall.dto.OmsOrderReturnApplyResult; import com.wxd.my_mall.dto.OmsReturnApplyQueryParam; import com.wxd.my_mall.dto.OmsUpdateStatusParam; import com.wxd.my_mall.mbg.model.OmsOrderReturnApply; import java.util.List; /** * 退货申请管理Service */ public interface OmsOrderReturnApplyService { /** * 分页查询申请 */ List<OmsOrderReturnApply> list(OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum); /** * 批量删除申请 */ int delete(List<Long> ids); /** * 修改申请状态 */ int updateStatus(Long id, OmsUpdateStatusParam statusParam); /** * 获取指定申请详情 */ OmsOrderReturnApplyResult getItem(Long id); }
15b7132bfccd7bf4b94f475478a3a9896f3cf112
763773ad383e67102d4b41845cf53521b057f213
/app/src/test/java/hsleiden/ikpmd3/ExampleUnitTest.java
2ff87751f00d9d501c0a821568f9bfb8577b130a
[]
no_license
jehoofd3/IKPMD
46f9f87f9568818f3e697f7158cbb6cb7ee3137c
5402376f0bbf9aa664ee0fd2d6afc051ca2c3504
refs/heads/master
2021-01-10T09:03:28.477893
2016-01-07T19:10:29
2016-01-07T19:10:29
46,347,508
0
0
null
null
null
null
UTF-8
Java
false
false
293
java
package hsleiden.ikpmd3; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
a2845734200ce51a63d24ed945316fa43b02cc98
0c566a055a2a6bfacbd8a3cb8e6f597e6ba3119a
/app/src/main/java/com/jacob/google/map/offical/CircleDemoActivity.java
1412a89096eda14c14d160399d2d8234c9a9c992
[]
no_license
wangjia55/GoogleMapDemo
8fc819c0de69e3c0deeeab109da38ff457e49be1
04dd3dfa2dafe32d57a189e897f8d3fb6b99cc58
refs/heads/master
2016-09-02T01:57:18.143734
2015-08-04T08:51:14
2015-08-04T08:51:14
40,173,319
0
0
null
null
null
null
UTF-8
Java
false
false
9,409
java
/* Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jacob.google.map.offical; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.jacob.google.map.R; import java.util.ArrayList; import java.util.List; /** * This shows how to draw circles on a map. */ public class CircleDemoActivity extends FragmentActivity implements OnSeekBarChangeListener, OnMarkerDragListener, OnMapLongClickListener { private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689); private static final double DEFAULT_RADIUS = 1000000; public static final double RADIUS_OF_EARTH_METERS = 6371009; private static final int WIDTH_MAX = 50; private static final int HUE_MAX = 360; private static final int ALPHA_MAX = 255; private GoogleMap mMap; private List<DraggableCircle> mCircles = new ArrayList<DraggableCircle>(1); private SeekBar mColorBar; private SeekBar mAlphaBar; private SeekBar mWidthBar; private int mStrokeColor; private int mFillColor; private class DraggableCircle { private final Marker centerMarker; private final Marker radiusMarker; private final Circle circle; private double radius; public DraggableCircle(LatLng center, double radius) { this.radius = radius; centerMarker = mMap.addMarker(new MarkerOptions() .position(center) .draggable(true)); radiusMarker = mMap.addMarker(new MarkerOptions() .position(toRadiusLatLng(center, radius)) .draggable(true) .icon(BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_AZURE))); circle = mMap.addCircle(new CircleOptions() .center(center) .radius(radius) .strokeWidth(mWidthBar.getProgress()) .strokeColor(mStrokeColor) .fillColor(mFillColor)); } public DraggableCircle(LatLng center, LatLng radiusLatLng) { this.radius = toRadiusMeters(center, radiusLatLng); centerMarker = mMap.addMarker(new MarkerOptions() .position(center) .draggable(true)); radiusMarker = mMap.addMarker(new MarkerOptions() .position(radiusLatLng) .draggable(true) .icon(BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_AZURE))); circle = mMap.addCircle(new CircleOptions() .center(center) .radius(radius) .strokeWidth(mWidthBar.getProgress()) .strokeColor(mStrokeColor) .fillColor(mFillColor)); } public boolean onMarkerMoved(Marker marker) { if (marker.equals(centerMarker)) { circle.setCenter(marker.getPosition()); radiusMarker.setPosition(toRadiusLatLng(marker.getPosition(), radius)); return true; } if (marker.equals(radiusMarker)) { radius = toRadiusMeters(centerMarker.getPosition(), radiusMarker.getPosition()); circle.setRadius(radius); return true; } return false; } public void onStyleChange() { circle.setStrokeWidth(mWidthBar.getProgress()); circle.setFillColor(mFillColor); circle.setStrokeColor(mStrokeColor); } } /** Generate LatLng of radius marker */ private static LatLng toRadiusLatLng(LatLng center, double radius) { double radiusAngle = Math.toDegrees(radius / RADIUS_OF_EARTH_METERS) / Math.cos(Math.toRadians(center.latitude)); return new LatLng(center.latitude, center.longitude + radiusAngle); } private static double toRadiusMeters(LatLng center, LatLng radius) { float[] result = new float[1]; Location.distanceBetween(center.latitude, center.longitude, radius.latitude, radius.longitude, result); return result[0]; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.circle_demo); mColorBar = (SeekBar) findViewById(R.id.hueSeekBar); mColorBar.setMax(HUE_MAX); mColorBar.setProgress(0); mAlphaBar = (SeekBar) findViewById(R.id.alphaSeekBar); mAlphaBar.setMax(ALPHA_MAX); mAlphaBar.setProgress(127); mWidthBar = (SeekBar) findViewById(R.id.widthSeekBar); mWidthBar.setMax(WIDTH_MAX); mWidthBar.setProgress(10); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { mColorBar.setOnSeekBarChangeListener(this); mAlphaBar.setOnSeekBarChangeListener(this); mWidthBar.setOnSeekBarChangeListener(this); mMap.setOnMarkerDragListener(this); mMap.setOnMapLongClickListener(this); mFillColor = Color.HSVToColor( mAlphaBar.getProgress(), new float[] {mColorBar.getProgress(), 1, 1}); mStrokeColor = Color.BLACK; DraggableCircle circle = new DraggableCircle(SYDNEY, DEFAULT_RADIUS); mCircles.add(circle); // Move the map so that it is centered on the initial circle mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 4.0f)); } @Override public void onStopTrackingTouch(SeekBar seekBar) { // Don't do anything here. } @Override public void onStartTrackingTouch(SeekBar seekBar) { // Don't do anything here. } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (seekBar == mColorBar) { mFillColor = Color.HSVToColor(Color.alpha(mFillColor), new float[] {progress, 1, 1}); } else if (seekBar == mAlphaBar) { mFillColor = Color.argb(progress, Color.red(mFillColor), Color.green(mFillColor), Color.blue(mFillColor)); } for (DraggableCircle draggableCircle : mCircles) { draggableCircle.onStyleChange(); } } @Override public void onMarkerDragStart(Marker marker) { onMarkerMoved(marker); } @Override public void onMarkerDragEnd(Marker marker) { onMarkerMoved(marker); } @Override public void onMarkerDrag(Marker marker) { onMarkerMoved(marker); } private void onMarkerMoved(Marker marker) { for (DraggableCircle draggableCircle : mCircles) { if (draggableCircle.onMarkerMoved(marker)) { break; } } } @Override public void onMapLongClick(LatLng point) { // We know the center, let's place the outline at a point 3/4 along the view. View view = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getView(); LatLng radiusLatLng = mMap.getProjection().fromScreenLocation(new Point( view.getHeight() * 3 / 4, view.getWidth() * 3 / 4)); // ok create it DraggableCircle circle = new DraggableCircle(point, radiusLatLng); mCircles.add(circle); } }
dbb6106311062d2d39d99b36442cb4b7b2fa6dae
5700d9c0d9bce8f1a30283accdd7595c29aa9a04
/Simulador/src/drcl/comp/Port.java
5c2c3a07a3bbc6f0173511a14b2a2e4676e50d74
[ "Apache-2.0" ]
permissive
yunxao/JN-Sim
a6588578671d11952bf23723526fa27303630af4
313fad9818968b688275147b129ecf83ecc2d734
refs/heads/master
2016-09-02T02:51:56.785806
2015-01-23T15:10:06
2015-01-23T15:10:06
29,734,723
0
0
null
null
null
null
UTF-8
Java
false
false
44,666
java
// @(#)Port.java 2/2004 // Copyright (c) 1998-2004, Distributed Real-time Computing Lab (DRCL) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of "DRCL" nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // package drcl.comp; import java.util.*; import drcl.data.*; import drcl.comp.contract.*; /** * The implementation of a port in the autonomous component architecture (ACA). * A port has separate input and output channels. Each channel can be * connected to a different {@link Wire}. The wire that is connected to the * input channel is called the "in-wire" of the port. The wire that is * connected to the output channel is called the "out-wire" of the port. * Use {@link #getInWire()} and {@link #getOutWire()} to access those wires. * * @see Component * @see Wire */ public class Port extends drcl.DrclObj { /** Set to true to make ports created from now execution boundary.*/ public static boolean EXECUTION_BOUNDARY = true; /** The duplex port type. */ public final static int PortType_INOUT = 0; /** The input-only port type. */ public final static int PortType_IN = 1; /** The output-only port type. */ public final static int PortType_OUT = 2; /** The server port type */ public final static int PortType_SERVER = 3; /** The event port type */ public final static int PortType_EVENT = 4; /** The <i>fork</i> port type */ public final static int PortType_FORK = 5; final static String[] PortType_ALL = new String[]{ "IN&OUT", "IN", "OUT", "SERVER", "EVENT", "FORK" }; // private void ___FLAG___() {} // // Mask of the port type encoded in the port flag, default is PortType_INOUT static final int Flag_TYPE = 7; // first 3 bits // Bit mask of the "execution boundary" flag, default is on // Turn off the flag to have the thread which delivers data to the port // continue processing the data in the host component. static final int Flag_EXEBOUNDARY = 1 << 3; // Bit mask of the "removable" flag, default is on static final int Flag_REMOVABLE = 1 << 4; // Bit mask of the "shadow port" flag, default is off static final int Flag_SHADOW = 1 << 5; // Bit mask of the "trace" flag, default is off static final int Flag_TRACE_SEND = 1 << 6; //static final int Flag_TRACE_DATA = 1 << 7; // Bit mask of the "event export" flag, default is on static final int Flag_EVENT_EXPORT= 1 << 8; /** ID of the port group this port belongs to. Must use {@link #setGroupID(String)} or {@link #set(String, String)} to set the group ID of a port because it affects the bookkeeping in the host component. */ public String groupID; /** ID of the port, unique in the port group it belongs to. Must use {@link #setID(String)} or {@link #set(String, String)} to set the ID of a port because it affects the bookkeeping in the host component. @see #groupID */ public String id; // The component that contains the port. public Component host; protected Wire outwire, inwire; // By default, exe boundary, removable and event export int flag = EXECUTION_BOUNDARY? (Flag_EXEBOUNDARY | Flag_REMOVABLE | Flag_EVENT_EXPORT): (Flag_REMOVABLE | Flag_EVENT_EXPORT); // separate this from other flags for performance reason boolean flagTraceData = false; public static final Object SEND_RCV_REQUEST = "SEND_RCV_REQ"; // private void ___CONSTRUCTOR_INIT___() {} // /** Constructor, default duplex port type. */ public Port() { this(PortType_INOUT); } /** Constructor, with specified port type. */ public Port(int type_) { setType(type_); } /** Constructor, with specified port type and properties. */ public Port(int type_, boolean exeBoundary_) { this(type_); if (!exeBoundary_) flag = flag & ~Flag_EXEBOUNDARY; } public final void reset() { } // private void ___PROPERTIES___() {} // /** Sets the host component. */ public final void setHost(Component host_) { host = host_; } /** Returns the host component. */ public final Component getHost() { return host; } /** * Sets the id of the group this port belongs to. * Returns false if failed. */ public final boolean setGroupID(String groupID_) { if (id == null) { groupID = groupID_== null? null: groupID_.intern(); return true; } else return _set(groupID_, id); } /** Get the id of the group this port belongs to. */ public final String getGroupID() { return groupID; } /** * Set the id of the port, unique in the port group it belongs to. * Returns false if failed. */ public final boolean setID(String id_) { if (groupID == null) { id = id_== null? null: id_.intern(); return true; } else return _set(groupID, id_); } /** Sets the group ID and port ID of this port. */ public final boolean set(String gid_, String id_) { if (gid_ != null) gid_ = gid_.intern(); if (id_ != null) id_ = id_.intern(); return _set(gid_, id_); } boolean _set(String gid_, String id_) { if (host != null && (gid_ == null || id_ == null)) return false; if (host == null || gid_ == null || id == null) { groupID = gid_; id = id_; return true; } else { if (host.getPort(gid_, id_) != null) return false; boolean removable_ = isRemovable(); if (!removable_) setRemovable(true); host.removePort(this); host.addPort(this, gid_, id_); if (!removable_) setRemovable(false); return true; } } /** Returns the id of the port. */ public final String getID() { return id; } public final void setType(int type_) { flag &= ~Flag_TYPE; flag |= type_; } public final void setType(String type_) { for (int i=0; i<PortType_ALL.length; i++) if (type_.equals(PortType_ALL[i])) { setType(i); return; } } /** Returns the port type of this port. */ public final String getTypeInString() { try { return PortType_ALL[flag & Flag_TYPE]; } catch (Exception e_) { return "UNKNOWN"; } } public final int getType() { return flag & Flag_TYPE; } public final void setExecutionBoundary(boolean flag_) { if (flag_) flag |= Flag_EXEBOUNDARY; else flag &= ~Flag_EXEBOUNDARY; } public final boolean isExecutionBoundary() { return (flag & Flag_EXEBOUNDARY) != 0; } public final int getFlag() { return flag; } public final void setRemovable(boolean flag_) { if (flag_) flag |= Flag_REMOVABLE; else flag &= ~Flag_REMOVABLE; } public final boolean isRemovable() { return (flag & Flag_REMOVABLE) != 0; } public final void setTraceEnabled(boolean enabled_) { if (!isShadow()) flagTraceData = enabled_; if (enabled_) { if (isShadow() && !flagTraceData) { //if ((flag & Flag_TRACE_DATA) == 0) { // flag |= Flag_TRACE_DATA; flagTraceData = enabled_; if (inwire != null) inwire.inEvtListeners = new PortPack(this, inwire.inEvtListeners); } if ((flag & Flag_TRACE_SEND) == 0) { flag |= Flag_TRACE_SEND; if (outwire != null) outwire.outEvtListeners = new PortPack(this, outwire.outEvtListeners); } } else { if (isShadow() && flagTraceData) { //if ((flag & Flag_TRACE_DATA) != 0) { // flag &= ~Flag_TRACE_DATA; flagTraceData = enabled_; if (inwire != null) inwire.inEvtListeners = inwire._removePort(inwire.inEvtListeners, this); } if ((flag & Flag_TRACE_SEND) != 0) { flag &= ~Flag_TRACE_SEND; if (outwire != null) outwire.outEvtListeners = outwire._removePort(outwire.outEvtListeners, this); } } } public final void setDataTraceEnabled(boolean enabled_) { if (!isShadow()) flagTraceData = enabled_; //else if (enabled_ ^ (flag & Flag_TRACE_DATA) != 0) { else if (enabled_ ^ flagTraceData) { if (enabled_) { // flag |= Flag_TRACE_DATA; flagTraceData = enabled_; if (inwire != null) inwire.inEvtListeners = new PortPack(this, inwire.inEvtListeners); } else { // flag &= ~Flag_TRACE_DATA; flagTraceData = enabled_; if (inwire != null) inwire.inEvtListeners = inwire._removePort(inwire.inEvtListeners, this); } } } public final boolean isDataTraceEnabled() //{ return (flag & Flag_TRACE_DATA) != 0; } { return flagTraceData; } public final void setSendTraceEnabled(boolean enabled_) { if (enabled_ ^ (flag & Flag_TRACE_SEND) != 0) { if (enabled_) { flag |= Flag_TRACE_SEND; if (outwire != null) outwire.outEvtListeners = new PortPack(this, outwire.outEvtListeners); } else { flag &= ~Flag_TRACE_SEND; if (outwire != null) outwire.outEvtListeners = outwire._removePort(outwire.outEvtListeners, this); } } } public final boolean isSendTraceEnabled() { return (flag & Flag_TRACE_SEND) != 0; } public final void setEventExportEnabled(boolean enabled_) { if (enabled_) flag |= Flag_EVENT_EXPORT; else flag &= ~Flag_EVENT_EXPORT; } public final boolean isEventExportEnabled() { return (flag & Flag_EVENT_EXPORT) != 0; } public final boolean isShadow() { return (flag & Flag_SHADOW) != 0; } public void setShadow(boolean flag_) { if (flag_ ^ (flag & Flag_SHADOW) != 0) { if (flag_ ^ anyClient()) { if (flag_) throw new PortException("Port has no client to become shadow: " + this); else throw new PortException("Port has at least one client. " + "Cannot become nonshadow: " + this); } _setShadow(flag_); } } void _setShadow(boolean flag_) { if (flag_) { if (inwire != null) inwire._moveToShadow(this); if (outwire != inwire && outwire != null) outwire._moveToShadow(this); flag |= Flag_SHADOW; } else { if (inwire != null) inwire._moveOutOfShadow(this); if (outwire != inwire && outwire != null) outwire._moveOutOfShadow(this); flag &= ~Flag_SHADOW; } } public final Contract getContract() { if (anyClient()) { // this port is a shadow port Port[] pp_ = getConceptualClients(); Vector vContract_ = new Vector(); for (int i=0; i<pp_.length; i++) if (pp_[i] != null) vContract_.addElement(pp_[i].getContract()); if (vContract_.size() == 0) return ContractAny.INSTANCE; else if (vContract_.size() == 1) return (Contract)vContract_.firstElement(); else { // create a multiple-contract Contract[] cc_ = new Contract[vContract_.size()]; vContract_.copyInto(cc_); return new ContractMultiple(cc_); } } else { return Component.getContract(this); } } public Wire getOutWire() { return outwire; } public Wire getInWire() { return inwire; } /** Returns true if the port connects to or shadows for at least one port. */ public final boolean anyConnection() { if (outwire != null && outwire.anyPortExcept(this)) return true; if (inwire != null && inwire != outwire) return inwire.anyPortExcept(this); return false; } /** Returns true if the port connects to or shadows for at least one port. */ public final boolean anyOutConnection() { if (outwire != null && outwire.anyPortExcept(this)) return true; return false; } /** * Clients = InClients + OutClients. * @see {@link #getInClients()} * @see {@link #getOutClients()} */ public final boolean anyClient() { if (outwire == null && inwire == null) return false; Port[] tmp_ = null; if (outwire != null) { tmp_ = outwire.getPortsExcept(this); for (int i=0; i<tmp_.length; i++) if (host == tmp_[i].host.parent) return true; } if (inwire != null) { tmp_ = inwire.getPortsExcept(this); for (int i=0; i<tmp_.length; i++) if (host == tmp_[i].host.parent) return true; } return false; } Port[] _getAllConnectedPorts(boolean removeDuplicate_) { if (inwire == null && outwire == null) return new Port[0]; Port[] pp1 = inwire == null? new Port[0]: inwire.getPortsExcept(this); Port[] pp2 = outwire == null? new Port[0]: outwire.getPortsExcept(this); return _merge(pp1, pp2, removeDuplicate_); } // merge pp1 and pp2 to a new array // pp1 and pp2 and their elements cannot be null // assume pp1 and pp2 do not contain duplicates static Port[] _merge(Port[] pp1, Port[] pp2, boolean removeDuplicate_) { if (removeDuplicate_) { LinkedList ll = new LinkedList(); HashMap map_ = new HashMap(); // put pp1 to map for (int i=0; i<pp1.length; i++) map_.put(pp1[i], pp1[i]); // check if any port in pp2 also appear in pp1 for (int i=0; i<pp2.length; i++) if (!map_.containsKey(pp2[i])) ll.add(pp2[i]); pp2 = (Port[])ll.toArray(new Port[ll.size()]); } Port[] tmp_ = new Port[pp1.length + pp2.length]; System.arraycopy(pp1, 0, tmp_, 0, pp1.length); System.arraycopy(pp2, 0, tmp_, pp1.length, pp2.length); return tmp_; } /** * Clients = InClients + OutClients. * @see {@link #getInClients()} * @see {@link #getOutClients()} */ public final Port[] getClients() { if (inwire == null && outwire == null) return new Port[0]; Port[] in_ = getInClients(); Port[] out_ = getOutClients(); return _merge(in_, out_, true); } /** * OutClients: the set of ports at which if data is sent, * the data would arrive at this port. */ public final Port[] getOutClients() { if (outwire == null) return new Port[0]; Port[] tmp_ = outwire.getOutPorts(); if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (host.isAncestorOf(p_.host)) v_.addElement(p_); } tmp_ = new Port[v_.size()]; v_.copyInto(tmp_); return tmp_; } /** * InClients: the set of ports at which if data is sent, * the data would arrive at this port. */ public final Port[] getInClients() { if (inwire == null) return new Port[0]; Port[] tmp_ = inwire.getInPorts(); if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (host.isAncestorOf(p_.host)) v_.addElement(p_); } tmp_ = new Port[v_.size()]; v_.copyInto(tmp_); return tmp_; } /** * ConceptualClients = ConceptualOutClients + ConceptualInClients. * @see {@link #getConceptualInClients()} * @see {@link #getConceptualOutClients()} */ public final Port[] getConceptualClients() { if (inwire == null && outwire == null) return new Port[0]; Port[] in_ = getConceptualInClients(); Port[] out_ = getConceptualOutClients(); return _merge(in_, out_, true); } /** * ConceptualOutClients: the OutClients that belong to direct child * components. */ public final Port[] getConceptualOutClients() { if (inwire == null) return new Port[0]; Port[] tmp_ = outwire.getOutPorts(); if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (host == p_.host.parent) v_.addElement(p_); } tmp_ = new Port[v_.size()]; v_.copyInto(tmp_); return tmp_; } /** * ConceptualInClients: the InClients that belong to direct child * components. */ public final Port[] getConceptualInClients() { if (outwire == null) return new Port[0]; Port[] tmp_ = inwire.getInPorts(); if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (host == p_.host.parent) v_.addElement(p_); } tmp_ = new Port[v_.size()]; v_.copyInto(tmp_); return tmp_; } /** Any peer conntected to this port? Peer = InPeer or OutPeer. * @see {@link #getInPeers()} * @see {@link #getOutPeers()} */ public final boolean anyPeer() { if (inwire == null && outwire == null) return false; Port[] tmp_ = _getAllConnectedPorts(false); for (int i=0; i<tmp_.length; i++) if (!host.isAncestorOf(tmp_[i].host)) return true; return false; } /** * Peers = InPeers + OutPeers. * @see {@link #getInPeers()} * @see {@link #getOutPeers()} */ public final Port[] getPeers() { if (inwire == null && outwire == null) return new Port[0]; return _getPeers(_getAllConnectedPorts(true)); } /** * OutPeers: the set of ports (including shadow ports) at which if data * is sent, the data would arrive at this port. */ public final Port[] getOutPeers() { if (inwire == null) return new Port[0]; return _getPeers(inwire.getOutPorts()); } /** * InPeers: if data is sent at this port, the set of * ports (including shadow ports) at which the data would arrive. */ public final Port[] getInPeers() { if (outwire == null) return new Port[0]; return _getPeers(outwire.getInPorts()); } // identifies and returns peers of this port (including ancestor ports) Port[] _getPeers(Port[] tmp_) { if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (p_ == null) System.out.println("Port: oops..."); if (!host.isAncestorOf(p_.host)) v_.addElement(p_); } return (Port[])v_.toArray(new Port[v_.size()]); } /** * ConceptualInPeers: the InPeers except those are hidden by * outer components. */ public final Port[] getConceptualInPeers() { Port[] ancestorsOut = getOutAncestors(); Port[] shadowsIn = outwire == null? new Port[0]: outwire.getShadowInPorts(); Port[] connectedTo = getInPeers(); // find my shadow out ports int nshadow = 0; Component outermost = null; Component innermost = null; for (int i=0; i<ancestorsOut.length; i++) { Port p = ancestorsOut[i]; if (p.host.isAncestorOf(this.host)) { if (nshadow == 0) outermost = innermost = p.host; else if (p.host.isAncestorOf(outermost)) outermost = p.host; else if (innermost.isAncestorOf(p.host)) innermost = p.host; ancestorsOut[nshadow++] = p; } } LinkedList ll = new LinkedList(); for (int i=0; i<connectedTo.length; i++) { Port p = connectedTo[i]; if (nshadow > 0 && !innermost.isAncestorOf(p.host)) continue; // dont consider this connection boolean pass_ = true; for (int j=0; pass_ && j<shadowsIn.length; j++) if (shadowsIn[j].host.isAncestorOf(p.host)) pass_ = false; if (pass_) ll.add(p); } return (Port[])ll.toArray(new Port[ll.size()]); } /** Returns all the ancestor ports (def: the host of which contains * the host of this port. */ public final Port[] getAncestors() { if (inwire == null && outwire == null) return new Port[0]; return _getAncestors(_getAllConnectedPorts(true)); } /** Returns all the ancestor out ports (def: the host of which contains * the host of this port. */ public final Port[] getOutAncestors() { if (outwire == null) return new Port[0]; return _getAncestors(outwire.getShadowOutPorts()); } /** Returns all the ancestor in ports (def: the host of which contains * the host of this port. */ public final Port[] getInAncestors() { if (inwire == null) return new Port[0]; return _getAncestors(inwire.getShadowInPorts()); } // identifies and returns ancestors of this port Port[] _getAncestors(Port[] tmp_) { if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (p_.host.isAncestorOf(host)) v_.addElement(p_); } return (Port[])v_.toArray(new Port[v_.size()]); } public final Port[] getShadows() { if (inwire == null && outwire == null) return new Port[0]; return _getShadows(_getAllConnectedPorts(true)); } public final Port[] getOutShadows() { if (outwire == null) return new Port[0]; return _getShadows(outwire.getOutPorts()); } public final Port[] getInShadows() { if (inwire == null) return new Port[0]; return _getShadows(inwire.getInPorts()); } // identifies and returns shadow ports of this Port[] _getShadows(Port[] tmp_) { if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (p_.host == host.parent) v_.addElement(p_); } return (Port[])v_.toArray(new Port[v_.size()]); } /** * Returns host's ancestor's peers and the shadow ports. */ public final Port[] getParentPeers() { if (inwire == null && outwire == null) return new Port[0]; Port[] tmp_ = _getAllConnectedPorts(true); if (tmp_ == null) return new Port[0]; Vector v_ = new Vector(); for (int i=0; i<tmp_.length; i++) { Port p_ = tmp_[i]; if (!host.parent.isAncestorOf(p_.host)) v_.addElement(p_); } tmp_ = new Port[v_.size()]; v_.copyInto(tmp_); return tmp_; } public boolean isConnectedWith(Port p_) { if (inwire == null && outwire == null) return false; else if (inwire != null && inwire.isAttachedToBy(p_)) return true; else if (outwire != null && outwire.isAttachedToBy(p_)) return true; else return false; } // private void ___DATA_TRANSPORT___() {} // // for Util.inject() final void doReceiving(Object data_) { if (isShadow()) { if (isDataTraceEnabled()) host.trace(Component.Trace_DATA, this, data_, "(shadow)"); Port[] clients_ = getInClients(); // do not copy data_ for (int i=0; i<clients_.length; i++) { Port client_ = clients_[i]; client_.doReceiving(data_); } } else { //doReceiving(data_, null, null); //if (isDataTraceEnabled()) // host.trace(Component.Trace_DATA, this, data_, // "(create context)"); //Note: trace check is done in TaskReceive host.runtime.newTask(new TaskReceive(this, data_), null); } } /** Called by the host component to send data at this port. */ public final void doSending(Object data_) { doSending(data_, host.runtime.getThread()); } //public static boolean DEBUG = false; /** Internal implementation of doSending() */ protected void doSending(Object data_, WorkerThread thread_) { // server port: // bypassing other ports on the out wire of this port. if (thread_ != null && thread_.returnPort != null && (flag & Flag_TYPE) == 3) { //((Port)thread_.returnPort).doReceiving(data_, this, thread_); Port p_ = (Port)thread_.returnPort; Component host_ = p_.host; // trace for event listeners if (outwire != null) { for (PortPack tmp_ = outwire.outEvtListeners; tmp_ != null; tmp_ = tmp_.next) { Port p2_ = tmp_.port; if (p2_.host != null && (p2_ == this || p2_.host.isAncestorOf(host))) p2_.host.trace(Component.Trace_SEND, p2_, data_); } for (PortPack tmp_ = p_.outwire.inEvtListeners; tmp_ != null; tmp_ = tmp_.next) { Port p2_ = tmp_.port; if (p2_ == p_ || (p2_.host != null && p2_.host.isAncestorOf(host_))) p2_.host.trace(Component.Trace_DATA, p2_, data_, "(shadow)"); } } // sendReceiving if (thread_.sendingPort == p_) { //if (p_.isDataTraceEnabled()) // host_.trace(Component.Trace_DATA, p_, data_, // "(for sendReceive())"); thread_.sendingPort = data_; return; } if (thread_.sendingPort == this || !p_.isExecutionBoundary()) { if (host_.isEnabled()) { //if (p_.isDataTraceEnabled()) // host_.trace(Component.Trace_DATA, p_, data_, // "(not across exe boundary)"); // the following execution order is important String prevState_ = thread_.state; thread_.totalNumEvents ++; if (p_.flagTraceData) host_.trace(Component.Trace_DATA, p_, data_); try { host_.process(data_, p_); } catch (Exception e_) { if (host_.isErrorNoticeEnabled()) host_.error(data_, "process()", p_, e_); e_.printStackTrace(); } thread_.releaseAllLocks(host_); thread_.state = prevState_; } } else {// server port: set return port //if (p_.isDataTraceEnabled()) // host_.trace(Component.Trace_DATA, p_, data_, // "(new context)"); host_.runtime.newTask(new TaskReceive(p_, data_), thread_); } return; } if (outwire != null) { //outwire.doSending(data_, this); // trace for event listeners for (PortPack tmp_ = outwire.outEvtListeners; tmp_ != null; tmp_ = tmp_.next) { Port p_ = tmp_.port; if (p_ == this) p_.host.trace(Component.Trace_SEND, p_, data_); else if (p_.host != null && p_.host.isAncestorOf(host)) p_.host.trace(Component.Trace_SEND, p_, data_, "(shadow)"); } for (PortPack tmp_ = outwire.inEvtListeners; tmp_ != null; tmp_ = tmp_.next) { Port p_ = tmp_.port; if (p_ != this && p_.isShadow() && p_.host != null && !p_.host.isAncestorOf(host)) p_.host.trace(Component.Trace_DATA, p_, data_, "(shadow)"); } for (PortPack tmp_ = outwire.inports; tmp_ != null; tmp_ = tmp_.next) { Port p_ = tmp_.port; Component host_ = p_.host; //if (p_ == this || !host_.isEnabled()) continue; if (p_ == this) continue; //p_.doReceiving(data_, this, thread_); if (thread_ == null) { //if (p_.isDataTraceEnabled()) // host_.trace(Component.Trace_DATA, p_, data_, // "(create context)"); //Note: trace check is done in TaskReceive host_.runtime.newTask(new TaskReceive(p_, data_), thread_); continue; } // sendReceiving if (thread_.sendingPort == p_) { /* if (p_.flagTraceData) host_.trace(Component.Trace_DATA, p_, data_, "(for sendReceive())"); */ thread_.sendingPort = data_; continue; } // Cross execution boundary if one of the following conditions // is true // 1. !isExecutionBoundary() // 2. thread's sendingPort is peer_ if (thread_.sendingPort == this || !p_.isExecutionBoundary()) { if (host_.isEnabled()) { // Not execution boundary, the current thread will process // the data. // MUST do it out of the synchronized claus. // Context needs to be changed beforehand and restored // afterwards. //if (p_.isDataTraceEnabled()) // host_.trace(Component.Trace_DATA, p_, data_, // "(not across exe boundary)"); // server port: set return port // XXX: we probably need to back up returnPort here // though it is backed up in sendReceive() // because if sending component calls only // doSending() and this port is not an // execution boundary, then the returnPort // is not backed up, so the previous setting // may be overwritten if ((p_.flag & Port.Flag_TYPE) == 3) thread_.returnPort = this; // the following execution order is important String prevState_ = thread_.state; thread_.totalNumEvents ++; //if (DEBUG && thread_.sendingPort == this) // System.out.println("SEND-RECEIVE: " + this // + " ---> " + p_ + ": data=" + data_); if (p_.flagTraceData) host_.trace(Component.Trace_DATA, p_, data_); try { host_.process(data_, p_); } catch (Exception e_) { if (host_.isErrorNoticeEnabled()) host_.error(data_, "process()", p_, e_); e_.printStackTrace(); } // restore context thread_.releaseAllLocks(host_); // Don't hold locks across components! thread_.state = prevState_; } } else {// server port: set return port //if (p_.isDataTraceEnabled()) // host_.trace(Component.Trace_DATA, p_, data_, // "(new context)"); if ((p_.flag & Port.Flag_TYPE) == 3) // set up return port host_.runtime.newTask(new TaskReceive(p_, data_, this), thread_); else host_.runtime.newTask(new TaskReceive(p_, data_), thread_); } } // for (PortPack tmp_... } } /** * Same as {@link #doSending(Object)} in terms of functionality. * Performance-aware components may use the runtime * notifies the runtime */ public final void doLastSending(Object data_) { host.finishing(); doSending(data_, host.runtime.getThread()); } class SendReceiveRunnable implements Runnable { Port port; Object data; SendReceiveRunnable(Port port_, Object data_) { port = port_; data = data_; } public void run() { data = port.sendReceive(data); synchronized (this) { this.notify(); } } } public final Object sendReceive(Object data_) { // the following check is covered by codes below, commented out for reducing overhead //if (!anyOutConnection()) // throw new SendReceiveException("sendreceive()| no connection"); WorkerThread thread_ = host.runtime.getThread(); if (thread_ == null) { //throw new SendReceiveException("sendreceive()| not in a WorkerThread"); try { SendReceiveRunnable srr_ = new SendReceiveRunnable(this, data_); synchronized (srr_) { host.runtime.addRunnable(0.0, this, srr_); srr_.wait(); return srr_.data; } } catch (Exception e_) { e_.printStackTrace(); //throw new SendReceiveException("sendreceive()| " + e_); if (this.getHost().isErrorNoticeEnabled()) drcl.Debug.error("sendreceive()| " + e_); return -1; } } Object prevSendingPort_ = thread_.sendingPort; thread_.sendingPort = this; // store returnPort here in case peer is a server port as well Port prevReturnPort_ = thread_.returnPort; thread_.returnPort = null; doSending(data_, thread_); if (thread_.sendingPort == this) { if (!host.runtime.resetting) { // throw new SendReceiveException("sendreceive()| did not get reply from " // + this + ".sendReceive(), data=" + data_); //drcl.Debug.error("sendreceive()| did not get reply from " + this // + ", returns <null> instead"); if (this.getHost().isErrorNoticeEnabled()) drcl.Debug.error("sendreceive()| did not get reply from " + this + ".sendReceive(), data=" + data_); return -1; } else data_ = null; // runtime is resetting... } data_ = thread_.sendingPort; thread_.sendingPort = prevSendingPort_; thread_.returnPort = prevReturnPort_; if (flagTraceData) host.trace(Component.Trace_DATA, this, data_, "(end sendReceive())"); return data_; } // private void ___CONNECTION___() {} // boolean _shadowConnect(Port client_) { // type mismatch? if (getType() == PortType_IN && client_.getType() == PortType_OUT) return false; else if (getType() == PortType_OUT && client_.getType() == PortType_IN) return false; setType(client_.getType()); if (client_.getType() == PortType_SERVER) { if (!_shadowConnectTo(client_, false)) return false; return _shadowConnectTo(client_, true); } if (!isShadow()) // move to shadow list _setShadow(true); if (inwire == outwire && client_.inwire == client_.outwire) { // lump all together if (inwire != null) { if (client_.inwire != null) { inwire.join(client_.inwire); } else inwire.joinInOut(client_); } else if (client_.inwire != null) client_.inwire.shadowJoinInOut(this); else new Wire().joinInOut(client_).shadowJoinInOut(this); return true; } // split in/out if necessary if (inwire == outwire && inwire != null && client_.inwire != client_.outwire && (client_.inwire != null || client_.outwire != null)) inoutSplit(); else if (client_.inwire == client_.outwire && client_.inwire != null && inwire != outwire && (inwire != null || outwire != null)) client_.inoutSplit(); if (inwire != null) { if (client_.inwire != null) inwire.join(client_.inwire); else inwire.joinIn(client_); } else if (client_.inwire != null) client_.inwire.shadowJoinIn(this); else new Wire().joinIn(client_).shadowJoinIn(this); if (outwire != null) { if (client_.outwire != null) outwire.join(client_.outwire); else outwire.joinOut(client_); } else if (client_.outwire != null) client_.outwire.shadowJoinOut(this); else new Wire().joinOut(client_).shadowJoinOut(this); return true; } /** * Bi-direction connection, consider proxying. * Returns true if either direction is set up successfully. */ public final boolean connect(Port peer_) { if (host.isAncestorOf(peer_.host)) return _shadowConnect(peer_); else if (peer_.host.isAncestorOf(host)) return peer_._shadowConnect(this); // server port? if (getType() == PortType_SERVER) { if (peer_.getType() == PortType_IN || peer_.getType() == PortType_SERVER) return false; if (!peer_.connectTo(this)) return false; if (peer_.inwire == null) peer_.inwire = inwire; else inwire.join(peer_.inwire); if (outwire == null) outwire = new Wire().joinOut(this); return true; } else if (peer_.getType() == PortType_SERVER) { if (getType() == PortType_IN) return false; if (!connectTo(peer_)) return false; if (inwire == null) inwire = peer_.inwire; else peer_.inwire.join(inwire); if (peer_.outwire == null) peer_.outwire = new Wire().joinOut(peer_); return true; } // type mismatch? if (getType() == PortType_IN) { if (peer_.getType() == PortType_IN) return false; return peer_.connectTo(this); } else if (getType() == PortType_OUT) { if (peer_.getType() == PortType_OUT) return false; return connectTo(peer_); } else if (peer_.getType() == PortType_OUT) return peer_.connectTo(this); else if (peer_.getType() == PortType_IN) return connectTo(peer_); if (inwire == outwire && peer_.inwire == peer_.outwire) { // lump all together if (inwire != null) { if (peer_.inwire != null) inwire.join(peer_.inwire); else inwire.joinInOut(peer_); } else if (peer_.inwire != null) peer_.inwire.joinInOut(this); else new Wire().joinInOut(peer_).joinInOut(this); return true; } // split in/out if necessary if (inwire == outwire && inwire != null && peer_.inwire != peer_.outwire && (peer_.inwire != null || peer_.outwire != null)) inoutSplit(); else if (peer_.inwire == peer_.outwire && peer_.inwire != null && inwire != outwire && (inwire != null || outwire != null)) peer_.inoutSplit(); // join wires if (inwire != null) { if (peer_.outwire != null) inwire.join(peer_.outwire); else inwire.joinOut(peer_); } else if (peer_.outwire != null) peer_.outwire.joinIn(this); else new Wire().joinOut(peer_).joinIn(this); if (outwire != null) { if (peer_.inwire != null) outwire.join(peer_.inwire); else outwire.joinIn(peer_); } else if (peer_.inwire != null) peer_.inwire.joinOut(this); else new Wire().joinIn(peer_).joinOut(this); return true; } /** * Disconnects from the given ports. */ public final void connect(Port[] pp_) { for (int i=0; i<pp_.length; i++) connect(pp_[i]); } /** Attaches the port to the IN wire for receiving data from the wire. */ public final void attachIn(Port p_) { attachIn(new Port[]{p_}); } /** Attaches the ports to the IN wire for receiving data from the wire. */ public final void attachIn(Port[] pp_) { Wire wire_ = getInWire(); if (wire_ == null) { wire_ = new Wire(); wire_.joinIn(this); } wire_.attach(pp_); } /** Removes the port from the IN wire. */ public final void detachIn(Port p_) { detachIn(new Port[]{p_}); } /** Removes the ports from the IN wire. */ public final void detachIn(Port[] pp_) { Wire wire_ = getInWire(); if (wire_ != null) wire_.detach(pp_); } /** Attaches the port to the OUT wire for receiving data from the wire. */ public final void attachOut(Port p_) { attachOut(new Port[]{p_}); } /** Attaches the ports to the OUT wire for receiving data from the wire. */ public final void attachOut(Port[] pp_) { Wire wire_ = getOutWire(); if (wire_ == null) { wire_ = new Wire(); wire_.joinOut(this); } wire_.attach(pp_); } /** Removes the port from the OUT wire. */ public final void detachOut(Port p_) { detachOut(new Port[]{p_}); } /** Removes the port from the OUT wire. */ public final void detachOut(Port[] pp_) { Wire wire_ = getOutWire(); if (wire_ != null) wire_.detach(pp_); } boolean _shadowConnectTo(Port client_, boolean reverse_) { // type mismatch? if (!reverse_) { if (getType() == PortType_OUT || client_.getType() == PortType_OUT) return false; } else if (getType() == PortType_IN && client_.getType() == PortType_IN) return false; if (!isShadow()) // move to shadow list _setShadow(true); if (reverse_) { // it's outwire if (outwire != null) { if (client_.outwire != null) outwire.join(client_.outwire); else outwire.joinOut(client_); } else if (client_.outwire != null) client_.outwire.joinOut(this); else new Wire().joinOut(client_).joinOut(this); } else { // it's inwire if (inwire != null) { if (client_.inwire != null) inwire.join(client_.inwire); else inwire.joinIn(client_); } else if (client_.inwire != null) client_.inwire.joinIn(this); else new Wire().joinIn(client_).joinIn(this); } return true; } /** * Uni-direction connection, consider proxying. * Returns true if the connection is set up successfully. */ public final boolean connectTo(Port peer_) { if (host.isAncestorOf(peer_.host)) return _shadowConnectTo(peer_, false); else if (peer_.host.isAncestorOf(host)) return peer_._shadowConnectTo(this, true); // type mismatch? if (getType() == PortType_IN || peer_.getType() == PortType_OUT) return false; if (outwire == null && peer_.inwire == null) return new Wire().joinOut(this).joinIn(peer_) != null; else if (outwire != null) { if (peer_.inwire != null) outwire.join(peer_.inwire); else outwire.joinIn(peer_); } else peer_.inwire.joinOut(this); return true; } // shortcut for probing component void _connectTo(Port peer_) { if (outwire == null && peer_.inwire == null) new Wire().joinOut(this).joinIn(peer_); else if (outwire != null) { if (peer_.inwire != null) outwire.join(peer_.inwire); else outwire.joinIn(peer_); } else peer_.inwire.joinOut(this); } /** * Connects to the given ports. */ public final void connectTo(Port[] pp_) { for (int i=0; i<pp_.length; i++) connectTo(pp_[i]); } /** * Disconnect with all peers. */ public final void disconnect() { disconnectPeers(); } /** * Disconnect with all peers and clients on the IN wire. */ public final void disconnectInWire() { if (inwire != null) inwire.disconnect(this); inwire = null; if (isShadow() && !anyClient()) _setShadow(false); } /** * Disconnect with all peers and clients on the OUT wire. */ public final void disconnectOutWire() { if (outwire != null) outwire.disconnect(this); outwire = null; if (isShadow() && !anyClient()) _setShadow(false); } /** * Removes peers from the wires attached with this port. */ public final void disconnectPeers() { if (this == host.infoPort) { outwire = null; return; } Port[] peers_ = getPeers(); if (peers_ == null || peers_.length == 0) return; if (inwire != null) { inwire.split(peers_); if (!inwire.anyPortExcept(this)) inwire = null; } if (outwire != null) { if (outwire != inwire) outwire.split(peers_); if (!outwire.anyPortExcept(this)) outwire = null; } } public final void disconnectClients() { Port[] clients_ = getClients(); if (clients_ == null || clients_.length == 0) return; if (inwire != null) inwire.split(clients_); if (outwire != null && outwire != inwire) outwire.split(clients_); _setShadow(false); } public final void disconnectWithParent() { Port[] peers_ = getParentPeers(); if (peers_ == null || peers_.length == 0) return; if (inwire != null) inwire.split(peers_); if (outwire != null && outwire != inwire) outwire.split(peers_); for (int i=0; i<peers_.length; i++) { Port parent_ = peers_[i]; if (!parent_.anyClient()) parent_._setShadow(false); } } /** * Splits the "IN" wire/"OUT" wire of this port. */ public synchronized void inoutSplit() { if (inwire != outwire || inwire == null) return; /* outwire = (Wire)inwire.clone(); outwire.inports = inwire.inports; inwire.inports = new Port[]{this}; outwire.outports = new Port[]{this}; if (inwire.outports != null) for (int i=0; i<inwire.outports.length; i++) if (inwire.outports[i] == this) inwire.outports[i] = null; if (outwire.inports != null) for (int i=0; i<outwire.inports.length; i++) if (outwire.inports[i] == this) outwire.inports[i] = null; else if (outwire.inports[i] != null) outwire.inports[i].inwire = outwire; */ inwire.inoutSplit(this); } // private void ___MISC___() {} // public final void exportEvent(String evtName_, Object evtObj_, String evtDescription_) { doSending(new EventContract.Message(host.getTime(), evtName_, toString(), evtObj_, evtDescription_)); } public final void exportEvent(String evtName_, double value_, String evtDescription_) { doSending(new DoubleEventContract.Message(host.getTime(), evtName_, toString(), value_, evtDescription_)); } public final boolean _isEventExportEnabled() { return ((flag & Flag_EVENT_EXPORT) != 0) && anyConnection(); } /** Duplicates the content of the port from <code>source_</code>. This method is meant to be invoked by {@link Component}. It only duplicates the flag. ID, groupID and wires are not copied. */ public final void duplicate(Object source_) { Port that_ = (Port)source_; //id = that_.id; //groupID = that_.groupID; flag = that_.flag; //setRemovable(that_.isRemovable()); //inwire = outwire = null; // don't clone wires } String fullpath; /** Returns the full path. */ public final String toString() { if (fullpath == null) fullpath = Util.getPortFullID(this); return fullpath; } public final String info() { StringBuffer sb_ = new StringBuffer(Util.getPortFullID(this) + "\n"); sb_.append("Type: " + getTypeInString() + "\n"); sb_.append(" Shadow? " + isShadow() + "\n"); sb_.append("ExecutionBoudnary? " + isExecutionBoundary() + "\n"); sb_.append(" Removable? " + isRemovable() + "\n"); sb_.append(" DataTraceEnabled? " + isDataTraceEnabled() + "\n"); sb_.append(" SendTraceEnabled? " + isSendTraceEnabled() + "\n"); int i = 0, k = 0; StringBuffer tmp_ = new StringBuffer(); /* Port[] all_ = _getAllConnectedPorts(true); for (int j=0; j<all_.length; j++) { Port p_ = all_[j]; String portid_ = Util.getPortID(p_, host != null && host.parent != null? host.parent: null); if (host.isAncestorOf(p_.host)) tmp_.append(Util.checkConnect(this, p_) + "Client " + ++k + ": " + portid_ + "\n"); else sb_.append(Util.checkConnect(this, p_) + "Peer " + ++i + ": " + portid_ + "\n"); } if (i + k == 0) sb_.append("No peer and client.\n"); else if (i==0) sb_.append("No peer.\n" + tmp_); else if (k==0) sb_.append("No client.\n"); else sb_.append(tmp_); */ if (inwire == outwire) { if (inwire == null) sb_.append("No connection.\n"); else sb_.append("one wire for in/out: " + inwire + "\n"); } else { if (inwire != null) sb_.append("inwire: " + inwire + "\n"); if (outwire != null) sb_.append("outwire:" + outwire + "\n"); } return sb_.toString(); } }
cb3f2003eadc28e9b7ba3cf38bbd059000ba8fb5
839389d2c19b031385b1ce0ab475e8d3d53f78a2
/DesignPattern/src/com/ss/design/impl/Male.java
87104fb722d71c246a6aa36d91254ba13aa793a7
[]
no_license
ShowLuu/JavaDesignPattern
30e0e3dd031f471d93662303de0d135374f71e22
c5bd6f6737d884dd040b35e07a118ee0fe68e396
refs/heads/master
2021-01-25T09:43:51.819647
2018-03-08T09:07:04
2018-03-08T09:07:04
123,311,542
0
0
null
null
null
null
UTF-8
Java
false
false
334
java
package com.ss.design.impl; import com.ss.design.inte.Human; public class Male implements Human { @Override public void eat() { System.out.println("Male can eat."); } @Override public void sleep() { System.out.println("Male can sleep."); } @Override public void beat() { System.out.println("Male can beat."); } }
dcc6721f30c5979dd6f69b228c8bec07e369fad8
46da4bfdecec9ee8e528608f00a7d1cff14037ca
/app/src/main/java/com/rahul/blx/ElectronicsResponseClasses/LocationsResolvedElectronicClasses.java
39ce8bc13d7966cfdc747bbbb6e0764485ad8fc4
[]
no_license
rahul6975/BLX
54916abda956c1c7ac1e31064507ccce30524b85
843b01166f8e139f3a7c27ed8e8f3ad5b2de4e62
refs/heads/master
2023-05-06T07:23:51.364724
2021-05-29T06:52:39
2021-05-29T06:52:39
371,899,921
0
0
null
null
null
null
UTF-8
Java
false
false
1,388
java
package com.rahul.blx.ElectronicsResponseClasses; import javax.annotation.Generated; import com.google.gson.annotations.SerializedName; import java.io.Serializable; @Generated("com.robohorse.robopojogenerator") public class LocationsResolvedElectronicClasses implements Serializable { @SerializedName("COUNTRY_id") private String cOUNTRYId; @SerializedName("COUNTRY_name") private String cOUNTRYName; @SerializedName("ADMIN_LEVEL_1_id") private String aDMINLEVEL1Id; @SerializedName("ADMIN_LEVEL_1_name") private String aDMINLEVEL1Name; @SerializedName("ADMIN_LEVEL_3_id") private String aDMINLEVEL3Id; @SerializedName("ADMIN_LEVEL_3_name") private String aDMINLEVEL3Name; @SerializedName("SUBLOCALITY_LEVEL_1_id") private String sUBLOCALITYLEVEL1Id; @SerializedName("SUBLOCALITY_LEVEL_1_name") private String sUBLOCALITYLEVEL1Name; public String getCOUNTRYId(){ return cOUNTRYId; } public String getCOUNTRYName(){ return cOUNTRYName; } public String getADMINLEVEL1Id(){ return aDMINLEVEL1Id; } public String getADMINLEVEL1Name(){ return aDMINLEVEL1Name; } public String getADMINLEVEL3Id(){ return aDMINLEVEL3Id; } public String getADMINLEVEL3Name(){ return aDMINLEVEL3Name; } public String getSUBLOCALITYLEVEL1Id(){ return sUBLOCALITYLEVEL1Id; } public String getSUBLOCALITYLEVEL1Name(){ return sUBLOCALITYLEVEL1Name; } }
e4ab7ff9b4b68ad83201fc6c2c867afd11d47021
1f0cb0b6f4c74ff706254baf5b028bc9417615f9
/spring-micro-repositories/spring-micro-repositories-mysql/spring-micro-repositories-mysql-modules_2/spring-micro-repositories-mysql-auth_2/src/main/java/org/example/spring/repositories/mysql/auth/dao/impl/TDepartmentDaoImpl.java
f6e3d2a96b74cfd96918fa944fdf961c99567654
[]
no_license
yuan50697105/spring-build-project-1
af448da5e3676a99c22aaaca6de4fb9e8ea55811
967fc586637146d8ab3f80bd518ed50bf70dae90
refs/heads/master
2022-07-22T13:45:00.442964
2021-06-03T02:53:19
2021-06-03T02:53:19
359,333,990
0
0
null
null
null
null
UTF-8
Java
false
false
1,287
java
package org.example.spring.repositories.mysql.auth.dao.impl; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.extension.toolkit.SqlHelper; import lombok.AllArgsConstructor; import org.example.spring.plugins.mybatis.dao.impl.TkBaseDaoImpl; import org.example.spring.repositories.mysql.auth.dao.TDepartmentDao; import org.example.spring.repositories.mysql.auth.mapper.TDepartmentMapper; import org.example.spring.repositories.mysql.auth.table.po.TDepartment; import org.example.spring.repositories.mysql.auth.table.query.TDepartmentQuery; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Repository @AllArgsConstructor @Transactional public class TDepartmentDaoImpl extends TkBaseDaoImpl<TDepartment, TDepartmentQuery, TDepartmentMapper> implements TDepartmentDao { @Override protected Wrapper<TDepartment> queryWrapper(TDepartmentQuery tDepartmentQuery) { return null; } @Override public boolean existChildByPIds(List<Long> ids) { return baseMapper.existChildByPIds(ids); } @Override public boolean validateDelete(List<Long> ids) { return SqlHelper.retBool(baseMapper.validateDelete(ids)); } }
2fb6877fe10cd4a368483a77e344ddd69c4ebd4a
4e8a6f9ee707604c47a5c025c9029bb64cbd836b
/src/mseg/erp/dao/tipoadministracion/TipoAdministracionDAOImpl.java
93b68e4aa40e30171ee76ea64cf69e4351535978
[]
no_license
fabricioscianda/gdp
df2197568448f86b149299c88f6978563fa1e5c7
0eec29a0200434bf4e260ca2d16836254b4db22e
refs/heads/master
2021-01-23T13:58:08.630600
2015-04-28T03:32:53
2015-04-28T03:32:53
27,416,779
0
0
null
null
null
null
UTF-8
Java
false
false
535
java
package mseg.erp.dao.tipoadministracion; import mseg.erp.model.TipoAdministracion; import mseg.erp.dao.generic.GenericDAOImpl; import mseg.erp.vomodel.VOTipoAdministracion; public class TipoAdministracionDAOImpl extends GenericDAOImpl<VOTipoAdministracion, TipoAdministracion> implements ITipoAdministracionDAO { public TipoAdministracionDAOImpl() { super(TipoAdministracion.class, VOTipoAdministracion.class); } @Override public Long getId(VOTipoAdministracion objetoVO) { return objetoVO.getId(); } }
aae3ded0c14b1bf5c5c70e74131a177a336716cb
2e976b8d19c7c6389fdf6e374f799fdeb01d8ac0
/BestTimetoBuyandSellStock.java
c1375e226cd5c2b39ec90d27480096b73b027788
[]
no_license
Arpit-Sharma-USC/LeetCode
db4eb6aa0c5bbbb78e6ea27c0a767bcc99cd37c4
ba542241ef08c30bb45cef8c92b8d395c0db753e
refs/heads/master
2020-05-04T05:56:43.116284
2019-06-28T21:53:49
2019-06-28T21:53:49
178,995,678
1
0
null
null
null
null
UTF-8
Java
false
false
399
java
class Solution { public int maxProfit(int[] prices) { int minPrice=Integer.MAX_VALUE; int maxProf= 0; for(int i =0;i<prices.length;i++) { if(prices[i]<minPrice) minPrice=prices[i]; else if((prices[i]-minPrice)>maxProf) maxProf=prices[i]-minPrice; } return maxProf; } }
cff18da6a05c2c75ca4d0a866439cb708afdc95b
1b7ebd3409dfca48ef6afc9986d47b744d7cfe84
/MyEclipse_2017_CI/permission-shiro/src/com/hdquan/service/MenuService.java
4763d8b3f074dcb524b0eaa848af0db893029f4e
[]
no_license
hedingquan/javaForHdquan
dc1471702abb2212143cc180a7299c3746605e08
971d4877d3bcbfb8ad90644251e36400233d1bd0
refs/heads/master
2021-03-07T21:57:29.262416
2020-03-10T13:37:33
2020-03-10T13:37:33
246,299,378
1
0
null
null
null
null
UTF-8
Java
false
false
136
java
package com.hdquan.service; import java.util.List; import com.hdquan.pojo.Menu; public interface MenuService { List<Menu> show(); }
[ "hedingna123" ]
hedingna123
76dd049f9560379dece381c4badeb0813604129b
a840ad11c5313a362827e2f50788ef0a14561fed
/21.Arrays/src/ConvertToTest.java
3dbcfaf5a72f8089b8d2240567a6de2c64ba154e
[]
no_license
denglitong/thingking_in_java
4f3d5cc4341877978b21b3123b57b45f0f157c0c
76addcb8758e6d5f720760ab58b9db6cf5c1ef46
refs/heads/master
2023-05-04T13:43:07.119064
2021-05-27T09:59:45
2021-05-27T09:59:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
450
java
import java.util.Arrays; /** * @author denglitong * @date 2021/1/23 */ public class ConvertToTest { static final int SIZE = 6; public static void main(String[] args) { Boolean[] a1 = new Boolean[SIZE]; Arrays.setAll(a1, new Rand.Boolean()::get); boolean[] a1p = ConvertTo.primitive(a1); ArrayShow.show("a1p", a1p); Boolean[] a1b = ConvertTo.boxed(a1p); ArrayShow.show("a1b", a1b); } }
2c17780747e2e50c8cf2cb529d8e6e3e7114fb56
43145c76d8088adb3ea4911735be23108c273f01
/soot3/src/soot/JastAddJ/BodyDecl.java
109ca45298e03b1c795055e052ce3efe3f099e38
[]
no_license
sanchuanchen/soot-dex
207853149ddbbbe43e2a2ff2a411192802f914b5
65e50dc293734d5ebeaa366e78817ef86b47b8c4
refs/heads/master
2020-12-24T18:03:13.314462
2013-12-12T17:54:08
2013-12-12T17:54:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
17,043
java
/* This file was generated with JastAdd2 (http://jastadd.org) version R20121122 (r889) */ package soot.JastAddJ; import java.util.HashSet; import java.util.LinkedHashSet; import java.io.File; import java.util.*; import beaver.*; import java.util.ArrayList; import java.util.zip.*; import java.io.*; import java.io.FileNotFoundException; import java.util.Collection; import soot.*; import soot.util.*; import soot.jimple.*; import soot.coffi.ClassFile; import soot.coffi.method_info; import soot.coffi.CONSTANT_Utf8_info; import soot.tagkit.SourceFileTag; import soot.coffi.CoffiMethodSource; /** * @production BodyDecl : {@link ASTNode}; * @ast node * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/java.ast:72 */ public abstract class BodyDecl extends ASTNode<ASTNode> implements Cloneable { /** * @apilevel low-level */ public void flushCache() { super.flushCache(); isDAafter_Variable_values = null; isDUafter_Variable_values = null; isDAbefore_Variable_values = null; isDUbefore_Variable_values = null; typeThrowable_computed = false; typeThrowable_value = null; lookupVariable_String_values = null; } /** * @apilevel internal */ public void flushCollectionCache() { super.flushCollectionCache(); } /** * @apilevel internal */ @SuppressWarnings({"unchecked", "cast"}) public BodyDecl clone() throws CloneNotSupportedException { BodyDecl node = (BodyDecl)super.clone(); node.isDAafter_Variable_values = null; node.isDUafter_Variable_values = null; node.isDAbefore_Variable_values = null; node.isDUbefore_Variable_values = null; node.typeThrowable_computed = false; node.typeThrowable_value = null; node.lookupVariable_String_values = null; node.in$Circle(false); node.is$Final(false); return node; } /** * @ast method * @aspect BranchTarget * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/BranchTarget.jrag:211 */ public void collectFinally(Stmt branchStmt, ArrayList list) { // terminate search if body declaration is reached } /** * @ast method * @aspect LookupParTypeDecl * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.5Frontend/Generics.jrag:1238 */ public BodyDecl substitutedBodyDecl(Parameterization parTypeDecl) { throw new Error("Operation substitutedBodyDecl not supported for " + getClass().getName()); } /** * @ast method * @aspect EmitJimple * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddExtensions/JimpleBackend/EmitJimple.jrag:207 */ public void jimplify1phase2() { } /** * @ast method * @aspect EmitJimple * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddExtensions/JimpleBackend/EmitJimple.jrag:973 */ public void jimplify2() { } /** * We must report illegal uses of the SafeVarargs annotation. * It is only allowed on variable arity method and constructor declarations. * @ast method * @aspect SafeVarargs * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java7Frontend/SafeVarargs.jrag:93 */ public void checkWarnings() { if (hasIllegalAnnotationSafeVarargs()) error("@SafeVarargs is only allowed for variable " + "arity method and constructor declarations"); } /** * @ast method * */ public BodyDecl() { super(); } /** * Initializes the child array to the correct size. * Initializes List and Opt nta children. * @apilevel internal * @ast method * @ast method * */ public void init$Children() { } /** * @apilevel low-level * @ast method * */ protected int numChildren() { return 0; } /** * @apilevel internal * @ast method * */ public boolean mayHaveRewrite() { return false; } protected java.util.Map isDAafter_Variable_values; /** * @attribute syn * @aspect DA * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/DefiniteAssignment.jrag:243 */ @SuppressWarnings({"unchecked", "cast"}) public boolean isDAafter(Variable v) { Object _parameters = v; if(isDAafter_Variable_values == null) isDAafter_Variable_values = new java.util.HashMap(4); if(isDAafter_Variable_values.containsKey(_parameters)) { return ((Boolean)isDAafter_Variable_values.get(_parameters)).booleanValue(); } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); boolean isDAafter_Variable_value = isDAafter_compute(v); if(isFinal && num == state().boundariesCrossed) isDAafter_Variable_values.put(_parameters, Boolean.valueOf(isDAafter_Variable_value)); return isDAafter_Variable_value; } /** * @apilevel internal */ private boolean isDAafter_compute(Variable v) { return true; } protected java.util.Map isDUafter_Variable_values; /** * @attribute syn * @aspect DU * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/DefiniteAssignment.jrag:708 */ @SuppressWarnings({"unchecked", "cast"}) public boolean isDUafter(Variable v) { Object _parameters = v; if(isDUafter_Variable_values == null) isDUafter_Variable_values = new java.util.HashMap(4); if(isDUafter_Variable_values.containsKey(_parameters)) { return ((Boolean)isDUafter_Variable_values.get(_parameters)).booleanValue(); } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); boolean isDUafter_Variable_value = isDUafter_compute(v); if(isFinal && num == state().boundariesCrossed) isDUafter_Variable_values.put(_parameters, Boolean.valueOf(isDUafter_Variable_value)); return isDUafter_Variable_value; } /** * @apilevel internal */ private boolean isDUafter_compute(Variable v) { return true; } /** * @attribute syn * @aspect TypeScopePropagation * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/LookupType.jrag:479 */ public boolean declaresType(String name) { ASTNode$State state = state(); try { return false; } finally { } } /** * @attribute syn * @aspect TypeScopePropagation * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/LookupType.jrag:481 */ public TypeDecl type(String name) { ASTNode$State state = state(); try { return null; } finally { } } /** * @attribute syn * @aspect PrettyPrint * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/PrettyPrint.jadd:758 */ public boolean addsIndentationLevel() { ASTNode$State state = state(); try { return true; } finally { } } /** * @attribute syn * @aspect TypeAnalysis * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/TypeAnalysis.jrag:271 */ public boolean isVoid() { ASTNode$State state = state(); try { return false; } finally { } } /** * @attribute syn * @aspect Annotations * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.5Frontend/Annotations.jrag:283 */ public boolean hasAnnotationSuppressWarnings(String s) { ASTNode$State state = state(); try { return false; } finally { } } /** * @attribute syn * @aspect Annotations * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.5Frontend/Annotations.jrag:326 */ public boolean isDeprecated() { ASTNode$State state = state(); try { return false; } finally { } } /** * @attribute syn * @aspect Enums * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.5Frontend/Enums.jrag:26 */ public boolean isEnumConstant() { ASTNode$State state = state(); try { return false; } finally { } } /** * @attribute syn * @aspect GenericsParTypeDecl * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.5Frontend/GenericsParTypeDecl.jrag:67 */ public boolean visibleTypeParameters() { ASTNode$State state = state(); try { return true; } finally { } } /** * @attribute syn * @aspect EmitJimple * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddExtensions/JimpleBackend/EmitJimple.jrag:161 */ public boolean generate() { ASTNode$State state = state(); try { return true; } finally { } } /** * @return true if the modifier list includes the SafeVarargs annotation * @attribute syn * @aspect SafeVarargs * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java7Frontend/SafeVarargs.jrag:20 */ public boolean hasAnnotationSafeVarargs() { ASTNode$State state = state(); try { return false; } finally { } } /** * It is an error if the SafeVarargs annotation is used on something * that is not a variable arity method or constructor. * @attribute syn * @aspect SafeVarargs * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java7Frontend/SafeVarargs.jrag:56 */ public boolean hasIllegalAnnotationSafeVarargs() { ASTNode$State state = state(); try { return hasAnnotationSafeVarargs(); } finally { } } protected java.util.Map isDAbefore_Variable_values; /** * @attribute inh * @aspect DA * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/DefiniteAssignment.jrag:242 */ @SuppressWarnings({"unchecked", "cast"}) public boolean isDAbefore(Variable v) { Object _parameters = v; if(isDAbefore_Variable_values == null) isDAbefore_Variable_values = new java.util.HashMap(4); if(isDAbefore_Variable_values.containsKey(_parameters)) { return ((Boolean)isDAbefore_Variable_values.get(_parameters)).booleanValue(); } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); boolean isDAbefore_Variable_value = getParent().Define_boolean_isDAbefore(this, null, v); if(isFinal && num == state().boundariesCrossed) isDAbefore_Variable_values.put(_parameters, Boolean.valueOf(isDAbefore_Variable_value)); return isDAbefore_Variable_value; } protected java.util.Map isDUbefore_Variable_values; /** * @attribute inh * @aspect DU * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/DefiniteAssignment.jrag:707 */ @SuppressWarnings({"unchecked", "cast"}) public boolean isDUbefore(Variable v) { Object _parameters = v; if(isDUbefore_Variable_values == null) isDUbefore_Variable_values = new java.util.HashMap(4); if(isDUbefore_Variable_values.containsKey(_parameters)) { return ((Boolean)isDUbefore_Variable_values.get(_parameters)).booleanValue(); } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); boolean isDUbefore_Variable_value = getParent().Define_boolean_isDUbefore(this, null, v); if(isFinal && num == state().boundariesCrossed) isDUbefore_Variable_values.put(_parameters, Boolean.valueOf(isDUbefore_Variable_value)); return isDUbefore_Variable_value; } /** * @apilevel internal */ protected boolean typeThrowable_computed = false; /** * @apilevel internal */ protected TypeDecl typeThrowable_value; /** * @attribute inh * @aspect ExceptionHandling * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/ExceptionHandling.jrag:22 */ @SuppressWarnings({"unchecked", "cast"}) public TypeDecl typeThrowable() { if(typeThrowable_computed) { return typeThrowable_value; } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); typeThrowable_value = getParent().Define_TypeDecl_typeThrowable(this, null); if(isFinal && num == state().boundariesCrossed) typeThrowable_computed = true; return typeThrowable_value; } /** * @attribute inh * @aspect LookupMethod * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/LookupMethod.jrag:25 */ @SuppressWarnings({"unchecked", "cast"}) public Collection lookupMethod(String name) { ASTNode$State state = state(); Collection lookupMethod_String_value = getParent().Define_Collection_lookupMethod(this, null, name); return lookupMethod_String_value; } /** * @attribute inh * @aspect LookupFullyQualifiedTypes * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/LookupType.jrag:97 */ @SuppressWarnings({"unchecked", "cast"}) public TypeDecl lookupType(String packageName, String typeName) { ASTNode$State state = state(); TypeDecl lookupType_String_String_value = getParent().Define_TypeDecl_lookupType(this, null, packageName, typeName); return lookupType_String_String_value; } /** * @attribute inh * @aspect TypeScopePropagation * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/LookupType.jrag:261 */ @SuppressWarnings({"unchecked", "cast"}) public SimpleSet lookupType(String name) { ASTNode$State state = state(); SimpleSet lookupType_String_value = getParent().Define_SimpleSet_lookupType(this, null, name); return lookupType_String_value; } protected java.util.Map lookupVariable_String_values; /** * @attribute inh * @aspect VariableScope * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/LookupVariable.jrag:15 */ @SuppressWarnings({"unchecked", "cast"}) public SimpleSet lookupVariable(String name) { Object _parameters = name; if(lookupVariable_String_values == null) lookupVariable_String_values = new java.util.HashMap(4); if(lookupVariable_String_values.containsKey(_parameters)) { return (SimpleSet)lookupVariable_String_values.get(_parameters); } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); SimpleSet lookupVariable_String_value = getParent().Define_SimpleSet_lookupVariable(this, null, name); if(isFinal && num == state().boundariesCrossed) lookupVariable_String_values.put(_parameters, lookupVariable_String_value); return lookupVariable_String_value; } /** * @attribute inh * @aspect SyntacticClassification * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/SyntacticClassification.jrag:21 */ @SuppressWarnings({"unchecked", "cast"}) public NameType nameType() { ASTNode$State state = state(); NameType nameType_value = getParent().Define_NameType_nameType(this, null); return nameType_value; } /** * @attribute inh * @aspect NestedTypes * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/TypeAnalysis.jrag:566 */ @SuppressWarnings({"unchecked", "cast"}) public String hostPackage() { ASTNode$State state = state(); String hostPackage_value = getParent().Define_String_hostPackage(this, null); return hostPackage_value; } /** * @attribute inh * @aspect NestedTypes * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/TypeAnalysis.jrag:585 */ @SuppressWarnings({"unchecked", "cast"}) public TypeDecl hostType() { ASTNode$State state = state(); TypeDecl hostType_value = getParent().Define_TypeDecl_hostType(this, null); return hostType_value; } /** * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/PrettyPrint.jadd:353 * @apilevel internal */ public String Define_String_typeDeclIndent(ASTNode caller, ASTNode child) { { int childIndex = this.getIndexOfChild(caller); return indent(); } } /** * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Frontend/TypeAnalysis.jrag:514 * @apilevel internal */ public BodyDecl Define_BodyDecl_enclosingBodyDecl(ASTNode caller, ASTNode child) { { int childIndex = this.getIndexOfChild(caller); return this; } } /** * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddExtensions/JimpleBackend/Statements.jrag:464 * @apilevel internal */ public ArrayList Define_ArrayList_exceptionRanges(ASTNode caller, ASTNode child) { { int childIndex = this.getIndexOfChild(caller); return null; } } /** * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java7Frontend/TryWithResources.jrag:153 * @apilevel internal */ public boolean Define_boolean_resourcePreviouslyDeclared(ASTNode caller, ASTNode child, String name) { { int i = this.getIndexOfChild(caller); return false; } } /** * @apilevel internal */ public ASTNode rewriteTo() { return super.rewriteTo(); } }
6a84196bd18d3d193c229ae3356c19f5396de3e3
8697ce452be0166a3852c35f654af315f3630582
/venom-main/src/main/java/tk/clawhub/controller/DownloaderController.java
04fbbf79d62ceae9910b9755f0b5ddeccaa9b847
[]
no_license
ClawHub/venom
96688fba370b2acdd56c6a63a093f3063e8ace7a
089054882da6303d261999a4658c1be65ca4f16e
refs/heads/master
2020-03-27T17:43:40.012159
2018-08-31T09:21:36
2018-08-31T09:21:36
146,869,953
1
1
null
null
null
null
UTF-8
Java
false
false
291
java
package tk.clawhub.controller; import org.springframework.web.bind.annotation.RestController; /** * <Description>Downloader controller <br> * * @author LiZhiming<br> * @version 1.0<br> * @taskId <br> * @date 2018 -07-24 <br> */ @RestController public class DownloaderController { }
f3773be75bcb426ee103c013379d5ede06339456
cb8da6414075bc4308ce669b86299876c3c61aea
/app/src/test/java/com/app/andrew/moviesviewer/ExampleUnitTest.java
910084e98818e7d4e9e3929434c1a3925f8cb418
[]
no_license
andyalbert/MovieViewer
dd29a1666dcfa9346b839ec0758c4aa56666c6e7
5e2ff5b567ae8292209e1677adf771558eb06602
refs/heads/master
2021-01-01T06:01:17.118304
2017-07-15T18:28:48
2017-07-15T18:28:48
97,330,040
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package com.app.andrew.moviesviewer; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
fbe8cc7875c014afda2a4f6a5e3dfa4eaaec2258
237b9d11b56b0f5308b0a78d2f4e75a8f1d1de3e
/streams/src/ByteFile.java
6fb5cf5e311ab23aecb9d67adac05ded8f767a2c
[]
no_license
petrol95/java-core
5c037623350ca0a0f308bdcd2d9a234fcfb34056
f1bb0205ba4e86df1dfda17f40d26baf7bb5f7ef
refs/heads/master
2021-07-03T23:52:22.632376
2020-02-09T20:51:46
2020-02-09T20:51:46
188,416,553
0
0
null
2020-10-13T16:27:28
2019-05-24T12:16:22
Java
UTF-8
Java
false
false
1,066
java
import java.io.*; import java.io.FileInputStream; /** * Прочитать файл (около 50 байт) в байтовый массив и вывести этот массив в консоль */ public class ByteFile { private static final String FILE_NAME = "streams\\byteFile.txt"; private static OutputStream os; private static FileInputStream is; public static void main(String[] args) throws IOException { try { byte[] bytesIn = new byte[50]; byte[] bytesOut = new byte[50]; os = new FileOutputStream(FILE_NAME); for (int i = 0; i < bytesIn.length; i++) { bytesIn[i] = (byte) i; } os.write(bytesIn); is = new FileInputStream(FILE_NAME); is.read(bytesOut); System.out.println("Read " + bytesOut.length + " bytes"); for (byte b : bytesOut) { System.out.print(b + " "); } } finally { os.close(); is.close(); } } }
4aa9c6b04a7d4fda33bf9e0d97118870d19f41ff
6eeac3e88ec3a620bf3da1ba53cef6ab2d302df6
/src/main/java/com/brahma/loganalyzer/LogAnalyzerApplication.java
1230e0c56ece85b7d03a6641e0a822375dc78e73
[]
no_license
stratzoomer/LogAnalyzer
8d285fb7a24edef038feb07ac88cc5a10bf09cb3
78842ab26ebfa50df3931d15405bf00e3b2592b2
refs/heads/master
2016-09-05T09:06:20.083441
2014-06-01T21:10:55
2014-06-01T21:10:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,179
java
package com.brahma.loganalyzer; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.views.ViewBundle; import io.dropwizard.setup.Environment; import io.dropwizard.assets.AssetsBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.brahma.loganalyzer.resources.*; import com.brahma.loganalyzer.core.LogFile; import com.brahma.loganalyzer.health.TemplateHealthCheck; public class LogAnalyzerApplication extends Application<LogAnalyzerConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(LogAnalyzerApplication.class); private AtomicLong counter; public static HashMap<Long, LogFile> logFileList; public static void main(String[] args) throws Exception { new LogAnalyzerApplication().run(args); } @Override public String getName() { return "Log Analyzer"; } @Override public void initialize(Bootstrap<LogAnalyzerConfiguration> bootstrap) { bootstrap.addBundle(new ViewBundle()); bootstrap.addBundle(new AssetsBundle()); } @Override public void run(LogAnalyzerConfiguration configuration, Environment environment) { this.counter = new AtomicLong(); logFileList = new HashMap<Long, LogFile>(); LOGGER.info("Inside run of LogAnalyzer"); final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getUploadLocation()); environment.healthChecks().register("uploadLocation", healthCheck); environment.jersey().register(new LogAnalysisSummaryResource()); environment.jersey().register(new FileUploadResource(counter)); environment.jersey().register(new DefaultLogResource(counter)); environment.jersey().register(new LogFileDetailResource()); environment.jersey().register(new LogAnalyzerMainResource()); environment.jersey().register(new RestfulInformationResource()); environment.jersey().register(com.sun.jersey.multipart.impl.MultiPartReaderServerSide.class); } }
866e7e19a3f06e971619cd851fe21c5f296cef99
5ae001fbd81ae893d7c78ce020382e4c73cdf6a3
/app-client/src/test/java/marc/nguyen/minesweeper/client/data/repositories/MinefieldRepositoryImplTest.java
64a877e10e5e529d273c79d678a1cc62e537ae33
[ "Unlicense" ]
permissive
Darkness4/minesweeper
1ba1c8c20baea7416248fe75575fa5b0b730e27c
bab4c1f4f0999aae57d03352fcd81e85473542c5
refs/heads/master
2022-12-24T17:55:38.762973
2020-10-05T22:47:03
2020-10-05T22:47:03
293,356,173
0
0
null
null
null
null
UTF-8
Java
false
false
2,425
java
package marc.nguyen.minesweeper.client.data.repositories; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import dagger.Lazy; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import marc.nguyen.minesweeper.client.data.devices.ServerSocketDevice; import marc.nguyen.minesweeper.client.domain.repositories.MinefieldRepository; import marc.nguyen.minesweeper.common.data.models.Level; import marc.nguyen.minesweeper.common.data.models.Minefield; import marc.nguyen.minesweeper.common.data.models.Player; import marc.nguyen.minesweeper.common.data.models.Position; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MinefieldRepositoryImplTest { MinefieldRepository repository; ServerSocketDevice device; Lazy<ServerSocketDevice> deviceLazy; @BeforeEach void setUp(@Mock ServerSocketDevice device, @Mock Lazy<ServerSocketDevice> deviceLazy) { this.device = device; this.deviceLazy = deviceLazy; repository = new MinefieldRepositoryImpl(deviceLazy); when(deviceLazy.get()).thenReturn(device); } @Test void fetch() { // Arrange final var t = new Minefield(Level.EASY, true); when(device.getObservable()) .thenReturn(Observable.just("trash object", t, new Player("Not the right data"))); final TestObserver<Minefield> observer = new TestObserver<>(); // Act repository.fetch().subscribe(observer); // Assert observer.assertComplete(); observer.assertValue(t); } @Test void watchTiles() { // Arrange final var t = new Position(0, 0); when(device.getObservable()) .thenReturn(Observable.just("trash object", t, new Player("Not the right data"))); final TestObserver<Position> observer = new TestObserver<>(); // Act repository.watchTiles().subscribe(observer); // Assert observer.assertComplete(); observer.assertValue(t); } @Test void updateTile() { // Arrange final var t = new Position(0, 0); final TestObserver<Position> observer = new TestObserver<>(); // Act repository.updateTile(t).subscribe(observer); // Assert observer.assertComplete(); verify(device).write(t); } }
defce1255c30afb1665142a19003f023f63a82e6
c7907547af0aaf15d3bb87e14142e156d0ba85de
/trunk/BHSC/app/src/main/java/com/bhsc/mobile/net/NewsResponse.java
999ed3264143e4bb0c87dbb9512c0e3dc3186f1b
[]
no_license
bdyz1016/BHVoice
03ffd316aa27a562aaf1326c5ac688b04b05c748
090ab9522410a5bddea91121f4ab7e6479be8004
refs/heads/master
2021-05-24T04:14:38.309919
2020-11-10T06:24:53
2020-11-10T06:24:53
42,421,576
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
package com.bhsc.mobile.net; import com.bhsc.mobile.dataclass.Data_DB_News; import java.util.List; /** * Created by lynn on 11/2/15. */ public class NewsResponse extends Response{ private int code; private List<Data_DB_News> list; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public List<Data_DB_News> getList() { return list; } public void setList(List<Data_DB_News> list) { this.list = list; } }
a3dc4f04baef9d063e5386390062859e4fa53b8c
5e6b13a4d00453b700c34a4c1028d41393404290
/tensquare_friend/src/main/java/com.tensquare.friend/config/InterceptorConfig.java
624d59fd104bf34bb77cfd5a23225d88f01b6001
[]
no_license
liyunhe174/tensquare
27ed4157498043da7c658a4871c3b38795c0f555
539491499acf388822591b348eb4c4d890c201f8
refs/heads/master
2020-12-28T14:26:13.984631
2020-04-17T09:37:20
2020-04-17T09:37:20
238,369,221
1
1
null
null
null
null
UTF-8
Java
false
false
781
java
package com.tensquare.friend.config; import com.tensquare.friend.filter.JwtFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * @Auther: liyunhe * @Date: 2020/1/29 21:32 * @Description: */ @Component public class InterceptorConfig extends WebMvcConfigurationSupport { @Autowired private JwtFilter jwtFilter; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtFilter) .addPathPatterns("/**") .excludePathPatterns("/**/login"); } }
e40eebe4df0b9d5f60dc388e2ef9987307ca6137
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-health/src/main/java/com/amazonaws/services/health/model/transform/OrganizationEventDetailsMarshaller.java
4c82cbb3299474dc77e799216a3f939f87b08876
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379135
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
2023-09-13T23:35:28
2010-03-22T23:34:58
null
UTF-8
Java
false
false
3,067
java
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.health.model.transform; import java.util.Map; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.health.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * OrganizationEventDetailsMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class OrganizationEventDetailsMarshaller { private static final MarshallingInfo<String> AWSACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("awsAccountId").build(); private static final MarshallingInfo<StructuredPojo> EVENT_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("event").build(); private static final MarshallingInfo<StructuredPojo> EVENTDESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("eventDescription").build(); private static final MarshallingInfo<Map> EVENTMETADATA_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("eventMetadata").build(); private static final OrganizationEventDetailsMarshaller instance = new OrganizationEventDetailsMarshaller(); public static OrganizationEventDetailsMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(OrganizationEventDetails organizationEventDetails, ProtocolMarshaller protocolMarshaller) { if (organizationEventDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(organizationEventDetails.getAwsAccountId(), AWSACCOUNTID_BINDING); protocolMarshaller.marshall(organizationEventDetails.getEvent(), EVENT_BINDING); protocolMarshaller.marshall(organizationEventDetails.getEventDescription(), EVENTDESCRIPTION_BINDING); protocolMarshaller.marshall(organizationEventDetails.getEventMetadata(), EVENTMETADATA_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
43314ab67cd225ee7432cac95beb7980be5c896c
f1e0b51e22c88fd0f1763bafdd349c1b3582c085
/app/src/main/java/com/rikkathewrold/rikkamusic/search/mvp/view/fragments/SingerSearchFragment.java
acca98eb5cc4e23d4f8291b4cb172f1d0594e49b
[]
no_license
yiwanwanwan/RikkaMusic
43c8f8396661fef29ae42a09d3fbf79f8cb7fc18
235598fbcc7a9cc2803006169d16ce1d7051ef8c
refs/heads/master
2023-02-11T02:31:53.936500
2021-01-08T02:34:41
2021-01-08T02:34:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,383
java
package com.rikkathewrold.rikkamusic.search.mvp.view.fragments; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.blankj.utilcode.util.ToastUtils; import com.rikkathewrold.rikkamusic.R; import com.rikkathewrold.rikkamusic.base.BaseFragment; import com.rikkathewrold.rikkamusic.search.adapter.SingerSearchAdapter; import com.rikkathewrold.rikkamusic.search.bean.AlbumSearchBean; import com.rikkathewrold.rikkamusic.search.bean.FeedSearchBean; import com.rikkathewrold.rikkamusic.search.bean.HotSearchDetailBean; import com.rikkathewrold.rikkamusic.search.bean.PlayListSearchBean; import com.rikkathewrold.rikkamusic.search.bean.RadioSearchBean; import com.rikkathewrold.rikkamusic.search.bean.SingerSearchBean; import com.rikkathewrold.rikkamusic.search.bean.SongSearchBean; import com.rikkathewrold.rikkamusic.search.bean.SynthesisSearchBean; import com.rikkathewrold.rikkamusic.search.bean.UserSearchBean; import com.rikkathewrold.rikkamusic.search.event.KeywordsEvent; import com.rikkathewrold.rikkamusic.search.mvp.contract.SearchContract; import com.rikkathewrold.rikkamusic.search.mvp.presenter.SearchPresenter; import com.rikkathewrold.rikkamusic.search.mvp.view.SearchResultActivity; import com.rikkathewrold.rikkamusic.search.mvp.view.SingerActivity; import com.rikkathewrold.rikkamusic.util.LogUtil; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import static com.rikkathewrold.rikkamusic.search.mvp.view.SingerActivity.SINGER_ID; import static com.rikkathewrold.rikkamusic.search.mvp.view.SingerActivity.SINGER_NAME; import static com.rikkathewrold.rikkamusic.search.mvp.view.SingerActivity.SINGER_PICURL; /** * 歌手搜索界面 100 */ @SuppressLint("ValidFragment") public class SingerSearchFragment extends BaseFragment<SearchPresenter> implements SearchContract.View { private static final String TAG = "SingerSearchFragment"; @BindView(R.id.rv) RecyclerView rvSinger; private String type; private String keywords; private boolean needRefresh = false; private int searchType = 100; private SingerSearchAdapter adapter; private List<SingerSearchBean.ResultBean.ArtistsBean> list = new ArrayList<>(); public SingerSearchFragment() { } public SingerSearchFragment(String type) { this.type = type; setFragmentTitle(type); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onGetKeywordsEvent(KeywordsEvent event) { LogUtil.d(TAG, "onGetKeywordsEvent : " + event); if (event != null) { if (keywords != null && !event.getKeyword().equals(keywords)) { needRefresh = true; if (((SearchResultActivity) getActivity()).getPosition() == 1) { needRefresh = false; keywords = event.getKeyword(); showDialog(); mPresenter.getSingerSearch(keywords, searchType); } } keywords = event.getKeyword(); } } @Override protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_recyclerview, container, false); ButterKnife.bind(this, rootView); EventBus.getDefault().register(this); return rootView; } @Override protected void initData() { adapter = new SingerSearchAdapter(getContext()); LinearLayoutManager manager = new LinearLayoutManager(getContext()); rvSinger.setLayoutManager(manager); rvSinger.setAdapter(adapter); adapter.setListener(listener); adapter.setKeywords(keywords); if (keywords != null) { showDialog(); mPresenter.getSingerSearch(keywords, searchType); } } SingerSearchAdapter.OnSingerClickListener listener = position -> { if (list != null) { //进入歌手界面 Intent intent = new Intent(getActivity(), SingerActivity.class); intent.putExtra(SINGER_ID, list.get(position).getId()); intent.putExtra(SINGER_PICURL, list.get(position).getPicUrl()); String name = list.get(position).getName(); if (!TextUtils.isEmpty(list.get(position).getTrans())) { name += "(" + list.get(position).getTrans() + ")"; } intent.putExtra(SINGER_NAME, name); getActivity().startActivity(intent); } }; @Override public SearchPresenter onCreatePresenter() { return new SearchPresenter(this); } @Override protected void initVariables(Bundle bundle) { } @Override protected void onVisible() { super.onVisible(); if (needRefresh) { needRefresh = false; showDialog(); mPresenter.getSingerSearch(keywords, searchType); } } @Override public void onClick(View v) { } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Override public void onGetHotSearchDetailSuccess(HotSearchDetailBean bean) { } @Override public void onGetHotSearchDetailFail(String e) { } @Override public void onGetSongSearchSuccess(SongSearchBean bean) { } @Override public void onGetSongSearchFail(String e) { } @Override public void onGetFeedSearchSuccess(FeedSearchBean bean) { } @Override public void onGetFeedSearchFail(String e) { } @Override public void onGetSingerSearchSuccess(SingerSearchBean bean) { hideDialog(); LogUtil.d(TAG, "onGetSingerSearchSuccess : " + bean); list.clear(); if (bean.getResult().getArtists() != null) { list.addAll(bean.getResult().getArtists()); } adapter.notifyDataSetChanged(list); } @Override public void onGetSingerSearchFail(String e) { hideDialog(); LogUtil.d(TAG, "onGetSingerSearchFail : " + e); ToastUtils.showShort(e); } @Override public void onGetAlbumSearchSuccess(AlbumSearchBean bean) { } @Override public void onGetAlbumSearchFail(String e) { } @Override public void onGetPlayListSearchSuccess(PlayListSearchBean bean) { } @Override public void onGetPlayListSearchFail(String e) { } @Override public void onGetRadioSearchSuccess(RadioSearchBean bean) { } @Override public void onGetRadioSearchFail(String e) { } @Override public void onGetUserSearchSuccess(UserSearchBean bean) { } @Override public void onGetUserSearchFail(String e) { } @Override public void onGetSynthesisSearchSuccess(SynthesisSearchBean bean) { } @Override public void onGetSynthesisSearchFail(String e) { } }
2177274ccbf5e9e29605c09e6d501303e08b307f
1384811d9229c71776775afc48fb317d8220e8cf
/fetch_api/LessonExample/src/main/java/LessonExample/Controllers/HomeController.java
7df16b2dbba21bd5cfef35666d88e38d01d33177
[]
no_license
jacksnett/home-projects
2ab74e60147fb80a5133d810a5b4dc918d0bccaa
d54bd63a30cac26a7f9fdac43a85b890d7d0854c
refs/heads/master
2023-03-03T04:34:45.249467
2021-02-07T07:19:02
2021-02-07T07:19:02
332,538,798
0
0
null
null
null
null
UTF-8
Java
false
false
290
java
package LessonExample.Controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @RequestMapping("/") public String home() { return ("views/index.html"); } }
913ac0e79a2207d2515dc15cbb991851dfa28d5b
08dbac1864b25939040fcedc38b08774b9547aec
/app/src/main/java/com/siweisoft/heavycenter/module/main/order/detail/OrderDetailCT.java
3af57547b20a1ef476cc916e81f8639f83b73dc0
[]
no_license
summerviwox/heavycenter
b605346bc620ec340d560351db72b312e522d261
273adc2d51cdea5c0156bb5919eb28a19248cc8c
refs/heads/master
2020-12-05T22:06:07.129014
2020-01-07T18:38:36
2020-01-07T18:38:36
232,259,809
0
1
null
null
null
null
UTF-8
Java
false
false
193
java
package com.siweisoft.heavycenter.module.main.order.detail; import com.summer.x.base.ui.XFragment; public class OrderDetailCT extends XFragment<OrderDetailUI,OrderDetailDE,OrderDetailVA> { }
7692a3697d48a6719d784b1779580dcf6feacd65
5b37a090857da63a2318c74116f683851b51863e
/src/main/java/com/rnctech/nrdataservice/resource/ResourceSet.java
4d77c465f68b7fae763a4d487c7b3f3dff2cd349
[]
no_license
rnctechnology/ExecService
273f1e4281a7855f7684833f65ec2b9ded7f096f
fe877e8af5aa9b4abacf7dc5bc9ef39726bddd58
refs/heads/master
2023-02-02T15:52:38.682801
2023-01-29T18:57:31
2023-01-29T18:57:31
216,975,718
0
0
null
2022-11-16T02:41:22
2019-10-23T05:31:57
Java
UTF-8
Java
false
false
2,318
java
package com.rnctech.nrdataservice.resource; import com.google.gson.Gson; import java.util.Collection; import java.util.LinkedList; import java.util.regex.Pattern; /** * Set of resources * * @author zilin 2020.09 */ public class ResourceSet extends LinkedList<Resource> { private static final long serialVersionUID = -8374688173015469744L; private static final Gson gson = new Gson(); public ResourceSet(Collection<Resource> resources) { super(resources); } public ResourceSet() { super(); } public ResourceSet filterByNameRegex(String regex) { ResourceSet result = new ResourceSet(); for (Resource r : this) { if (Pattern.matches(regex, r.getResourceId().getName())) { result.add(r); } } return result; } public ResourceSet filterByName(String name) { ResourceSet result = new ResourceSet(); for (Resource r : this) { if (r.getResourceId().getName().equals(name)) { result.add(r); } } return result; } public ResourceSet filterByClassnameRegex(String regex) { ResourceSet result = new ResourceSet(); for (Resource r : this) { if (r instanceof JResource && Pattern.matches(regex, ((JResource) r).getClassName())) { result.add(r); } } return result; } public ResourceSet filterByClassname(String className) { ResourceSet result = new ResourceSet(); for (Resource r : this) { if (r instanceof JResource && ((JResource) r).getClassName().equals(className)) { result.add(r); } } return result; } public ResourceSet filterByNoteId(String noteId) { ResourceSet result = new ResourceSet(); for (Resource r : this) { if (equals(r.getResourceId().getId(), noteId)) { result.add(r); } } return result; } public ResourceSet filterBySourceType(String sourcetype) { ResourceSet result = new ResourceSet(); for (Resource r : this) { if (equals(r.getResourceId().getSourceType(), sourcetype)) { result.add(r); } } return result; } private boolean equals(String a, String b) { if (a == null && b == null) { return true; } else if (a != null && b != null) { return a.equals(b); } else { return false; } } public String toJson() { return gson.toJson(this); } public static ResourceSet fromJson(String json) { return gson.fromJson(json, ResourceSet.class); } }
11bed928072669e9544ecd169d321979fcf4d29f
f52981eb9dd91030872b2b99c694ca73fb2b46a8
/Source/Plugins/Applet/com.tle.common.applet/src/com/tle/admin/helper/GeneralDialog.java
a8f19e6c95433d528d588dc76e90e1aa790ac7a3
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LGPL-2.1-only", "LicenseRef-scancode-jdom", "GPL-1.0-or-later", "ICU", "CDDL-1.0", "LGPL-3.0-only", "LicenseRef-scancode-other-permissive", "CPL-1.0", "MIT", "GPL-2.0-only", "Apache-2.0", "NetCDF", "Apache-1.1", "EPL-1.0", "Classpath-exception-2.0", "CDDL-1.1", "LicenseRef-scancode-freemarker" ]
permissive
phette23/Equella
baa41291b91d666bf169bf888ad7e9f0b0db9fdb
56c0d63cc1701a8a53434858a79d258605834e07
refs/heads/master
2020-04-19T20:55:13.609264
2019-01-29T03:27:40
2019-01-29T22:31:24
168,427,559
0
0
Apache-2.0
2019-01-30T22:49:08
2019-01-30T22:49:08
null
UTF-8
Java
false
false
4,658
java
/* * Copyright 2017 Apereo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.admin.helper; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; import com.dytech.gui.ComponentHelper; import com.tle.common.i18n.CurrentLocale; public abstract class GeneralDialog implements ActionListener { public static final int OK_RESPONSE = 0; public static final int CANCEL_RESPONSE = 1; protected static final String QUESTION_MARK = "/icons/question.gif"; protected JPanel inner; protected int response; protected Object value; protected JButton okButton; protected JButton cancelButton; private String title; private Component parent; private JComponent content; protected JDialog dialog; private Dimension dialogSize; public GeneralDialog(Component parent, String title) { this.parent = parent; this.title = title; setupGUI(); } public void showDialog() { dialog = ComponentHelper.createJDialog(parent); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setContentPane(content); dialog.setModal(true); if( dialogSize != null ) { dialog.setSize(dialogSize); } dialog.setVisible(true); } public int getResponse() { return response; } public Object getValue() { return value; } public void setSize(int width, int height) { dialogSize = new Dimension(width, height); } protected void setInner(Component c) { inner.removeAll(); inner.add(c); inner.updateUI(); } protected abstract void cancelled(); protected abstract void ok(); protected void setValue(Object o) { value = o; } protected void setupGUI() { inner = new JPanel(); inner.setLayout(new GridLayout(1, 1)); okButton = new JButton(CurrentLocale.get("com.dytech.edge.admin.helper.ok")); cancelButton = new JButton(CurrentLocale.get("com.dytech.edge.admin.helper.cancel")); okButton.addActionListener(this); cancelButton.addActionListener(this); JLabel heading = new JLabel("<html><b>" + title + "</b>"); heading.setAlignmentY(Component.BOTTOM_ALIGNMENT); JPanel top = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS)); top.add(Box.createRigidArea(new Dimension(5, 0))); top.add(new JLabel(new ImageIcon(GeneralDialog.class.getResource(QUESTION_MARK)))); top.add(Box.createRigidArea(new Dimension(5, 0))); top.add(heading); top.add(Box.createHorizontalGlue()); JPanel bottom = new JPanel(); bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS)); bottom.add(Box.createHorizontalGlue()); bottom.add(okButton); bottom.add(Box.createRigidArea(new Dimension(5, 0))); bottom.add(cancelButton); bottom.setMaximumSize(bottom.getPreferredSize()); JPanel middle = new JPanel(); middle.setLayout(new BoxLayout(middle, BoxLayout.X_AXIS)); middle.add(Box.createRigidArea(new Dimension(37, 0))); middle.add(inner); middle.add(Box.createRigidArea(new Dimension(5, 0))); content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); content.add(Box.createRigidArea(new Dimension(0, 5))); content.add(top); content.add(Box.createRigidArea(new Dimension(0, 5))); content.add(middle); content.add(Box.createRigidArea(new Dimension(0, 5))); content.add(bottom); content.add(Box.createRigidArea(new Dimension(0, 5))); } /* * (non-Javadoc) * @see * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { if( e.getSource() == cancelButton ) { onCancel(); } else if( e.getSource() == okButton ) { onOk(); } } protected void onCancel() { response = CANCEL_RESPONSE; cancelled(); dialog.dispose(); } protected void onOk() { response = OK_RESPONSE; ok(); dialog.dispose(); } }