blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
0fa19ca403970c5f37a822efa4e0a9b963f9145c
Java
firwind/3fou_com_android
/app/src/main/java/com/zhiyicx/thinksnsplus/modules/home/message/managergroup/album/MessageGroupAlbumActivity.java
UTF-8
1,880
1.8125
2
[]
no_license
package com.zhiyicx.thinksnsplus.modules.home.message.managergroup.album; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import com.hyphenate.util.DensityUtil; import com.orhanobut.logger.Logger; import com.zhiyicx.baseproject.base.TSActivity; import com.zhiyicx.thinksnsplus.R; import com.zhiyicx.thinksnsplus.base.AppApplication; import com.zhiyicx.thinksnsplus.data.beans.ChatGroupNewBean; import com.zhiyicx.thinksnsplus.i.IntentKey; /** * <pre> * @author : huwenyong * @date : 2018/6/22 15:41 * desc : 群相册 * version : 1.0 * <pre> */ public class MessageGroupAlbumActivity extends TSActivity<MessageGroupAlbumPresenter,MessageGroupAlbumFragment>{ public static Intent newIntent(Context mContext, ChatGroupNewBean chatGroupNewBean){ Intent intent = new Intent(mContext,MessageGroupAlbumActivity.class); intent.putExtra(IntentKey.GROUP_INFO, (Parcelable) chatGroupNewBean); return intent; } @Override protected MessageGroupAlbumFragment getFragment() { return MessageGroupAlbumFragment.newInstance(getIntent().getParcelableExtra(IntentKey.GROUP_INFO)); } @Override protected void componentInject() { DaggerMessageGroupAlbumComponent.builder() .appComponent(AppApplication.AppComponentHolder.getAppComponent()) .messageGroupAlbumPresenterModule(new MessageGroupAlbumPresenterModule(mContanierFragment)) .build() .inject(this); } @Override protected void initView(Bundle savedInstanceState) { super.initView(savedInstanceState); } }
true
bab777171a775cb786f9f499797e16a5dd240e45
Java
Simone-Ghidoli/ing-sw-2020-Ghidoli-Giannini-Greco
/src/main/java/it/polimi/ingsw/ps60/serverSide/controller/turn/turnEffects/MinotaurTurnEffect.java
UTF-8
780
2.40625
2
[]
no_license
package it.polimi.ingsw.ps60.serverSide.controller.turn.turnEffects; import it.polimi.ingsw.ps60.serverSide.model.Worker; import static it.polimi.ingsw.ps60.GlobalVariables.game; public class MinotaurTurnEffect extends BaseTurnEffect { @Override public void move(int[][] move) { Worker worker = game.getPlayerInGame().get().getWorker(move[0][0]); int[] delta = {move[1][0] - worker.getCellPosition().getPosition()[0], move[1][1] - worker.getCellPosition().getPosition()[1]}; if (!game.getCellByPosition(move[1]).isFree()) game.getCellByPosition(move[1]).getWorkerIn().moveWorker (game.getCellByPosition(new int[]{move[1][0] + delta[0], move[1][1] + delta[1]})); super.move(move); } }
true
c0d4c032280bb896f7d1e58ade90d13baaec3adc
Java
JammersTho/practice
/app/src/main/java/com/example/anton/sticky_notes_1test/SecondScreen.java
UTF-8
2,576
2.21875
2
[]
no_license
package com.example.anton.sticky_notes_1test; import android.annotation.TargetApi; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class SecondScreen extends AppCompatActivity { public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE= 5469; private boolean permitionGranted = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_screen); final Intent notificationHeadIntent = new Intent(getBaseContext(), FloatingHeadService.class); //stop the service for the floating head and return to the main activitys final Button buttonBack = (Button) findViewById(R.id.button); buttonBack.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { stopService(notificationHeadIntent); finish(); } }); //start the service for the floating head final Button buttonShowHead = (Button) findViewById(R.id.button2); buttonShowHead.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ checkPermission(); if (permitionGranted){ startService(notificationHeadIntent); } }else{ startService(notificationHeadIntent); } } }); } public void checkPermission() { if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE); }else{ permitionGranted = true; } } @TargetApi(23) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) { if (!Settings.canDrawOverlays(this)) { checkPermission(); } else { permitionGranted = true; } } } }
true
13d969b07edf46ea02549df199bab5a7ef78e676
Java
Krrish0/SoulMusic_Player
/app/src/main/java/dark/ash/com/soulmusicplayer/ui/FragmentBase.java
UTF-8
276
1.71875
2
[]
no_license
package dark.ash.com.soulmusicplayer.ui; import android.support.v4.app.Fragment; public abstract class FragmentBase extends Fragment { public abstract String getMediaId(); public abstract void setMediaId(String mediaId); public abstract void onConnected(); }
true
fa0ebb5eb0c66269bf20f3faa29b7d9045f91431
Java
AntonKalaturnyi/pizzeria-pro
/service-impl/src/main/java/pzinsta/pizzeria/service/impl/OrderItemTemplateServiceImpl.java
UTF-8
791
2.0625
2
[ "MIT" ]
permissive
package pzinsta.pizzeria.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pzinsta.pizzeria.dao.OrderItemTemplateDAO; import pzinsta.pizzeria.model.order.OrderItemTemplate; import pzinsta.pizzeria.service.OrderItemTemplateService; import java.util.Collection; @Service public class OrderItemTemplateServiceImpl implements OrderItemTemplateService { private OrderItemTemplateDAO orderItemTemplateDAO; @Autowired public OrderItemTemplateServiceImpl(OrderItemTemplateDAO orderItemTemplateDAO) { this.orderItemTemplateDAO = orderItemTemplateDAO; } @Override public Collection<OrderItemTemplate> getOrderItemTemplates() { return orderItemTemplateDAO.findAll(); } }
true
6ad1ca9199306b0e158d09cbf8e8b37e28f998cb
Java
Allpo/cosplay_stuff
/app/src/main/java/allpo/cosplaystuff/activities/gallery/PictureGalleryAdapter.java
UTF-8
4,392
2.234375
2
[]
no_license
package allpo.cosplaystuff.activities.gallery; import android.content.Context; import android.graphics.Bitmap; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ArrayAdapter; import android.widget.ImageView; import java.util.HashMap; import java.util.List; import java.util.Map; import allpo.cosplaystuff.R; import allpo.cosplaystuff.activities.home.HomeProjectListActivity; import allpo.cosplaystuff.datas.CosplayPicture; import allpo.cosplaystuff.helpers.Utils.ImageHelper; /** * Created by Allpo on 16/08/2014. */ public class PictureGalleryAdapter extends ArrayAdapter<CosplayPicture> { public static final String TAG = "PictureGalleryAdapter"; private List<CosplayPicture> mDatas; private Map<Integer, Bitmap> mPics; public PictureGalleryAdapter(Context context, int resource, List<CosplayPicture> picList) { super(context, resource); mPics = new HashMap<Integer, Bitmap>(); mDatas = picList; } @Override public int getCount() { if (mDatas == null){ return 0; } return mDatas.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = convertView; GalleryPictureViewHolder holder; //if rowview == null then we need to create the view //it means the list view is not full of view if (rowView == null) { rowView = inflater.inflate(R.layout.item_grid_list_picture, parent, false); holder = new GalleryPictureViewHolder(); holder.picture = (ImageView) rowView.findViewById(R.id.picture_gallery_item_picture); rowView.setTag(holder); } else { //in this case it means we've reach the maximum number of view //we will re-use a recyclable view holder = (GalleryPictureViewHolder) rowView.getTag(); } CosplayPicture cosplayPicture = mDatas.get(position); holder.picture.setVisibility(View.INVISIBLE); //Get the Drawable as default image // if (((AbstractActivity) getContext()).image == null) { // ((AbstractActivity) getContext()).image = ImageHelper.createRoundImage(BitmapFactory.decodeResource(getContext().getResources(), R.drawable.cs_cerberus)); // } // holder.picture.setImageBitmap(((HomeProjectListActivity) getContext()).image); LoadImageTask task = new LoadImageTask(); task.holder = holder; task.position = position; task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return rowView; } private class GalleryPictureViewHolder{ ImageView picture; } //AsyncTask that will lazyload the picture to avoid freeze during the scroll private class LoadImageTask extends AsyncTask<Void, Void, Void>{ public int position; public GalleryPictureViewHolder holder; private Bitmap pic; boolean isInCache = true; @Override protected Void doInBackground(Void... params) { CosplayPicture project = mDatas.get(position); pic = mPics.get(project.getId()); if (pic == null) { isInCache = false; Log.d(TAG, "Getting picture from object"); if (project.getPath() != null) { pic = ImageHelper.createPreviewImage(ImageHelper.getBitmapFromPath(project.getPath())); } else { pic = ((HomeProjectListActivity) getContext()).image; } mPics.put(project.getId(), pic); } return null; } @Override protected void onPostExecute(Void aVoid) { holder.picture.setImageBitmap(pic); if (!isInCache) { Animation myFadeInAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in); holder.picture.startAnimation(myFadeInAnimation); } holder.picture.setVisibility(View.VISIBLE); } } }
true
382374882bff5f82af47a3c1bf55cd8e406f0c12
Java
btsv56/Ride-sharing-software-isep-lapr3
/src/main/java/lapr/project/controller/RemoveVehicleController.java
UTF-8
1,008
2.4375
2
[]
no_license
/* * 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 lapr.project.controller; import java.sql.SQLException; import lapr.project.data.VehicleDB; import lapr.project.model.VehiclesRegistry; /** * * @author bruno */ public class RemoveVehicleController { private final VehiclesRegistry vr; /** * */ public RemoveVehicleController() { vr = new VehiclesRegistry(); } /** * * @param vdb */ public RemoveVehicleController(VehicleDB vdb) { vr = new VehiclesRegistry(); vr.setVehicleDB(vdb); } /** * * @param idVehicle * @return */ public boolean removeVehicle(int idVehicle){ try { vr.removeVehicle(idVehicle); return true; } catch (SQLException e) { return false; } } }
true
7dc7e3141424ae5ecb1ea29361ebce9f4d445229
Java
aheadlcx/analyzeApk
/baike/sources/com/baidu/mobads/utils/m.java
UTF-8
12,880
1.789063
2
[]
no_license
package com.baidu.mobads.utils; import android.annotation.TargetApi; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Build.VERSION; import com.baidu.mobads.a.a; import com.baidu.mobads.interfaces.utils.IBase64; import com.baidu.mobads.interfaces.utils.IXAdPackageUtils; import com.baidu.mobads.interfaces.utils.IXAdPackageUtils.ApkInfo; import com.baidu.mobads.interfaces.utils.IXAdSystemUtils; import com.baidu.mobads.interfaces.utils.IXAdURIUitls; import com.baidu.mobads.openad.FileProvider; import com.baidu.mobads.openad.d.c; import com.tencent.bugly.Bugly; import com.xiaomi.mipush.sdk.Constants; import java.io.File; import java.util.List; import org.eclipse.paho.client.mqttv3.internal.ClientDefaults; public class m implements IXAdPackageUtils { public boolean isInstalled(Context context, String str) { try { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(str, 0); if (applicationInfo == null || !str.equals(applicationInfo.packageName)) { return false; } return true; } catch (NameNotFoundException e) { return false; } } public boolean isSystemPackage(PackageInfo packageInfo) { return (packageInfo.applicationInfo.flags & 1) != 0; } @TargetApi(3) public void openApp(Context context, String str) { try { Intent launchIntentForPackage = context.getPackageManager().getLaunchIntentForPackage(str); launchIntentForPackage.addFlags(ClientDefaults.MAX_MSG_SIZE); context.startActivity(launchIntentForPackage); } catch (Exception e) { } } @Deprecated public Intent getInstallIntent(String str) { try { Uri fromFile = Uri.fromFile(new File(str)); Intent intent = new Intent("android.intent.action.VIEW"); try { intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(ClientDefaults.MAX_MSG_SIZE); intent.setDataAndType(fromFile, "application/vnd.android.package-archive"); return intent; } catch (Exception e) { return intent; } } catch (Exception e2) { return null; } } public Intent a(Context context, File file) { Intent intent; if (file != null) { try { if (file.exists()) { Uri c; intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); if (c(context)) { intent.addFlags(268435457); c = c(context, file); } else { intent.addFlags(ClientDefaults.MAX_MSG_SIZE); c = Uri.fromFile(file); } if (c == null) { return null; } intent.setDataAndType(c, "application/vnd.android.package-archive"); return intent; } } catch (Exception e) { e.printStackTrace(); return null; } } intent = null; return intent; } private boolean c(Context context) { return VERSION.SDK_INT >= 24 && b(context) >= 24; } private Uri c(Context context, File file) { try { return FileProvider.getUriForFile(context, context.getPackageName() + ".bd.provider", file); } catch (Exception e) { e.printStackTrace(); return null; } } public boolean a(Context context) { if (!c(context)) { return true; } File file = new File(XAdSDKFoundationFacade.getInstance().getIoUtils().getStoreagePath(context) + "t"); if (!file.exists()) { file.mkdir(); } if (c(context, file) != null) { return true; } return false; } public Intent a(Context context, String str) { Intent intent = null; try { intent = a(context, new File(str)); } catch (Exception e) { e.printStackTrace(); } return intent; } public void b(Context context, File file) { try { context.startActivity(a(context, file)); } catch (Exception e) { e.printStackTrace(); } } public void b(Context context, String str) { try { context.startActivity(a(context, str)); } catch (Exception e) { e.printStackTrace(); } } public int getAppVersion(Context context) { int i = 0; try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 16384).versionCode; } catch (NameNotFoundException e) { return i; } } public ApkInfo getLocalApkFileInfo(Context context, String str) { try { PackageInfo packageArchiveInfo = context.getPackageManager().getPackageArchiveInfo(str, 1); if (packageArchiveInfo != null) { return new ApkInfo(context, packageArchiveInfo); } return null; } catch (Exception e) { return null; } } public boolean isForeground(Context context, String str) { try { for (RunningAppProcessInfo runningAppProcessInfo : ((ActivityManager) context.getSystemService("activity")).getRunningAppProcesses()) { if (runningAppProcessInfo.processName.equals(str)) { if (runningAppProcessInfo.importance == 100) { return true; } return false; } } return false; } catch (Exception e) { return false; } } public void sendAPOIsSuccess(Context context, boolean z, int i, String str, String str2) { d commonUtils = XAdSDKFoundationFacade.getInstance().getCommonUtils(); IXAdURIUitls uRIUitls = XAdSDKFoundationFacade.getInstance().getURIUitls(); IXAdSystemUtils systemUtils = XAdSDKFoundationFacade.getInstance().getSystemUtils(); IBase64 base64 = XAdSDKFoundationFacade.getInstance().getBase64(); String encodeUrl = uRIUitls.encodeUrl(str); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("aposuccess=" + z); if (!z) { stringBuilder.append("&failtime=" + i); } stringBuilder.append("&sn=" + systemUtils.getEncodedSN(context)); stringBuilder.append("&mac=" + base64.encode(systemUtils.getMacAddress(context))); stringBuilder.append("&cuid=" + systemUtils.getCUID(context)); stringBuilder.append("&pack=" + context.getPackageName()); stringBuilder.append("&v=" + ("android_" + a.c + "_" + "4.1.30")); stringBuilder.append("&targetscheme=" + encodeUrl); stringBuilder.append("&pk=" + str2); try { c cVar = new c(uRIUitls.addParameters(commonUtils.vdUrl(stringBuilder.toString(), 369), null), ""); cVar.e = 1; new com.baidu.mobads.openad.d.a().a(cVar); } catch (Exception e) { XAdSDKFoundationFacade.getInstance().getAdLogger().d("XAdPackageUtils", e.getMessage()); } } public boolean sendAPOInfo(Context context, String str, String str2, int i, int i2, int i3) { String str3; boolean z; PackageManager packageManager = context.getPackageManager(); IXAdSystemUtils systemUtils = XAdSDKFoundationFacade.getInstance().getSystemUtils(); IXAdURIUitls uRIUitls = XAdSDKFoundationFacade.getInstance().getURIUitls(); d commonUtils = XAdSDKFoundationFacade.getInstance().getCommonUtils(); Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(str)); intent.addFlags(ClientDefaults.MAX_MSG_SIZE); String encodeUrl = uRIUitls.encodeUrl(str); List queryIntentActivities = packageManager.queryIntentActivities(intent, 65536); String str4 = "&sn=" + systemUtils.getEncodedSN(context) + "&fb_act=" + i2 + "&pack=" + context.getPackageName() + "&v=" + ("android_" + a.c + "_" + "4.1.30") + "&targetscheme=" + encodeUrl + "&pk=" + str2; String str5 = "&open="; if (queryIntentActivities.size() > 0) { str5 = str5 + "true"; encodeUrl = ""; str3 = str5 + "&n=" + queryIntentActivities.size(); z = true; int i4 = 0; while (i4 < queryIntentActivities.size()) { boolean z2; ResolveInfo resolveInfo = (ResolveInfo) queryIntentActivities.get(i4); if (i4 == 0) { str3 = str3 + "&p=" + resolveInfo.activityInfo.packageName; } else { str3 = str3 + Constants.ACCEPT_TIME_SEPARATOR_SP + resolveInfo.activityInfo.packageName; } if (str2.equals(resolveInfo.activityInfo.packageName)) { try { int i5 = packageManager.getPackageInfo(resolveInfo.activityInfo.packageName, 0).versionCode; if (i5 < i3) { z = false; } str5 = encodeUrl + "&installedVersion=" + i5 + "&requiredVersion=" + i3 + "&realopen=" + z; z2 = z; } catch (Exception e) { Exception exception = e; Exception exception2 = exception; str5 = encodeUrl + "&exception=true&installedVersion=" + -1 + "&requiredVersion=" + i3 + "&realopen=" + z; exception2.printStackTrace(); z2 = z; } } else { str5 = encodeUrl; z2 = z; } i4++; z = z2; encodeUrl = str5; } if (!encodeUrl.equals("")) { str3 = str3 + encodeUrl; } } else { z = false; str3 = str5 + Bugly.SDK_IS_DEV; } try { c cVar = new c(uRIUitls.addParameters(commonUtils.vdUrl(str4 + str3, i), null), ""); cVar.e = 1; new com.baidu.mobads.openad.d.a().a(cVar); } catch (Exception e2) { XAdSDKFoundationFacade.getInstance().getAdLogger().d("XAdPackageUtils", e2.getMessage()); } return z; } public void sendDialerIsSuccess(Context context, boolean z, int i, String str) { d commonUtils = XAdSDKFoundationFacade.getInstance().getCommonUtils(); IXAdURIUitls uRIUitls = XAdSDKFoundationFacade.getInstance().getURIUitls(); IXAdSystemUtils systemUtils = XAdSDKFoundationFacade.getInstance().getSystemUtils(); IBase64 base64 = XAdSDKFoundationFacade.getInstance().getBase64(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("callstate=" + z); if (!z) { stringBuilder.append("&duration=" + i); } stringBuilder.append("&sn=" + systemUtils.getEncodedSN(context)); stringBuilder.append("&mac=" + base64.encode(systemUtils.getMacAddress(context))); stringBuilder.append("&bdr=" + VERSION.SDK_INT); stringBuilder.append("&cuid=" + systemUtils.getCUID(context)); stringBuilder.append("&pack=" + context.getPackageName()); stringBuilder.append("&v=" + ("android_" + a.c + "_" + "4.1.30")); stringBuilder.append("&pk=" + str); try { c cVar = new c(uRIUitls.addParameters(commonUtils.vdUrl(stringBuilder.toString(), 372), null), ""); cVar.e = 1; new com.baidu.mobads.openad.d.a().a(cVar); } catch (Exception e) { XAdSDKFoundationFacade.getInstance().getAdLogger().d("XAdPackageUtils", e.getMessage()); } } public int b(Context context) { int i = 0; try { return context.getApplicationContext().getApplicationInfo().targetSdkVersion; } catch (Exception e) { e.printStackTrace(); return i; } } }
true
fbe0a4abab3ef56e7d79bf38342e29412328968c
Java
joao-goncalves-morphis/CodeGuru
/src/main/java/cgd/ho/structures/link/Bhol351a.java
UTF-8
7,280
1.929688
2
[]
no_license
package cgd.ho.structures.link; import morphis.framework.datatypes.structs.IDataStruct ; import morphis.framework.datatypes.annotations.Data ; import morphis.framework.datatypes.fields.* ; import static morphis.framework.commons.StringHandling.* ; import static morphis.framework.commons.MathHandling.* ; import java.math.BigDecimal ; import static morphis.framework.datatypes.serialization.Algorithm.* ; import morphis.framework.datatypes.annotations.Condition ; import morphis.framework.datatypes.conditions.ICondition ; import morphis.framework.datatypes.conditions.IConditions ; import morphis.framework.datatypes.arrays.IArray ; /** * * * @version 2.0 * */ public interface Bhol351a extends IDataStruct { /** * @return instancia da classe local Commarea */ @Data Commarea commarea() ; @Data(size=8, value="MHOJ351A") IString nmRotina() ; /** * Inner Classes */ /** * * BHOL351A - AREA DE LIGACAO DA ROTINA HISTORICO DE MOVIMENTOS * * @version 2.0 * */ public interface Commarea extends IDataStruct { /** * @return instancia da classe local DadosInput */ @Data DadosInput dadosInput() ; /** * @return instancia da classe local AreaOutput */ @Data AreaOutput areaOutput() ; public interface DadosInput extends IDataStruct { @Data(size=1) IString debug() ; @Data @Condition("S") ICondition debugSim() ; @Data @Condition("N") ICondition debugNao() ; /** * @return instancia da classe local Subconta */ @Data Subconta subconta() ; @Data(size=15, signed=true, compression=COMP3) ILong nsMovimento() ; @Data(size=1) IString iConsultas() ; @Data(size=1) IString iMovDia() ; @Data(size=2, signed=true, compression=COMP3) IInt qMovimentos() ; public interface Subconta extends IDataStruct { @Data(size=3) IString cPaisIsoaCont() ; @Data(size=4, signed=true, compression=COMP3) IInt cBancCont() ; @Data(size=4, signed=true, compression=COMP3) IInt cOeEgcCont() ; @Data(size=7, signed=true, compression=COMP3) IInt nsRdclCont() ; @Data(size=1, signed=true, compression=COMP3) IInt vChkdCont() ; @Data(size=3, signed=true, compression=COMP3) IInt cTipoCont() ; @Data(size=3) IString cMoedIsoScta() ; @Data(size=4, signed=true, compression=COMP3) IInt nsDeposito() ; } } public interface AreaOutput extends IDataStruct { /** * @return instancia da classe local TabMovimentos */ @Data(length=13) IArray<TabMovimentos> tabMovimentos() ; @Data(size=2, signed=true, compression=COMP3) IInt qPndeEnvr() ; @Data @Condition("13") ICondition pagCheia() ; /** * @return instancia da classe local DadosErro */ @Data DadosErro dadosErro() ; public interface TabMovimentos extends IDataStruct { @Data(size=15, signed=true, compression=COMP3) ILong nsMovimentoO() ; @Data(size=10) IString zMovimentoO() ; @Data(size=10) IString zValorO() ; @Data(size=21) IString xRefMovO() ; @Data(size=17, decimal=2, signed=true, compression=COMP3) IDecimal mMovimentoO() ; @Data(size=17, decimal=2, signed=true, compression=COMP3) IDecimal mSldoCbloO() ; @Data(size=1) IString iDbcrO() ; @Data(size=1) IString iEstornoO() ; @Data(size=3) IString cMoedIsoOriMovO() ; @Data(size=17, decimal=2, signed=true, compression=COMP3) IDecimal mSldoCbloAposO() ; @Data(size=17, decimal=2, signed=true, compression=COMP3) IDecimal mSldoDpnlAposO() ; @Data(size=10, signed=true, compression=COMP3) ILong nDocumentoO() ; @Data(size=17, decimal=2, signed=true, compression=COMP3) IDecimal mMovMoeOrigMovO() ; @Data(size=2) IString aAplOrigO() ; @Data(size=12, decimal=5, signed=true, compression=COMP3) IDecimal tJuroO() ; } public interface DadosErro extends IDataStruct { @Data(size=9, signed=true, compression=COMP3) ILong cSqlcode() ; @Data(size=2) IString aAplErr() ; @Data(size=3, signed=true, compression=COMP3) IInt cRtnoEvenSwal() ; @Data @Condition("049") ICondition dadosNotfnd() ; @Data(size=50) IString msgErrob() ; @Data(size=8) IString nmTabela() ; @Data(size=8) IString modOrigemErro() ; @Data(size=40) IString chAcesso() ; @Data(size=2) IString cTipoErroBbn() ; @Data @Condition("A1") ICondition abend() ; @Data @Condition("A2") ICondition abendDb2() ; @Data @Condition("A3") ICondition abendCics() ; @Data @Condition("FU") ICondition erroFuncao() ; @Data @Condition("AU") ICondition autorizacao() ; @Data @Condition("FC") ICondition fimConsulta() ; @Data @Condition(" ") ICondition semErros() ; } } } }
true
2d4777a64505cec33ec6c917ab2cc3c805d4080a
Java
xghrbc1001/xghrbc1001.github.com
/md/java/中文乱码.java
UTF-8
647
2.90625
3
[]
no_license
import java.io.*; import java.util.regex.*; public class Test{ public static void main(String []args) throws Exception{ System.exit(0); BufferedReader br = new BufferedReader(new FileReader("s.txt")); Pattern reg = Pattern.compile("[\u00a1-\u00ff]"); Pattern reg2 = Pattern.compile("\u00b7"); String line; while((line = br.readLine()) != null){ Matcher m = reg.matcher(line); int count = 0; while(m.find()) count++; m = reg2.matcher(line); int cnt = 0; while(m.find()) cnt++; if(count - cnt > 5){ System.out.println(line); } } } }
true
12952d0e700832586f92d16c6be9267c63f07ef5
Java
Arbonkeep/Java-Desisgn-Patterns
/Design-Patterns/DesignPattern/src/com/arbonkeep/proxy/cglib/ProxyFactory.java
GB18030
1,130
3.015625
3
[]
no_license
package com.arbonkeep.proxy.cglib; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class ProxyFactory implements MethodInterceptor{ private Object target; //췽target public ProxyFactory(Object target) { this.target = target; } //һtargetĴ public Object getProxyInstance() { //1.һ Enhancer enhancer = new Enhancer(); //2.ø(ΪĿ꺯) enhancer.setSuperclass(target.getClass()); //3.ûص enhancer.setCallback(this); //4.󣬼 return enhancer.create(); } //дinterceptĿķ @Override public Object intercept(Object arg0, Method method, Object[] args, MethodProxy arg3) throws Throwable { System.out.println("Cglibģʽ ʼ"); Object obj = method.invoke(target, args);//зֵ System.out.println("Cglibģʽύ"); return obj; } }
true
8766a253f0a54cc06e00c1a640a4e22a7d7613ce
Java
so0choi/DesignPattern
/src/decoratorpattern/Beverage.java
UTF-8
589
3.625
4
[]
no_license
package decoratorpattern; public abstract class Beverage { String description = null; Size beverageSize; enum Size { TALL, GRANDE, VENTI }; public String getDescription() { return description; } public abstract double cost(); public void setSize(String size) { if (size.equals("t")) { this.beverageSize = Size.TALL; } else if (size.equals("g")) { this.beverageSize = Size.GRANDE; } else if (size.equals("v")) { this.beverageSize = Size.VENTI; } else { System.out.println("Size error"); } } public Size getSize() { return this.beverageSize; } }
true
4a93472b37bb7a6d1d49fe1dcd750e972234d96f
Java
devabir93/almobarkia
/app/src/main/java/net/selsela/almobarakeya/ui/productlist/SizeRecyclerViewAdapter.java
UTF-8
4,867
2.140625
2
[ "Apache-2.0" ]
permissive
package net.selsela.almobarakeya.ui.productlist; import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import net.selsela.almobarakeya.R; import net.selsela.almobarakeya.data.model.home.Size; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class SizeRecyclerViewAdapter extends RecyclerView.Adapter<SizeRecyclerViewAdapter.ViewHolder> { private Context context; private List<Size> sizes; UpdateDataClickListener updateDataClickListener; private int selectedItem; private int sPosition; private boolean isSelected; private SparseBooleanArray sSelectedItems; private boolean clickable = true; public SizeRecyclerViewAdapter(List<Size> sizes, Context context, UpdateDataClickListener updateDataClickListener) { this.sizes = sizes; this.context = context; this.updateDataClickListener = updateDataClickListener; sSelectedItems = new SparseBooleanArray(); sPosition = 0; selectedItem = 0; isSelected = false; } public void setClickable(boolean b) { this.clickable = b; if (!b) selectedItem = -1; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.sizelist, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { final Size size = sizes.get(position); if (size == null) return; holder.itemView.setClickable(clickable); holder.itemView.setEnabled(clickable); holder.size.setText(size.getName()); if (selectedItem == holder.getAdapterPosition() && !isSelected) { //selected sSelectedItems.put(selectedItem, false); holder.size.setBackgroundColor(ContextCompat.getColor(context, R.color.brown)); holder.size.setTextColor(ContextCompat.getColor(context, R.color.colorprimary)); } else { if (sSelectedItems.get(holder.getAdapterPosition())) { //selected holder.size.setBackgroundColor(ContextCompat.getColor(context, R.color.brown)); holder.size.setTextColor(ContextCompat.getColor(context, R.color.colorprimary)); } else { ///unselected holder.size.setBackground(ContextCompat.getDrawable(context, R.drawable.textview_rectanglel)); holder.size.setTextColor(ContextCompat.getColor(context, R.color.colorprimary)); } } holder.size.setSelected(sSelectedItems.get(holder.getAdapterPosition(), false)); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isSelected = true; if (sSelectedItems.get(holder.getAdapterPosition(), false)) { //selected sSelectedItems.delete(holder.getAdapterPosition()); holder.size.setSelected(false); holder.size.setBackgroundColor(ContextCompat.getColor(context, R.color.brown)); holder.size.setTextColor(ContextCompat.getColor(context, R.color.colorprimary)); } else { ///unselected holder.size.setBackground(ContextCompat.getDrawable(context, R.drawable.textview_rectanglel)); holder.size.setTextColor(ContextCompat.getColor(context, R.color.colorprimary)); sSelectedItems.put(sPosition, false); sSelectedItems.put(holder.getAdapterPosition(), true); holder.size.setSelected(true); } updateDataClickListener.onSizeSelected(size, position); } }); } @Override public int getItemCount() { return sizes.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.size) TextView size; public ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } public void selected(int position) { int previousItem = selectedItem; sPosition = position; notifyDataSetChanged(); notifyItemChanged(previousItem); notifyItemChanged(position); } public interface UpdateDataClickListener { void onSizeSelected(Size size, int position); } }
true
a58a60d16cdb1287d7d105ada605398d22537191
Java
Comfortok/EpamTraining
/practice07chess/Main.java
UTF-8
254
2.203125
2
[]
no_license
package kz.epam.khassenov.practice07chess; public class Main { public static void main(String[] args) { Horse horse = new Horse(); horse.generateSolution(); Queen queen = new Queen(); queen.generateSolution(); } }
true
430f8b74c56d1b5e48d1b62a05c6a6bf74baf5d8
Java
rJankowski93/Appsjar-app
/app/src/main/java/com/krkcoders/appsjar/fragments/AppListFragment.java
UTF-8
1,662
2.15625
2
[]
no_license
package com.krkcoders.appsjar.fragments; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.krkcoders.appsjar.R; import com.krkcoders.appsjar.activities.AppDetails; import com.krkcoders.appsjar.adapters.CaptionedImagesAdapter; import com.krkcoders.appsjar.models.App; import io.realm.Realm; import io.realm.RealmResults; public class AppListFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RecyclerView gameRecycler = (RecyclerView)inflater.inflate(R.layout.game_list_fragment, container, false); Realm realm = Realm.getDefaultInstance(); final RealmResults<App> games = realm.where(App.class).findAll(); CaptionedImagesAdapter adapter = new CaptionedImagesAdapter(games); gameRecycler.setAdapter(adapter); GridLayoutManager layoutManager = new GridLayoutManager(getActivity(),2); gameRecycler.setLayoutManager(layoutManager); adapter.setListener(new CaptionedImagesAdapter.Listener() { public void onClick(int position) { Intent intent = new Intent(getActivity(), AppDetails.class); intent.putExtra("gameId",games.get(position).getId()); getActivity().startActivity(intent); } }); return gameRecycler; } }
true
9907e6ffaeb4b68f77f28a4da5d6d4d61a3b7f90
Java
CerganRadu99/Java-Remote-Learning
/week7/w7p2/src/main/java/com/iquestgroup/remotelearning/week7/w7p2/service/EmployeeService.java
UTF-8
735
2.640625
3
[]
no_license
package com.iquestgroup.remotelearning.week7.w7p2.service; import com.iquestgroup.remotelearning.week7.w7p2.domain.Employee; /** * Provides methods to retrieve information about employees. */ public interface EmployeeService { /** * Determines if a given employee is an assembly line worker. * * @param employee the employee to check * @return true is the employee is an assembly line worker, false otherwise */ public boolean isAssemblyLineWorker(Employee employee); /** * Determines if a given employee is an administrator. * * @param employee the employee to check * @return true is the employee is an administrator, false otherwise */ public boolean isAdministrator(Employee employee); }
true
59e0ddfff6bd0e1d484a4d5dc91f55d195738d7b
Java
seerdaryilmazz/OOB
/user-service/src/main/java/ekol/usermgr/dto/ActiveDirectoryUser.java
UTF-8
4,174
2.328125
2
[]
no_license
package ekol.usermgr.dto; import javax.naming.NamingException; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ldap.core.DirContextOperations; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by kilimci on 27/12/2017. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ActiveDirectoryUser { private String username; private String displayName; private String email; private String phoneNumber; private String mobileNumber; private String office; private String sapNumber; private String thumbnail; public static ActiveDirectoryUser createWith(DirContextOperations userOperations){ ActiveDirectoryUser adUser = new ActiveDirectoryUser(); String username = readAttrAsString(userOperations, "userPrincipalName").toLowerCase(); if(username.contains("@")){ adUser.setUsername(username.split("@")[0]); }else{ adUser.setUsername(username); } adUser.setDisplayName(readAttrAsString(userOperations, "displayname")); adUser.setEmail(readAttrAsString(userOperations, "mail")); adUser.setPhoneNumber(readAttrAsString(userOperations, "telephonenumber")); adUser.setMobileNumber(readAttrAsString(userOperations, "mobile")); adUser.setOffice(readAttrAsString(userOperations, "physicaldeliveryofficename")); String rawSapNumber = readAttrAsString(userOperations, "homephone"); if(rawSapNumber != null){ StringBuilder sapNumber = new StringBuilder(12); for(int i = 0; i < rawSapNumber.length(); i++){ if(Character.isDigit(rawSapNumber.charAt(i))){ sapNumber.append(rawSapNumber.charAt(i)); } } adUser.setSapNumber(sapNumber.toString()); } byte[] thumbnail = readAttrAsByteArray(userOperations, "thumbnailphoto"); if(thumbnail != null){ adUser.setThumbnail(Base64.encodeBase64String(thumbnail)); } return adUser; } private static Object readAttr(DirContextOperations userOperations, String name){ try { return userOperations.getAttributes().get(name) != null ? userOperations.getAttributes().get(name).get() : null; } catch (NamingException e) { Logger logger = LoggerFactory.getLogger(ActiveDirectoryUser.class); logger.error("Error parsing LDAP user account", e); return null; } } private static byte[] readAttrAsByteArray(DirContextOperations userOperations, String name){ return (byte[])readAttr(userOperations, name); } private static String readAttrAsString(DirContextOperations userOperations, String name){ return (String)readAttr(userOperations, name); } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getOffice() { return office; } public void setOffice(String office) { this.office = office; } public String getSapNumber() { return sapNumber; } public void setSapNumber(String sapNumber) { this.sapNumber = sapNumber; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
true
1cb7c5be887004cc64c9788d852e163b1791b245
Java
janesser/messageformat.benchmark
/src/main/java/de/esserjan/edu/messageformat/MessageFormatBenchmark.java
UTF-8
5,216
2.359375
2
[]
no_license
package de.esserjan.edu.messageformat; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.stringtemplate.v4.ST; import com.github.javafaker.ChuckNorris; import com.github.javafaker.DateAndTime; import com.github.javafaker.Faker; import com.github.pwittchen.kirai.library.Kirai; /** * Execute by {@link org.openjdk.jmh.Main}. * * @author jesser@gmx.de */ @Warmup(iterations = 1) @Measurement(iterations = 2) @Fork(2) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class MessageFormatBenchmark { private static final Pattern SF_CONVERT = Pattern.compile("(?<!')\\{([0-9]+)\\}"); private static final ChuckNorris CHUCK_NORRIS = new Faker().chuckNorris(); private static final DateAndTime DATE = new Faker().date(); public static enum TestPatterns { NO_PATTERN("1NO_PATTERN.", null), // SIMPLE_PATTERN("2SIMPLE_PATTERN {0}.", new Supplier<Object[]>() { public Object[] get() { return new Object[] { CHUCK_NORRIS.fact() }; } }), // COMPLEX_PATTERN("3COMPLEX_PATTERN '{3}' {2} {1} {0}.", new Supplier<Object[]>() { public Object[] get() { return new Object[] { // CHUCK_NORRIS.fact(), // CHUCK_NORRIS.fact(), // CHUCK_NORRIS.fact(), // }; } }), // FORMATTING_PATTERN("4FORMATTING_PATTERN {0} {1}.", new Supplier<Object[]>() { public Object[] get() { return new Object[] { // CHUCK_NORRIS.fact(), // DATE.birthday(), // }; } }), // ; private final String pattern; private final Supplier<Object[]> argSupplier; private final String format; private final String namedCurly; private final String namedTagged; private TestPatterns(String pattern, Supplier<Object[]> argSupplier) { this.pattern = pattern; this.argSupplier = argSupplier; this.format = SF_CONVERT.matcher(pattern).replaceAll("%s"); this.namedCurly = SF_CONVERT.matcher(pattern.replace("{3}", "3")).replaceAll("{arg$1}"); this.namedTagged = SF_CONVERT.matcher(pattern).replaceAll("<arg$1>"); } public Object[] getArgs() { if (argSupplier == null) return null; else return argSupplier.get(); } public String getPattern() { return pattern; } public String getFormat() { return format; } public String getNamedCurly() { return namedCurly; } public String getNamedTagged() { return namedTagged; } } @Param({ "NO_PATTERN", "SIMPLE_PATTERN", "COMPLEX_PATTERN", "FORMATTING_PATTERN" }) private TestPatterns pattern; @Benchmark public void testIcuMF(Blackhole bh) { String formatted = com.ibm.icu.text.MessageFormat.format(pattern.getPattern(), pattern.getArgs()); bh.consume(formatted); } @Benchmark public void testJdkMF(Blackhole bh) { String formatted = java.text.MessageFormat.format(pattern.getPattern(), pattern.getArgs()); bh.consume(formatted); } // TODO add blackhole-appender private static final Logger LOGGER = Logger.getRootLogger(); @Benchmark public void testLogMF(Blackhole bh) { org.apache.log4j.LogMF.error(LOGGER, pattern.getPattern(), pattern.getArgs()); } @Benchmark public void testSF(Blackhole bh) { String formatted = String.format(pattern.getFormat(), pattern.getArgs()); bh.consume(formatted); } @Benchmark public void testKirai(Blackhole bh) { Kirai kirai = com.github.pwittchen.kirai.library.Kirai.from(pattern.getNamedCurly()); Object[] args = pattern.getArgs(); if (args != null) for (int j = 0; j < args.length; j++) { kirai.put("arg" + j, args[j]); } final CharSequence formatted = kirai.format(); bh.consume(formatted); } @Benchmark public void testST(Blackhole bh) { ST st = new org.stringtemplate.v4.ST(pattern.getNamedTagged()); Object[] args = pattern.getArgs(); if (args != null) for (int j = 0; j < args.length; j++) { st.add("arg" + j, args[j]); } String formatted = st.render(); bh.consume(formatted); } }
true
dc79610383360966dc0aba868114df23021b2299
Java
dmitriykotov333/SmartNotes
/sql/src/main/java/com/kotov/smartnotes/adapter/draggable/AdapterCheck.java
UTF-8
9,140
1.9375
2
[]
no_license
package com.kotov.smartnotes.adapter.draggable; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.kotov.smartnotes.R; import com.kotov.smartnotes.activity.editor.Presenter; import com.kotov.smartnotes.adapter.OnClickListener; import com.kotov.smartnotes.database.Action; import com.kotov.smartnotes.database.CheckAction; import com.kotov.smartnotes.model.Check; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import androidx.core.view.MotionEventCompat; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.RecyclerView; public class AdapterCheck extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements DragItemTouchHelper.MoveHelperAdapter { public Context ctx; public List<Check> items = new ArrayList(); public OnStartDragListener mDragStartListener = null; public OnItemClickListener mOnItemClickListener; private OnClickListener<Check> onClickListener; private String date; public void setOnClickListener(OnClickListener<Check> onClickListener) { this.onClickListener = onClickListener; } public interface OnItemClickListener { void onItemClick(View view, Check social, int i); } public interface OnStartDragListener { void onStartDrag(RecyclerView.ViewHolder viewHolder); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } public AdapterCheck(Context context, List<Check> items, String date) { this.items = items; this.ctx = context; this.date = date; checkAction = new CheckAction(ctx); action = new Action(ctx); } public void setDragListener(OnStartDragListener onStartDragListener) { this.mDragStartListener = onStartDragListener; } public class OriginalViewHolder extends RecyclerView.ViewHolder implements DragItemTouchHelper.TouchViewHolder { public CheckBox checkBox; public ImageView bt_move; public View lyt_parent; public com.google.android.material.textfield.TextInputEditText name; public OriginalViewHolder(View view) { super(view); this.bt_move = (ImageView) view.findViewById(R.id.remove_check); this.name = (com.google.android.material.textfield.TextInputEditText) view.findViewById(R.id.check_title); this.checkBox = (CheckBox) view.findViewById(R.id.checkbox); this.lyt_parent = view.findViewById(R.id.lyt_parent); } public void onItemSelected() { this.itemView.setBackgroundColor(ctx.getResources().getColor(R.color.grey)); } public void onItemClear() { this.itemView.setBackgroundColor(0); } } public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { return new OriginalViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.check_item, viewGroup, false)); } @SuppressLint("ClickableViewAccessibility") public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int i) { if (viewHolder instanceof OriginalViewHolder) { OriginalViewHolder originalViewHolder = (OriginalViewHolder) viewHolder; Check social = items.get(i); //originalViewHolder.checkBox.setChecked(social.isCheck()); boolean rst = social.isCheck() != -1; originalViewHolder.checkBox.setChecked(rst); originalViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int rs; if (isChecked) { rs = 1; } else { rs = -1; } checkAction.updateCheck(rs, items, i); // сохраняем изменяемое значение в массив /* Realm.getDefaultInstance().executeTransaction(realm -> { items.get(i).setCheck(isChecked); realm.insertOrUpdate(items); });*/ } }); if (rst) { originalViewHolder.name.requestFocus(); } originalViewHolder.name.setText(social.getTitle()); originalViewHolder.name.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { originalViewHolder.bt_move.setImageResource(R.drawable.ic_delete); originalViewHolder.bt_move.setOnClickListener(view -> { if (onClickListener != null) { onClickListener.onItemClick(view, social, i); } }); } else { originalViewHolder.bt_move.setImageResource(R.drawable.ic_view_headline_black_24dp); } } }); originalViewHolder.name.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int is, int i1s, int i2s) { /*Realm.getDefaultInstance().executeTransaction(realm -> { items.get(i).setTitle(originalViewHolder.name.getText().toString()); items.get(i).setCheck(originalViewHolder.checkBox.isChecked()); realm.insertOrUpdate(items); });*/ } @Override public void afterTextChanged(Editable editable) { checkAction.updateCheckTitle(Objects.requireNonNull(originalViewHolder.name.getText()).toString(), items, i); } }); originalViewHolder.lyt_parent.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(view, items.get(i), i); } } }); originalViewHolder.lyt_parent.setOnTouchListener((view, motionEvent) -> { if (MotionEventCompat.getActionMasked(motionEvent) != 0 || mDragStartListener == null) { return false; } mDragStartListener.onStartDrag(viewHolder); return false; }); /* originalViewHolder.bt_move.setOnTouchListener((view, motionEvent) -> { if (MotionEventCompat.getActionMasked(motionEvent) != 0 || mDragStartListener == null) { return false; } mDragStartListener.onStartDrag(viewHolder); return false; });*/ } } public int getItemCount() { return this.items.size(); } public List<Check> get() { return items; } boolean rst = false; private CheckAction checkAction; public void addItem(Check dataObj, int index, String date) { items.add(dataObj); checkAction.addCheck(items); notifyItemInserted(index); rst = true; } public void deleteItem(int index) { /*Realm.getDefaultInstance().executeTransaction(realm -> { items.remove(index); realm.insertOrUpdate(items); });*/ checkAction.deleteCheckNotesId(items); items.remove(index); checkAction.addOneCheck(items, date, action); // checkAction.deleteCheck(items.get(index).getUpdate_date()); notifyItemRemoved(index); notifyItemRangeChanged(index, getItemCount()); } Action action; @Override public boolean onItemMove(int fromPosition, int toPosition) { checkAction.deleteCheckNotesId(items); Collections.swap(items, fromPosition, toPosition); checkAction.addOneCheck(items, date, action); notifyItemMoved(fromPosition, toPosition); return true; } }
true
83b95c8147f165f7e6f765dd4c9efd60b850d86b
Java
dzhao14/CS2510_Maze
/src/Examples.java
UTF-8
31,009
2.671875
3
[]
no_license
//CS2510 Fall 2016 //Assignment 11 //Zhao, David //dzhao //Carr, Kenneth "Theo" //kcarr // TO GENERATE MAZE: uncomment big-bang at the bottom of the Examples class import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import tester.*; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import javalib.impworld.*; import java.awt.Color; import javalib.worldimages.*; public class Examples { Node n0; Node n1; Node n2; Node n3; Node n4; Edge e0; Edge e1; Edge e2; ArrayList<Edge> el0; ArrayList<Edge> el1; MazeWorld mw; HashMap<Node, Node> hash1; HashMap<Node, Node> hash2; Collection<Node> c; WorldScene bg; Player p; // initialize objects void init() { this.n0 = new Node(0, 0); this.n1 = new Node(0, 1); this.n2 = new Node(0, 2); this.n3 = new Node(MazeWorld.WIDTH - 1, MazeWorld.HEIGHT - 1); this.n4 = new Node(1, 2); this.e0 = new Edge(n0, n1, 0); this.e1 = new Edge(n1, n2, 1); this.e2 = new Edge(n2, n4, 5); this.el0 = new ArrayList<Edge>(); this.el0.add(this.e0); this.el0.add(this.e1); this.el1 = new ArrayList<Edge>(); this.el1.add(this.e1); this.el1.add(this.e0); this.mw = new MazeWorld(false); this.hash1 = new HashMap<Node, Node>(); this.hash1.put(this.n0, this.n0); this.hash1.put(this.n1, this.n1); this.hash1.put(this.n2, this.n2); this.hash2 = new HashMap<Node, Node>(); this.hash2.put(this.n0, this.n0); this.hash2.put(this.n0, this.n1); this.hash2.put(this.n0, this.n2); this.c = new ArrayList<Node>(); this.bg = new WorldScene(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE); this.p = new Player(this.n0); } // test createNodeTable void testCreateNodeTable(Tester t) { this.init(); ArrayList<ArrayList<Node>> table = this.mw.createNodeTable(); for (int x = 0; x < MazeWorld.WIDTH; x++) { for (int y = 0; y < MazeWorld.HEIGHT; y++) { t.checkExpect(table.get(x).get(y).x, x); t.checkExpect(table.get(x).get(y).y, y); } } } // test linkNodeTable void testLinkNodeTable(Tester t) { this.init(); ArrayList<ArrayList<Node>> table = this.mw.linkNodeTable(this.mw.createNodeTable()); for (int x = 1; x < MazeWorld.WIDTH - 1; x++) { for (int y = 1; y < MazeWorld.HEIGHT - 1; y++) { t.checkExpect(table.get(x).get(y).edges.size(), 2); } } } // test sortEdges and its helper void testSortEdges(Tester t) { this.init(); ArrayList<Edge> l = this.mw.sortEdges(this.mw.linkNodeTable(this.mw.createNodeTable())); for (int i = 1; i < l.size(); i++) { t.checkExpect(l.get(i - 1).weight <= l.get(i).weight, true); } } // test createMinSpanningTree and its helpers void testCreateMinSpanningTree(Tester t) { this.init(); ArrayList<ArrayList<Node>> table = this.mw.linkNodeTable(this.mw.createNodeTable()); ArrayList<Edge> sortedEdges = this.mw.sortEdges(table); ArrayList<Edge> out = this.mw.createMinSpanningTree(sortedEdges, table); t.checkExpect(out.size(), MazeWorld.WIDTH * MazeWorld.HEIGHT - 1); } // test createMaze void testCreateMaze(Tester t) { this.init(); t.checkExpect(this.mw.board, null); this.mw.createMaze(); t.checkExpect(this.mw.board.size(), MazeWorld.HEIGHT * MazeWorld.WIDTH); } // test union void testUnion(Tester t) { this.init(); this.mw.createMaze(); ArrayList<Node> ln = new ArrayList<Node>(); for (Node c : this.hash1.values()) { ln.add(c); } t.checkExpect(ln.contains(this.n0), true); t.checkExpect(ln.contains(this.n1), true); t.checkExpect(ln.contains(this.n2), true); this.init(); this.mw.union(this.hash1, this.e0); ln = new ArrayList<Node>(); for (Node c : this.hash1.values()) { ln.add(c); } t.checkExpect(ln.contains(this.n1), false); this.mw.union(this.hash1, this.e1); ln = new ArrayList<Node>(); for (Node c : this.hash1.values()) { ln.add(c); } t.checkExpect(ln.contains(this.n2), false); } // more examples Node node00;; Node node10; Node node01; Node node11; Node node20; Node node21; Node node22; Node node12; Node node02; ArrayList<Node> tempBoard; // another initializer void initNodes() { this.node00 = new Node(0, 0); this.node10 = new Node(1, 0); this.node01 = new Node(0, 1); this.node11 = new Node(1, 1); this.node20 = new Node(2, 0); this.node21 = new Node(2, 1); this.node22 = new Node(2, 2); this.node12 = new Node(1, 2); this.node02 = new Node(0, 2); } // test determineHead void testDetermineHead(Tester t) { this.initNodes(); MazeWorld world1 = new MazeWorld(false); HashMap<Node, Node> hasher = new HashMap<Node, Node>(); hasher.put(this.node00, this.node00); hasher.put(this.node10, this.node11); hasher.put(this.node01, this.node11); hasher.put(this.node11, this.node11); t.checkExpect(world1.determineHead(hasher, node11), node11); t.checkExpect(world1.determineHead(hasher, node01), node11); t.checkExpect(world1.determineHead(hasher, node00), node00); t.checkExpect(world1.determineHead(hasher, node10), node11); } // test updateNodeEdges void testUpdateNodeEdges(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.createNodeTable(); ArrayList<ArrayList<Node>> table1 = world.linkNodeTable(table); ArrayList<Edge> l = new ArrayList<Edge>(); for (int x = 0; x < MazeWorld.WIDTH; x++) { for (int y = 0; y < MazeWorld.HEIGHT; y++) { for (Edge e : table1.get(x).get(y).edges) { l.add(e); } } } ArrayList<Node> out = world.updateNodeEdges(table, l); t.checkExpect(out.get(0).edges.size(), 2); t.checkExpect(out.get(1).edges.size(), 3); t.checkExpect(out.get(MazeWorld.HEIGHT * 2 + 1).edges.size(), 4); } // test table2List void testTable2List(Tester t) { this.init(); ArrayList<ArrayList<Node>> table = new ArrayList<ArrayList<Node>>(); for (int x = 0; x < MazeWorld.WIDTH; x++) { table.add(new ArrayList<Node>()); for (int y = 0; y < MazeWorld.HEIGHT; y++) { table.get(x).add(new Node(x, y)); } } t.checkExpect(table.size(), MazeWorld.WIDTH); t.checkExpect(table.get(1).size(), MazeWorld.HEIGHT); t.checkExpect(this.mw.table2List(table).size(), MazeWorld.WIDTH * MazeWorld.HEIGHT); } // test createPlayer void testCreatePlayer(Tester t) { this.init(); MazeWorld world1 = new MazeWorld(false); t.checkExpect(world1.player, null); world1.board = new ArrayList<Node>(); world1.board.add(n0); world1.createPlayer(); t.checkExpect(world1.player, new Player(n0)); } // test movePlayerDown void testMovePlayerDown(Tester t) { MazeWorld world1 = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world1.createNodeTable(); ArrayList<Node> list = world1.table2List(table); world1.board = list; world1.player = new Player(world1.board.get(0)); world1.player.x = 0; world1.player.y = 0; t.checkExpect(world1.player.on, world1.board.get(0)); t.checkExpect(world1.player.y, 0); t.checkExpect(world1.board.get(1).seen, false); t.checkExpect(world1.seen.contains(world1.board.get(1)), false); world1.movePlayerDown(); t.checkExpect(world1.player.on, world1.board.get(1)); t.checkExpect(world1.player.y, 1); t.checkExpect(world1.board.get(1).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(1)), true); world1.wl.add(world1.board.get(3)); world1.movePlayerDown(); t.checkExpect(world1.player.on, world1.board.get(1)); t.checkExpect(world1.player.y, 1); t.checkExpect(world1.board.get(1).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(1)), true); } // test movePlayerUp void testMovePlayerUp(Tester t) { MazeWorld world1 = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world1.createNodeTable(); ArrayList<Node> list = world1.table2List(table); world1.board = list; world1.player = new Player(world1.board.get(1)); world1.player.x = 0; world1.player.y = 1; t.checkExpect(world1.player.on, world1.board.get(1)); t.checkExpect(world1.player.y, 1); t.checkExpect(world1.board.get(0).seen, false); t.checkExpect(world1.seen.contains(world1.board.get(0)), false); world1.movePlayerUp(); t.checkExpect(world1.player.on, world1.board.get(0)); t.checkExpect(world1.player.y, 0); t.checkExpect(world1.board.get(0).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(0)), true); world1.wl.add(world1.board.get(3)); world1.movePlayerUp(); t.checkExpect(world1.player.on, world1.board.get(0)); t.checkExpect(world1.player.y, 0); t.checkExpect(world1.board.get(0).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(0)), true); } // test movePlayerLeft void testMovePlayerLeft(Tester t) { MazeWorld world1 = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world1.createNodeTable(); ArrayList<Node> list = world1.table2List(table); world1.board = list; world1.player = new Player(world1.board.get(MazeWorld.HEIGHT)); world1.player.x = 1; world1.player.y = 0; t.checkExpect(world1.player.on, world1.board.get(MazeWorld.HEIGHT)); t.checkExpect(world1.player.x, 1); t.checkExpect(world1.board.get(0).seen, false); t.checkExpect(world1.seen.contains(world1.board.get(0)), false); world1.movePlayerLeft(); t.checkExpect(world1.player.on, world1.board.get(0)); t.checkExpect(world1.player.x, 0); t.checkExpect(world1.board.get(0).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(0)), true); world1.wl.add(world1.board.get(3)); world1.movePlayerLeft(); t.checkExpect(world1.player.on, world1.board.get(0)); t.checkExpect(world1.player.x, 0); t.checkExpect(world1.board.get(0).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(0)), true); } // test movePlayerRight void testMovePlayerRight(Tester t) { MazeWorld world1 = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world1.createNodeTable(); ArrayList<Node> list = world1.table2List(table); world1.board = list; world1.player = new Player(world1.board.get(0)); world1.player.x = 0; world1.player.y = 0; t.checkExpect(world1.player.on, world1.board.get(0)); t.checkExpect(world1.player.x, 0); t.checkExpect(world1.board.get(MazeWorld.HEIGHT).seen, false); t.checkExpect(world1.seen.contains(world1.board.get(MazeWorld.HEIGHT)), false); world1.movePlayerRight(); t.checkExpect(world1.player.on, world1.board.get(MazeWorld.HEIGHT)); t.checkExpect(world1.player.x, 1); t.checkExpect(world1.board.get(MazeWorld.HEIGHT).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(MazeWorld.HEIGHT)), true); world1.wl.add(world1.board.get(3)); world1.movePlayerRight(); t.checkExpect(world1.player.on, world1.board.get(MazeWorld.HEIGHT)); t.checkExpect(world1.player.x, 1); t.checkExpect(world1.board.get(MazeWorld.HEIGHT).seen, true); t.checkExpect(world1.seen.contains(world1.board.get(MazeWorld.HEIGHT)), true); } // test slowGraphSearch void testSlowGraphSearch(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.createNodeTable(); ArrayList<Node> list = world.table2List(table); world.board = list; t.checkExpect(world.wl.contains(world.board.get(0)), false); world.slowGraphSearch(); t.checkExpect(world.wl.contains(world.board.get(0)), true); } // test slowGraphSearchHelp void testSlowGraphSearchHelp(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.createNodeTable(); ArrayList<Node> list = world.table2List(table); world.board = list; t.checkExpect(world.slowGraphSearchHelp(), false); world.slowGraphSearch(); world.wl.addFirst(new Node(MazeWorld.WIDTH - 1, MazeWorld.HEIGHT - 1)); t.checkExpect(world.slowGraphSearchHelp(), true); } // GraphTraverseType Examples GraphTraverseType<Node> bfsNode = new BFS<Node>(); GraphTraverseType<Node> dfsNode = new DFS<Node>(); // test determineSolution void testDetermineSolution(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.linkNodeTable(world.createNodeTable()); ArrayList<Edge> sortedEdges = world.sortEdges(table); ArrayList<Edge> spanningTreeEdges = world.createMinSpanningTree(sortedEdges, table); world.board = world.updateNodeEdges(table, spanningTreeEdges); ArrayList<Node> tempSeen = new ArrayList<Node>(); tempSeen.add(world.board.get(0)); world.seen = tempSeen; t.checkExpect(world.rightMoves, 0); t.checkExpect(world.wrongMoves, 0); world.determineSolution(); t.checkExpect(world.rightMoves, 1); t.checkExpect(world.wrongMoves, 0); tempSeen.add(this.n0); world.rightMoves = 0; world.wrongMoves = 0; t.checkExpect(world.rightMoves, 0); t.checkExpect(world.wrongMoves, 0); world.determineSolution(); t.checkExpect(world.rightMoves, 1); t.checkExpect(world.wrongMoves, 1); } // test fastGraphSearch void testFastGraphSearch(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.linkNodeTable(world.createNodeTable()); ArrayList<Edge> sortedEdges = world.sortEdges(table); ArrayList<Edge> spanningTreeEdges = world.createMinSpanningTree(sortedEdges, table); world.board = world.updateNodeEdges(table, spanningTreeEdges); ArrayList<Node> tempSeen = new ArrayList<Node>(); tempSeen.add(world.board.get(0)); t.checkExpect(world.fastGraphSearch(this.n0, new ArrayList<Node>(), this.bfsNode), false); t.checkExpect( world.fastGraphSearch(world.board.get(0), new ArrayList<Node>(), this.bfsNode), true); t.checkExpect(world.fastGraphSearch(this.n0, tempSeen, this.bfsNode), false); t.checkExpect(world.fastGraphSearch(world.board.get(0), tempSeen, this.bfsNode), false); } // test toggleColors void testToggleColors(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.createNodeTable(); ArrayList<Node> list = world.table2List(table); world.board = list; t.checkExpect(world.board.get(1).isHidden, false); world.toggleColors(); t.checkExpect(world.board.get(1).isHidden, true); } // test toggleScore void testToggleScore(Tester t) { MazeWorld world = new MazeWorld(false); t.checkExpect(world.showScore, false); world.toggleScore(); t.checkExpect(world.showScore, true); } // test drawEnd void testDrawEnd(Tester t) { MazeWorld world = new MazeWorld(false); world.rightMoves = 29; world.wrongMoves = 15; WorldScene testScene = new WorldScene(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE); WorldScene scene = new WorldScene(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE); scene.placeImageXY( new RectangleImage(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE, OutlineMode.SOLID, Color.WHITE), MazeWorld.WIDTH * Node.CELL_SIZE / 2, MazeWorld.HEIGHT * Node.CELL_SIZE / 2); scene.placeImageXY( new TextImage("Nice job!", MazeWorld.HEIGHT * Node.CELL_SIZE / 8, Color.RED), MazeWorld.WIDTH * Node.CELL_SIZE / 2, MazeWorld.HEIGHT * Node.CELL_SIZE / 8); scene.placeImageXY( new TextImage("Took " + (world.rightMoves + world.wrongMoves) + " moves", MazeWorld.HEIGHT * Node.CELL_SIZE / 8, Color.RED), MazeWorld.WIDTH * Node.CELL_SIZE / 2, MazeWorld.HEIGHT * Node.CELL_SIZE / 2); scene.placeImageXY( new TextImage(world.wrongMoves + " Wrong moves", MazeWorld.HEIGHT * Node.CELL_SIZE / 8, Color.RED), MazeWorld.WIDTH * Node.CELL_SIZE / 2, MazeWorld.HEIGHT * Node.CELL_SIZE / 4 * 3); world.drawEnd(testScene); t.checkExpect(testScene, testScene); } // test onTick void testOnTick(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.createNodeTable(); ArrayList<Node> list = world.table2List(table); world.board = list; world.wl.add(world.board.get(0)); t.checkExpect(world.wl.size(), 1); t.checkExpect(world.slowGraphSearchHelp(), false); world.onTick(); t.checkExpect(world.wl.size(), 0); world.wl.add(world.board.get(1)); t.checkExpect(world.gameStop, false); t.checkExpect(world.showScore, false); t.checkExpect(world.wl.contains(world.board.get(0)), false); world.board.get(MazeWorld.WIDTH * MazeWorld.HEIGHT - 1).seen = true; world.onTick(); t.checkExpect(world.gameStop, true); t.checkExpect(world.showScore, true); t.checkExpect(world.wl, new ArrayDeque<Node>()); } // test onKeyEvent void testOnKeyEvent(Tester t) { MazeWorld world = new MazeWorld(false); ArrayList<ArrayList<Node>> table = world.linkNodeTable(world.createNodeTable()); ArrayList<Edge> edges = new ArrayList<Edge>(); for (int x = 0; x < MazeWorld.WIDTH; x++) { for (int y = 0; y < MazeWorld.HEIGHT; y++) { for (Edge e : table.get(x).get(y).edges) { edges.add(e); } } } ArrayList<Node> tableLinked = world.updateNodeEdges(table, edges); world.board = tableLinked; world.player = new Player(world.board.get(MazeWorld.HEIGHT)); world.player.x = 1; world.onKeyEvent("q"); t.checkExpect(world.player.x, 1); world.onKeyEvent("left"); t.checkExpect(world.player.x, 0); world.player = new Player(world.board.get(0)); world.player.y = 0; world.onKeyEvent("q"); t.checkExpect(world.player.y, 0); world.onKeyEvent("down"); t.checkExpect(world.player.y, 1); world.player = new Player(world.board.get(1)); world.player.y = 1; world.onKeyEvent("q"); t.checkExpect(world.player.y, 1); world.onKeyEvent("up"); t.checkExpect(world.player.y, 0); world.player = new Player(world.board.get(0)); world.player.x = 0; world.onKeyEvent("q"); t.checkExpect(world.player.x, 0); world.onKeyEvent("right"); t.checkExpect(world.player.x, 1); t.checkExpect(world.func, this.dfsNode); world.onKeyEvent("q"); t.checkExpect(world.func, this.dfsNode); world.onKeyEvent("b"); t.checkExpect(world.func, this.bfsNode); world.onKeyEvent("q"); t.checkExpect(world.func, this.bfsNode); world.onKeyEvent("d"); t.checkExpect(world.func, this.dfsNode); t.checkExpect(world.board.get(1).isHidden, false); world.onKeyEvent("q"); t.checkExpect(world.board.get(1).isHidden, false); world.onKeyEvent("h"); t.checkExpect(world.board.get(1).isHidden, true); t.checkExpect(world.showScore, false); world.onKeyEvent("q"); t.checkExpect(world.showScore, false); world.onKeyEvent("j"); t.checkExpect(world.showScore, true); } // Deque examples to use for testing below Deque<Integer> deque; Deque<Node> dequeNode; // initializer for add/remove testing void initDeque() { this.deque = new ArrayDeque<Integer>(); this.dequeNode = new ArrayDeque<Node>(); deque.add(1); deque.addLast(2); deque.addLast(3); } // GraphTraverseType examples BFS<Integer> bfs = new BFS<Integer>(); DFS<Integer> dfs = new DFS<Integer>(); // test add/remove (for BFS) void testAddRemoveBFS(Tester t) { this.initDeque(); t.checkExpect(this.deque.getFirst(), 1); t.checkExpect(this.deque.getLast(), 3); this.bfs.add(this.deque, 9); t.checkExpect(this.deque.getFirst(), 9); t.checkExpect(this.deque.getLast(), 3); t.checkExpect(this.bfs.remove(this.deque), 3); t.checkExpect(this.deque.getFirst(), 9); t.checkExpect(this.deque.getLast(), 2); } // test add/remove (for DFS) void testAddRemoveDFS(Tester t) { this.initDeque(); t.checkExpect(this.deque.getFirst(), 1); t.checkExpect(this.deque.getLast(), 3); this.dfs.add(this.deque, 9); t.checkExpect(this.deque.getFirst(), 9); t.checkExpect(this.deque.getLast(), 3); t.checkExpect(this.dfs.remove(this.deque), 9); t.checkExpect(this.deque.getFirst(), 1); t.checkExpect(this.deque.getLast(), 3); } // test drawPlayer void testDrawPlayer(Tester t) { this.init(); WorldScene background = new WorldScene(Node.CELL_SIZE * 2, Node.CELL_SIZE * 2); WorldScene image = new WorldScene(Node.CELL_SIZE * 2, Node.CELL_SIZE * 2); image.placeImageXY(new CircleImage(Node.CELL_SIZE * 3 / 10, OutlineMode.SOLID, Color.RED), this.p.x * Node.CELL_SIZE + Node.CELL_SIZE / 2, this.p.y * Node.CELL_SIZE + Node.CELL_SIZE / 2); t.checkExpect(background, new WorldScene(Node.CELL_SIZE * 2, Node.CELL_SIZE * 2)); p.drawPlayer(background); t.checkExpect(background, image); } // test hasPlayerWon void testHasPlayerWon(Tester t) { this.init(); t.checkExpect(this.p.hasPlayerWon(), false); p.x = MazeWorld.WIDTH - 1; p.y = MazeWorld.HEIGHT - 1; t.checkExpect(this.p.hasPlayerWon(), true); } //////////////// HeapSort Method testing /////////////////// // another initializer ArrayList<Integer> l; HeapSort<Integer> hs = new HeapSort<Integer>(); Comparator<Integer> intComp = new CompareInt(); Comparator<Edge> edgeComp = new CompareEdges(); void init2() { this.l = new ArrayList<Integer>(); this.hs = new HeapSort<Integer>(); } // test heapSort void testHeapSort(Tester t) { this.init2(); this.l.add(7); this.l.add(8); this.l.add(6); this.l.add(4); this.l.add(9); this.l.add(3); t.checkExpect(l.get(0), 7); t.checkExpect(l.get(1), 8); t.checkExpect(l.get(4), 9); t.checkExpect(hs.heapSort(l, this.intComp).get(0), 3); t.checkExpect(hs.heapSort(l, this.intComp).get(1), 4); t.checkExpect(hs.heapSort(l, this.intComp).get(2), 6); t.checkExpect(hs.heapSort(l, this.intComp).get(3), 7); t.checkExpect(hs.heapSort(l, this.intComp).get(4), 8); t.checkExpect(hs.heapSort(l, this.intComp).get(5), 9); } // test buildHeap void testBuildHeap(Tester t) { this.init2(); this.l.add(7); this.l.add(8); this.l.add(6); this.l.add(4); this.l.add(9); this.l.add(3); t.checkExpect(l.get(0), 7); t.checkExpect(l.get(1), 8); t.checkExpect(l.get(4), 9); hs.buildHeap(l, this.intComp); t.checkExpect(l.get(0), 9); t.checkExpect(l.get(1), 8); t.checkExpect(l.get(2), 6); t.checkExpect(l.get(3), 4); t.checkExpect(l.get(4), 7); t.checkExpect(l.get(5), 3); } // test swap void testSwap(Tester t) { this.init2(); for (int i = 0; i < 6; i++) { l.add(i); } t.checkExpect(l.get(2), 2); t.checkExpect(l.get(5), 5); this.hs.swap(l, 2, 5); t.checkExpect(l.get(2), 5); t.checkExpect(l.get(5), 2); } // test downHeap void testDownHeap(Tester t) { this.init2(); this.l.add(7); this.l.add(8); this.l.add(6); this.l.add(4); this.l.add(9); this.l.add(3); t.checkExpect(l.get(0), 7); t.checkExpect(l.get(1), 8); t.checkExpect(l.get(4), 9); this.hs.downHeap(0, l, this.intComp, l.size()); t.checkExpect(l.get(0), 8); t.checkExpect(l.get(1), 9); t.checkExpect(l.get(2), 6); t.checkExpect(l.get(3), 4); t.checkExpect(l.get(4), 7); t.checkExpect(l.get(5), 3); } // test heapOrder void testOrderHeap(Tester t) { this.init(); this.init2(); this.l.add(7); this.l.add(8); this.l.add(6); this.l.add(4); this.l.add(9); this.l.add(3); hs.buildHeap(l, this.intComp); t.checkExpect(l.get(0), 9); t.checkExpect(l.get(1), 8); t.checkExpect(l.get(2), 6); t.checkExpect(l.get(3), 4); t.checkExpect(l.get(4), 7); t.checkExpect(l.get(5), 3); hs.heapOrder(l, this.intComp); t.checkExpect(l.get(0), 3); t.checkExpect(l.get(1), 4); t.checkExpect(l.get(2), 6); t.checkExpect(l.get(3), 7); t.checkExpect(l.get(4), 8); t.checkExpect(l.get(5), 9); } // test compare (in Comparator interface) void testCompare(Tester t) { this.init(); t.checkExpect(this.intComp.compare(5, 6), -1); t.checkExpect(this.intComp.compare(6, 6), 0); t.checkExpect(this.intComp.compare(7, 6), 1); t.checkExpect(this.edgeComp.compare(e1, e0), 1); t.checkExpect(this.edgeComp.compare(e0, e1), -1); t.checkExpect(this.edgeComp.compare(e0, e0), 0); } ////////// More MazeWorld testing /////////// // testing makeScene void testMakeScene(Tester t) { this.init(); this.mw.createMaze(); WorldScene bg = new WorldScene(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE); for (Node n : mw.board) { n.drawNode(bg); } t.checkExpect(this.mw.makeScene().height, MazeWorld.HEIGHT * Node.CELL_SIZE); t.checkExpect(this.mw.makeScene().width, MazeWorld.WIDTH * Node.CELL_SIZE); } // test drawNode void testDrawNode(Tester t) { this.init(); WorldScene img = new WorldScene(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE); img.placeImageXY(n0.determineRect(), n0.x * Node.CELL_SIZE + Node.CELL_SIZE / 2, n0.y * Node.CELL_SIZE + Node.CELL_SIZE / 2); img.placeImageXY( new RectangleImage(Node.CELL_SIZE, Node.CELL_SIZE, OutlineMode.OUTLINE, Color.BLACK), n0.x * Node.CELL_SIZE + Node.CELL_SIZE / 2, n0.y * Node.CELL_SIZE + Node.CELL_SIZE / 2); for (Edge e : n0.edges) { img.placeImageXY(n0.determineEdge(e), Node.CELL_SIZE * (e.from.x + e.to.x) / 2 + Node.CELL_SIZE / 2, Node.CELL_SIZE * (e.from.y + e.to.y) / 2 + Node.CELL_SIZE / 2); } t.checkExpect(this.bg, new WorldScene(MazeWorld.WIDTH * Node.CELL_SIZE, MazeWorld.HEIGHT * Node.CELL_SIZE)); this.n0.drawNode(this.bg); t.checkExpect(this.bg, img); } // test determineEdge void testDetermineEdge(Tester t) { t.checkExpect(this.n4.determineEdge(this.e2), new LineImage(new Posn(0, Node.CELL_SIZE - 2), Color.WHITE)); t.checkExpect(this.n0.determineEdge(this.e0), new LineImage(new Posn(Node.CELL_SIZE - 2, 0), Color.WHITE)); } // test determineRect void testDetermineRect(Tester t) { t.checkExpect(this.n0.determineRect(), new RectangleImage(Node.CELL_SIZE, Node.CELL_SIZE, OutlineMode.SOLID, Color.BLUE)); t.checkExpect(this.n1.determineRect(), new RectangleImage(Node.CELL_SIZE, Node.CELL_SIZE, OutlineMode.OUTLINE, Color.BLACK)); t.checkExpect(this.n3.determineRect(), new RectangleImage(Node.CELL_SIZE, Node.CELL_SIZE, OutlineMode.SOLID, Color.GREEN)); } // test Player's canmove functions void testCanMove(Tester t) { this.init(); t.checkExpect(this.p.canMoveDown(), false); t.checkExpect(this.p.canMoveUp(), false); t.checkExpect(this.p.canMoveLeft(), false); t.checkExpect(this.p.canMoveRight(), false); this.n0.edges.add(this.e0); t.checkExpect(this.p.canMoveDown(), true); this.n0.edges.add(new Edge(n0, new Node(0, -1))); t.checkExpect(this.p.canMoveUp(), true); this.n0.edges.add(new Edge(n0, new Node(1, 0))); t.checkExpect(this.p.canMoveRight(), true); this.n0.edges.add(new Edge(n0, new Node(-1, 0))); t.checkExpect(this.p.canMoveLeft(), true); this.n0.edges.remove(0); this.n0.edges.add(this.e0); t.checkExpect(this.p.canMoveDown(), true); } // // Test the game // void testGame(Tester t) { // MazeWorld mz = new MazeWorld(); // mz.bigBang((MazeWorld.WIDTH) * Node.CELL_SIZE, // (MazeWorld.HEIGHT) * Node.CELL_SIZE, .1); // } }
true
b070257070c63cf97a5d80a5b2ac246beea88afc
Java
yoara/web-old-infra
/biz-framework/biz-framework-component-web/src/main/java/org/yoara/framework/component/web/common/security/encrypt/annotation/CheckRSAEncryptAnnotation.java
UTF-8
790
2.6875
3
[]
no_license
package org.yoara.framework.component.web.common.security.encrypt.annotation; import java.lang.annotation.*; /** * 标注校验RSA 公钥,标注了该枚举的类或方法,在拦截器中,方法执行时将校验RSA 公钥 * * <p>处理方式</p> * <ui> * <li>·返回错误提示 {@link CheckRSAEncryptAnnotation.DealType#ALERT}</li> * <li>·返回json信息 {@link CheckRSAEncryptAnnotation.DealType#JSON}</li> * <li>·抛出异常 {@link CheckRSAEncryptAnnotation.DealType#EXCEPTION}</li> * </ui> */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CheckRSAEncryptAnnotation { /** 处理方式 **/ DealType dealType() default DealType.JSON; enum DealType {ALERT,JSON,EXCEPTION} }
true
07eeec359d574f29fb3363a163c492860a3d529d
Java
mananwason/JFP-Assignment
/assign3+bonus/Game.java
UTF-8
987
3.21875
3
[]
no_license
import java.util.Random; import java.util.Scanner; public class Game { Player[] players; public static void main(String args[]) { int i = 0,flag_winner=0; int highest = 0; System.out.println("enter number of players"); Scanner scan = new Scanner(System.in); int p = scan.nextInt(); Player[] players = new Player[20]; for (i = 0; i < p; i++) { players[i] = new Player("player" + (i + 1)); } while (highest < 100) { for (i = 0; i < p; i++) { players[i].rollTwice(); if (players[i].a == 6 || players[i].b == 6) { players[i].f = 1; } if ((players[i].f == 1)) { players[i].score = players[i].score + players[i].a + players[i].b; } System.out.print("\np"+(i+1)+"\t"+players[i].a + "\t" + players[i].b + "\t "+ players[i].score+ "\n"); if (players[i].score > highest) { highest = players[i].score; flag_winner=i; } } }System.out.println("\n\nwinner is p"+( flag_winner +1)); } }
true
84c744720a60b1e2108c231d13fe662ce89ced58
Java
RomanKriukov/cloudchatalpha
/app/src/main/java/com/example/cloudchat/ShowPrivateMessages.java
UTF-8
4,564
2.25
2
[]
no_license
package com.example.cloudchat; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ShowPrivateMessages extends AppCompatActivity { private EditText etSendMsg; private ListView listView; private DatabaseReference mDatabase; private User user; private User contact; private Messages message; private List<Messages> listData; private MessageModelAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_messages); Init(); getIntentMain(); getMsgFromDB(); } private void Init(){ etSendMsg = findViewById(R.id.input_msg); listView = findViewById(R.id.list_item_messages); mDatabase = FirebaseDatabase.getInstance().getReference(); user = new User(); message = new Messages(); listData = new ArrayList<Messages>(); } //============================================================================================================================= public void getMsgFromDB(){ ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if(listData.size() > 0){ listData.clear(); } for (DataSnapshot ds : snapshot.getChildren()){ Messages messages = ds.getValue(Messages.class); assert messages != null; listData.add(messages); } adapter = new MessageModelAdapter(ShowPrivateMessages.this, listData); listView.setAdapter(adapter); listView.setStackFromBottom(true); } @Override public void onCancelled(@NonNull DatabaseError error) { } }; mDatabase.child("PrivateChat").child(user.getId()).child(contact.getId()).addValueEventListener(valueEventListener); } //============================================================================================================================= private void getIntentMain(){ Intent keyUser = getIntent(); if(keyUser != null) { contact = new User(keyUser.getStringExtra("id_user"), keyUser.getStringExtra("user_name") ); user = new User(keyUser.getStringExtra("id_my_user"), keyUser.getStringExtra("my_user_name") ); setTitle(contact.getUserName()); } else { setTitle("Null"); } } //============================================================================================================================= public void sendMessage(View view) { getMsgFromDB(); if(!TextUtils.isEmpty(etSendMsg.getText().toString())) { message.setIdAuthor(user.getId()); message.setAuthor(user.getUserName()); message.setMessage(etSendMsg.getText().toString()); message.setDate(new Date()); etSendMsg.setText(""); String key = mDatabase.push().getKey(); mDatabase.child("PrivateChat").child(user.getId()).child(contact.getId()).child(key).setValue(message); mDatabase.child("PrivateChat").child(contact.getId()).child(user.getId()).child(key).setValue(message); mDatabase.child("AllListChat").child(user.getId()).child(contact.getUserName() + "&" + contact.getId()).setValue(message); mDatabase.child("AllListChat").child(contact.getId()).child(user.getUserName() + "&" + user.getId()).setValue(message); } else { Toast.makeText(ShowPrivateMessages.this, "Введите сообщение", Toast.LENGTH_SHORT).show(); } } }
true
f5866371efede0e67c93ce027c3611b8bf9e14a4
Java
PavelShchetska/hashicorp-vault-plugin
/src/main/java/com/datapipe/jenkins/vault/VaultBuildWrapper.java
UTF-8
11,361
1.570313
2
[ "MIT" ]
permissive
/** * The MIT License (MIT) * * Copyright (c) 2016 Datapipe, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.datapipe.jenkins.vault; import com.bettercloud.vault.Vault; import com.bettercloud.vault.VaultConfig; import com.bettercloud.vault.VaultException; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.AbstractIdCredentialsListBoxModel; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.cloudbees.plugins.credentials.matchers.IdMatcher; import com.datapipe.jenkins.vault.credentials.VaultTokenCredential; import hudson.*; import hudson.console.ConsoleLogFilter; import hudson.model.*; import hudson.remoting.VirtualChannel; import hudson.security.ACL; import hudson.tasks.BuildWrapper; import hudson.util.ListBoxModel; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.tasks.SimpleBuildWrapper; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.jenkinsci.remoting.RoleChecker; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.StaplerRequest; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Sample {@link BuildWrapper}. * * <p> * When the user configures the project and enables this builder, * {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked and a new {@link VaultBuildWrapper} * is created. The created instance is persisted to the project configuration XML by using XStream, * so this allows you to use instance fields (like {@link #vaultUrl}) to remember the configuration. * </p> * * <p> * When a build is performed, the {@link #preCheckout(AbstractBuild, Launcher, BuildListener)} * method will be invoked. * </p> * * @author Peter Tierno {@literal <}ptierno{@literal @}datapipe.com{@literal >} */ public class VaultBuildWrapper extends SimpleBuildWrapper { private String vaultUrl; private String authTokenCredentialId; private String tokenFilePath; private List<VaultSecret> vaultSecrets; private List<String> valuesToMask = new ArrayList<>(); // Possibly add these later // private final int openTimeout; // private final int readTimeout; // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public VaultBuildWrapper(@CheckForNull List<VaultSecret> vaultSecrets) { this.vaultSecrets = vaultSecrets; // Defaults to null to allow using global configuration // I am not sure this is necessary. this.vaultUrl = null; this.authTokenCredentialId = null; } @DataBoundSetter public void setVaultUrl(String vaultUrl) { this.vaultUrl = vaultUrl; } public String getVaultUrl() { return this.vaultUrl; } @DataBoundSetter public void setTokenFilePath(String tokenFilePath) { this.tokenFilePath = tokenFilePath; } public String getTokenFilePath() { return tokenFilePath; } @DataBoundSetter public void setAuthTokenCredentialId(String authTokenCredentialId) { this.authTokenCredentialId = authTokenCredentialId; } public String getAuthTokenCredentialId() { return this.authTokenCredentialId; } public List<VaultSecret> getVaultSecrets() { return this.vaultSecrets; } private String getUrl() { if (this.vaultUrl == null || this.vaultUrl.isEmpty()) { return getDescriptor().getVaultUrl(); } return this.vaultUrl; } private String getToken() { String token; if (!StringUtils.isBlank(authTokenCredentialId) || !StringUtils.isBlank(getDescriptor().getAuthTokenCredentialId())){ return getTokenFromCredentials(); } else if (!StringUtils.isBlank(tokenFilePath) || !StringUtils.isBlank(getDescriptor().getTokenFilePath())){ return readTokenFromFile(); } return null; } private String getTokenFromCredentials() { String id = authTokenCredentialId; if (id == null || id.isEmpty()) { id = getDescriptor().getAuthTokenCredentialId(); } List<VaultTokenCredential> credentials = CredentialsProvider.lookupCredentials(VaultTokenCredential.class, Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList()); VaultTokenCredential credential = CredentialsMatchers.firstOrNull(credentials, new IdMatcher(id)); return credential == null ? null : Secret.toString(credential.getToken()); } private String readTokenFromFile() { String path = tokenFilePath; if (path == null || path.isEmpty()){ path = getDescriptor().getTokenFilePath(); } if (path == null || path.isEmpty()){ return null; } FilePath file = new FilePath(new File(path)); try { return file.act(new FilePath.FileCallable<String>() { @Override public void checkRoles(RoleChecker roleChecker) throws SecurityException { //not needed } @Override public String invoke(File f, VirtualChannel channel) { try { return FileUtils.readFileToString(f); } catch (IOException e) { throw new RuntimeException(e); } }}).trim(); } catch (IOException| InterruptedException e) { throw new RuntimeException(e); } } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Override public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException { // This is where you 'build' the project. PrintStream logger = listener.getLogger(); String url = getUrl(); String token = getToken(); for (VaultSecret vaultSecret : vaultSecrets) { try { VaultConfig vaultConfig = new VaultConfig(url, token).build(); Vault vault = new Vault(vaultConfig); Map<String, String> values = vault.logical().read(vaultSecret.getPath()).getData(); for (VaultSecretValue value : vaultSecret.getSecretValues()) { valuesToMask.add(values.get(value.getVaultKey())); context.env(value.getEnvVar(), values.get(value.getVaultKey())); } } catch (VaultException e) { e.printStackTrace(logger); throw new AbortException(e.getMessage()); } } } @Override public ConsoleLogFilter createLoggerDecorator( @Nonnull final Run<?, ?> build) { return new MaskingConsoleLogFilter(build.getCharset().name(), valuesToMask); } /** * Descriptor for {@link VaultBuildWrapper}. Used as a singleton. The class is marked as public so * that it can be accessed from views. * * <p> * See <tt>src/main/resources/com/datapipe/jenkins/vault/VaultBuildWrapper/*.jelly</tt> for the * actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends Descriptor<BuildWrapper> { /** * To persist global configuration information, simply store it in a field and call save(). * * <p> * If you don't want fields to be persisted, use <tt>transient</tt>. */ private String vaultUrl; private String authTokenCredentialId; private String tokenFilePath; /** * In order to load the persisted global configuration, you have to call load() in the * constructor. */ public DescriptorImpl() { super(VaultBuildWrapper.class); load(); } public boolean isApplicable(AbstractProject<?, ?> item) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable name is used in the configuration screen. */ @Override public String getDisplayName() { return "Vault Plugin"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). Object vaultUrl = formData.getString("vaultUrl"); Object authTokenCredentialId = formData.getString("authTokenCredentialId"); Object tokenFilePath = formData.getString("tokenFilePath"); this.vaultUrl = (String) vaultUrl; this.authTokenCredentialId = (String) authTokenCredentialId; this.tokenFilePath = (String) tokenFilePath; save(); return super.configure(req, formData); } public String getVaultUrl() { return this.vaultUrl; } // Required by external plugins (according to Articfactory plugin) public void setVaultUrl(String vaultUrl) { this.vaultUrl = vaultUrl; } public String getAuthTokenCredentialId() { return authTokenCredentialId; } public void setAuthTokenCredentialId(String authTokenCredentialId) { this.authTokenCredentialId = authTokenCredentialId; } public String getTokenFilePath() { return tokenFilePath; } public void setTokenFilePath(String tokenFilePath) { this.tokenFilePath = tokenFilePath; } public ListBoxModel doFillAuthTokenCredentialIdItems() { final ListBoxModel lbm = new ListBoxModel(); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return lbm; } if (!jenkins.hasPermission(Jenkins.ADMINISTER)) { return lbm; } AbstractIdCredentialsListBoxModel model = new StandardListBoxModel().includeEmptyValue().includeAs(ACL.SYSTEM, jenkins, VaultTokenCredential.class); return model; } } }
true
6ee063531834a8275cbb49b61c332c6f219dce8b
Java
MayureshKushwah/DailyWork
/param sir task2 (march 2nd week)/DataBaseApplication/src/com/cts/training/jdbc/JdbcDynamic.java
UTF-8
2,360
3.015625
3
[]
no_license
package com.cts.training.jdbc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcDynamic { public static void main(String[] args) throws ClassNotFoundException, SQLException, NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //System.out.println("Enter employee id:"); // int id = Integer.parseInt(br.readLine()); //System.out.println("Enter employee name:"); //String name = br.readLine(); // System.out.println("Enter employee address:"); //String address = br.readLine(); //System.out.println("Enter employee age"); //int age = Integer.parseInt(br.readLine()); //System.out.println("Enter employee phone:"); //long phone = Integer.parseInt(br.readLine()); Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/ctspune"; Connection conn = DriverManager.getConnection(url, "root", "root"); //String query = "insert into employee values(?,?,?,?,?)"; //String query = "update employee set name =? where id=?"; //String query = "delete from employee where id=?"; //PreparedStatement ps = conn.prepareStatement(query); //ps.setInt(1, id); //ps.setString(1, name); //ps.setString(3, address); //ps.setInt(4, age); //ps.setLong(5, phone); //int result= ps.executeUpdate(); //if (result>0) // System.out.println("data inseted"); //else // System.out.println("try again"); Statement stmt = conn.createStatement(); String query = "select * from employee"; ResultSet rs = stmt.executeQuery(query); int count=1; while (rs.next()) { int id = rs.getInt(1);//=rs.getInt("id"); ie we can give attribute name String name= rs.getString(2); String address = rs.getString(3); int age = rs.getInt(4); long phone= rs.getInt(5); System.out.println("--------Employee--"+ count+ "---Record--------"+"\n Employee id:"+id+" \n Employee Name : "+name+" \n Emplyee Address:"+address+": \n Employee Age:"+age+": \n Employee ContactNo:"+phone); count++; } } }
true
31aadc3d4a63887674c3c47f78e093a501be255f
Java
UshaBS/Transfer-files1
/UASDemo/src/main/java/com/cap/dev/repositries/ProgramsOfferedRepo.java
UTF-8
614
1.984375
2
[]
no_license
package com.cap.dev.repositries; import javax.transaction.Transactional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import com.cap.dev.entities.ProgramsOffered; public interface ProgramsOfferedRepo extends JpaRepository<ProgramsOffered, String>{ @Transactional @Modifying @Query("UPDATE ProgramsOffered e SET e.description=:description WHERE e.programName=:programName") int updateProgramsOffered(String programName, String description); }
true
943e187cb760df6a180a34faee87091320c2dc8c
Java
fllaryora/CleanArch-Core
/presentation/src/main/java/com/tripl3dev/presentation/base/baseAdapter/GenericAdapter.java
UTF-8
3,255
2.234375
2
[]
no_license
package com.tripl3dev.presentation.base.baseAdapter; import android.content.Context; import android.databinding.ObservableBoolean; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; /** * Created by mahmoud on 6/7/2017. */ public class GenericAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public static int LOAD_MORE_VIEW_TYPE = -1; HolderInterface holderInterface; private View loadMoreView; private int maxItemsPerPage; private ObservableBoolean hasLoadMore = new ObservableBoolean(false); public GenericAdapter() { } public GenericAdapter(HolderInterface holderInterface) { this.holderInterface = holderInterface; } GenericHolder setLoadingMoreView(Context context) { if (loadMoreView == null) { RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 70); RelativeLayout relativeLayout = new RelativeLayout(context); relativeLayout.setLayoutParams(containerParams); RelativeLayout.LayoutParams progressParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); ProgressBar progressBar = new ProgressBar(context); progressBar.setLayoutParams(progressParams); relativeLayout.addView(progressBar); progressParams.addRule(Gravity.CENTER); return new GenericHolder(relativeLayout); } else { return new GenericHolder(loadMoreView); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == LOAD_MORE_VIEW_TYPE) { return setLoadingMoreView(parent.getContext()); } else { return holderInterface.getHolder(parent); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { holderInterface.getViewData(holder, position); } @Override public int getItemCount() { if (hasLoadMore.get()) { return holderInterface.listsize() + 1; } else { return holderInterface.listsize(); } } @Override public int getItemViewType(int position) { if (hasLoadMore.get() && position == getItemCount() - 1) { return LOAD_MORE_VIEW_TYPE; } else { return 1; } } public void stopLoadingMore(boolean stopIt) { if (stopIt) { hasLoadMore.set(false); } else { hasLoadMore.set(true); } } public void hasLoadMore(Boolean hasLoadMore) { this.hasLoadMore.set(hasLoadMore); } public void setMaxItemsPerPage(int maxItemsPerPage) { this.maxItemsPerPage = maxItemsPerPage; } public void setCustomLoadMoreView(View loadMoreView) { this.loadMoreView = loadMoreView; } public void loadingComplete() { hasLoadMore.set(false); notifyItemChanged(getItemCount()); } }
true
ad2deb1a97c577bba5efd6331bc68c9768b526be
Java
ashokvantage/Alteration
/app/src/main/java/com/tdevelopers/alteration/Renew/home/Shirt.java
UTF-8
428
1.828125
2
[]
no_license
package com.tdevelopers.alteration.Renew.home; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** * Created by ADMIN on 28-Dec-17. */ public class Shirt { @SerializedName("men") @Expose public List<ShirtItems> men = new ArrayList<ShirtItems>(); public List<ShirtItems> women = new ArrayList<ShirtItems>(); }
true
44c05c53bb349cc0995623746d9b7327e30c3d51
Java
AsnaNesry/PracticeCoding
/src/interface_examples/InterfaceOne.java
UTF-8
171
2.390625
2
[]
no_license
package interface_examples; public interface InterfaceOne { public abstract void display();//by default it is abstract public void print(); public void show(); }
true
e6a18ce10793e615eee819d253ba6e3309b8716a
Java
onestopweb/java
/java08 收藏/Spring11Favorite/src/cn/biz/FavBiz.java
UTF-8
170
1.6875
2
[]
no_license
package cn.biz; import java.util.List; import cn.entity.Favorite; public interface FavBiz { public void add(Favorite fav); public List<Favorite> search(String type); }
true
9d2f26d5c96618ef43d559c88837aa3d3fb1acaa
Java
Mircea-B/java-exercitii
/src/Interfaces/Patrat.java
UTF-8
318
2.59375
3
[]
no_license
package Interfaces; public class Patrat implements Shape { private int marimelatura; public Patrat(int marimeLatura){ this.marimelatura=marimeLatura; } @Override public double getArea() { return 0; } @Override public double getParameters() { return 0; } }
true
ad2d4767a017168579715224849077d3f4e70d26
Java
sr7172/Hackerrank-java-solutions
/src/JavaIfElse.java
UTF-8
788
4.28125
4
[]
no_license
import java.util.Scanner; /*Java program to test your if-else knowledge. *Given an integer n, perform the following conditional actions: *If n is odd, print Weird *If n is even and in the inclusive range of 2 to 5, print Not Weird *If n is even and in the inclusive range of 6 to 20 , print Weird *If , is even and greater than 20, print Not Weird */ public class JavaIfElse { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if(n % 2 == 1){ System.out.println("Weird"); } else{ if(n >= 6 && n<=20){ System.out.println("Weird"); } else{ System.out.println("Not Weird"); } } } }
true
54bf843975cb070b662c814ee4d6d520f1e267a2
Java
kyrenesjtv/JavaDesignPattern
/SimpleFactoryPattern/src/main/java/me/kyrene/JavaDesignPattern/SimpleFactoryPattern/product/AudiCar.java
UTF-8
537
2.984375
3
[]
no_license
package me.kyrene.JavaDesignPattern.SimpleFactoryPattern.product; import me.kyrene.JavaDesignPattern.SimpleFactoryPattern.annotation.Vehicle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by wanglin on 2018/2/7. */ @Vehicle(type = "Audi") public class AudiCar extends Car { private static Logger LOG = LoggerFactory.getLogger(AudiCar.class); public AudiCar(){ this.name="Audi"; } @Override public void driver() { LOG.info("My name is {}. I'm on my way", name); } }
true
dea82de913b6088edffb34a989ae5b858c366b34
Java
DinethShanG/Log_Analyzer
/src/main/java/com/ConstructionTeam/DatabaseRepository/DB_CRUDOperator.java
UTF-8
318
2.1875
2
[ "MIT" ]
permissive
package com.ConstructionTeam.DatabaseRepository; import com.ConstructionTeam.DataModels.User; import java.sql.SQLException; import java.util.ArrayList; public interface DB_CRUDOperator { ArrayList<User> getUserMailList() throws SQLException, ClassNotFoundException; void addUser(String name,String mail); }
true
5654da6dee62045fb574a6dd785b9395bb28686b
Java
llittlefoxx/tunisiamall
/tunisiamall.server/tunisiamall.server-web/src/main/java/virtual/entities/FriendshipRequest.java
UTF-8
101
1.617188
2
[]
no_license
package virtual.entities; public class FriendshipRequest { public int idSrc; public int idDest; }
true
cc5b38692f7e84f776406cbfd4dc3ac88f9c5b51
Java
Dantol91/D07-Deployment
/Acme Handy Worker/src/test/java/services/EndorsementServiceTest.java
UTF-8
1,505
2.03125
2
[]
no_license
package services; import java.util.Collection; import javax.transaction.Transactional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import utilities.AbstractTest; import domain.Endorsement; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/datasource.xml", "classpath:spring/config/packages.xml" }) @Transactional public class EndorsementServiceTest extends AbstractTest { // Service under test @Autowired private EndorsementService endorsementService; //Tests @Test public void testCreate() { Endorsement endorsement; endorsement = this.endorsementService.create(); Assert.notNull(endorsement); } @Test public void testDelete() { final Endorsement endorsement; endorsement = this.endorsementService.findOne(super.getEntityId("endorsement1")); this.endorsementService.delete(endorsement); } @Test public void testFindAll() { Collection<Endorsement> endorsements; endorsements = this.endorsementService.findAll(); Assert.notEmpty(endorsements); Assert.notNull(endorsements); } @Test public void testFindOne() { Endorsement endorsement; endorsement = this.endorsementService.findOne(super.getEntityId("endorsement1")); Assert.notNull(endorsement); } }
true
c3b94947b9f3e5bff1cda4f2429f660e9c5240e8
Java
HuyaAuto/jsoagger-fx
/jsoagger-jfxcore-engine/src/main/java/io/github/jsoagger/jfxcore/engine/components/input/InputWebView.java
UTF-8
3,504
2.109375
2
[ "Apache-2.0" ]
permissive
/*- * ========================LICENSE_START================================= * JSoagger * %% * Copyright (C) 2019 JSOAGGER * %% * 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. * =========================LICENSE_END================================== */ package io.github.jsoagger.jfxcore.engine.components.input; import io.github.jsoagger.jfxcore.api.IJSoaggerController; import io.github.jsoagger.jfxcore.viewdef.json.xml.model.VLViewComponentXML; import io.github.jsoagger.jfxcore.engine.client.utils.NodeHelper; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker.State; import javafx.scene.Node; import javafx.scene.layout.Region; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; /** * @author Ramilafananana VONJISOA * @mailto yvonjisoa@nexitia.com * @date 2019 */ public class InputWebView extends AbstractInputComponent { private Browser browser = null; /** * Constructor */ public InputWebView() { super(); browser = new Browser(); NodeHelper.setHgrow(browser); } /** * @{inheritedDoc} */ @Override public void buildFrom(IJSoaggerController controller, VLViewComponentXML configuration) { super.buildFrom(controller, configuration); String url = configuration.getPropertyValue("url"); Platform.runLater(() -> { browser.webEngine.load(controller.getClass().getResource(url).toExternalForm()); browser.webEngine.documentProperty().addListener((prop, oldDoc, newDoc) -> { String heightText = browser.webEngine.executeScript( "window.getComputedStyle(document.body, null).getPropertyValue('height')" ) .toString(); System.out.println("heighttext: " + heightText); Double height = Double.parseDouble(heightText.replace("px", "")) + 10 ; // <- Why are this 15.0 required?? //browser.browser.setMinHeight(height); }); }); } /** * @{inheritedDoc} */ @Override public Node getDisplay() { return browser; } /** * @{inheritedDoc} */ @Override public Node getComponent() { return browser; } /** * @author Ramilafananana VONJISOA * @mailto yvonjisoa@nexitia.com * @date 2019 */ public class Browser extends Region { WebView browser; WebEngine webEngine; public Browser() { super(); Platform.runLater(() -> { browser = new WebView(); webEngine = browser.getEngine(); webEngine.setJavaScriptEnabled(true); getChildren().add(browser); // Update the stage title when a new web page title is available webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue<? extends State> ov, State oldState, State newState) { if (newState == State.SUCCEEDED) { } } }); }); } } }
true
807ab72aca29e1b16c3c251fd9f1039a430614f4
Java
Amarvenkat/CRMSystem
/app/src/main/java/com/example/crmsystem/admin/InventoryViewHolder.java
UTF-8
820
1.84375
2
[]
no_license
package com.example.crmsystem.admin; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.crmsystem.R; public class InventoryViewHolder extends RecyclerView.ViewHolder { ImageView invimg; TextView invtitle,invprice,invdec,invquatity; public InventoryViewHolder(@NonNull View itemView) { super(itemView); invimg = (ImageView) itemView.findViewById(R.id.invimg); invtitle = (TextView) itemView.findViewById(R.id.invtitle); invprice = (TextView) itemView.findViewById(R.id.invprice); invdec = (TextView) itemView.findViewById(R.id.invdec); invquatity = (TextView) itemView.findViewById(R.id.invquatity); } }
true
5a0636b0b550f6b1de7851c5f4d4c5f090ccb223
Java
ushakov-sergey/5.Lesson1111
/src/ru/isu/Main.java
UTF-8
898
3.078125
3
[]
no_license
package ru.isu; import java.util.ArrayDeque; import java.util.Deque; import java.util.Scanner; import java.util.StringJoiner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); String[] split = input.split("/"); Deque<String> deque = new ArrayDeque<>(); for (String word : split) { if (word.equals("..")) { if (!deque.isEmpty()) deque.removeFirst(); else deque.addFirst(word); } else if (!word.equals(".")){ deque.addFirst(word); } } StringJoiner joiner = new StringJoiner("/"); while (!deque.isEmpty()) { joiner.add(deque.removeLast()); } scanner.close(); System.out.println(joiner.toString()); } }
true
4d7dd37a85f5134a662743ef146b8c14eedd07f1
Java
Tejender-09/TEJ_local
/Practice/src/inheritance/Son.java
UTF-8
309
2.71875
3
[]
no_license
package inheritance; public class Son extends Father { public void Third() { i=i*6; System.out.println("Third value of i= "+i); } public static void main(String[] args) { Son ob=new Son(); ob.First(); ob.Second(); ob.Third(); } }
true
3189883751d65a571e603dbec019a86d4d6cba23
Java
reverseengineeringer/com.yelp.android
/src/com/yelp/android/appdata/webrequests/br.java
UTF-8
1,362
1.851563
2
[]
no_license
package com.yelp.android.appdata.webrequests; import com.yelp.android.appdata.LocationService.Accuracies; import com.yelp.android.appdata.LocationService.AccuracyUnit; import com.yelp.android.appdata.LocationService.Recentness; import com.yelp.android.serializable.Event; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public class br extends k<Void, Void, a> { public br(String paramString, int paramInt1, int paramInt2, k.b paramb) { super(ApiRequest.RequestType.GET, "/events/section", LocationService.Accuracies.MEDIUM_KM, LocationService.Recentness.MINUTE_15, paramb, LocationService.AccuracyUnit.MILES); a("alias", paramString); a("offset", paramInt1); a("limit", paramInt2); } public a a(JSONObject paramJSONObject) throws YelpException, JSONException { return new a(Event.a(paramJSONObject.getJSONArray("events"), paramJSONObject.getJSONArray("users"), paramJSONObject.getJSONArray("businesses")), paramJSONObject.getInt("total")); } public static class a { public final List<Event> a; public final int b; public a(List<Event> paramList, int paramInt) { a = paramList; b = paramInt; } } } /* Location: * Qualified Name: com.yelp.android.appdata.webrequests.br * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
09b1497d2b6866ff5d940440a814625de2273bf3
Java
Hardik-Parmar/Labspot-Version-1-With-Support-Files
/Labspot_Backend_APIs/src/Java_DAO/lab_DAO/lab_after_login_DAO/Lab_Edit_Test_Details_DAO.java
UTF-8
1,106
2.75
3
[]
no_license
package Java_DAO.lab_DAO.lab_after_login_DAO; import java.sql.Connection; import java.sql.PreparedStatement; import Java_Beans.lab_Beans.lab_after_login_Beans.Lab_Edit_Test_Details_Bean; import database_connection.ConnectionProvider; public class Lab_Edit_Test_Details_DAO { public String lab_Edit_Test_Details(Lab_Edit_Test_Details_Bean bean) { try { Connection connection = ConnectionProvider.getConnection(); String query = "UPDATE test_details set lab_test_name = ?, lab_test_description = ?, lab_test_price = ? WHERE id = ?"; PreparedStatement ps = connection.prepareStatement(query); ps.setString(1, bean.getLab_test_name()); ps.setString(2, bean.getLab_test_description()); ps.setString(3, bean.getLab_test_price()); ps.setString(4, bean.getId()); int temp = ps.executeUpdate(); if(temp == 1) { return "Lab Test Details are Updated Successfully"; } else { return "Lab Test Details are not Updated"; } } catch(Exception e) { e.printStackTrace(); } return "Something went wrong in Lab Edit Test Details"; } }
true
15132816c7413d1d9ca09c6def6cef76644648b8
Java
square/reader-sdk-flutter-plugin
/android/src/main/java/com/squareup/sdk/reader/flutter/ReaderSettingsModule.java
UTF-8
3,391
1.820313
2
[ "Apache-2.0" ]
permissive
/* Copyright 2022 Square Inc. 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.squareup.sdk.reader.flutter; import android.app.Activity; import android.content.Context; import com.squareup.sdk.reader.ReaderSdk; import com.squareup.sdk.reader.core.CallbackReference; import com.squareup.sdk.reader.core.ResultError; import com.squareup.sdk.reader.flutter.internal.ErrorHandlerUtils; import com.squareup.sdk.reader.hardware.ReaderSettingsActivityCallback; import com.squareup.sdk.reader.hardware.ReaderSettingsErrorCode; import io.flutter.plugin.common.MethodChannel.Result; final class ReaderSettingsModule { // Define all the reader settings debug codes and messages below // These error codes and messages **MUST** align with iOS error codes and dart error codes // Search KEEP_IN_SYNC_READER_SETTINGS_ERROR to update all places // flutter plugin debug error codes private static final String FL_READER_SETTINGS_ALREADY_IN_PROGRESS = "fl_reader_settings_already_in_progress"; // flutter plugin debug messages private static final String FL_MESSAGE_READER_SETTINGS_ALREADY_IN_PROGRESS = "A reader settings operation is already in progress. Ensure that the in-progress reader settings is completed before calling startReaderSettingsAsync again."; private volatile CallbackReference readerSettingCallbackRef; private Context currentContext; public ReaderSettingsModule(Context context) { currentContext = context; } public void startReaderSettings(final Result flutterResult) { if (readerSettingCallbackRef != null) { flutterResult.error( ErrorHandlerUtils.USAGE_ERROR, ErrorHandlerUtils.getNativeModuleErrorMessage(FL_READER_SETTINGS_ALREADY_IN_PROGRESS), ErrorHandlerUtils.getDebugErrorObject(FL_READER_SETTINGS_ALREADY_IN_PROGRESS, FL_MESSAGE_READER_SETTINGS_ALREADY_IN_PROGRESS)); return; } ReaderSettingsActivityCallback readerSettingsCallback = new ReaderSettingsActivityCallback() { @Override public void onResult(com.squareup.sdk.reader.core.Result<Void, ResultError<ReaderSettingsErrorCode>> result) { readerSettingCallbackRef.clear(); readerSettingCallbackRef = null; if (result.isError()) { ResultError<ReaderSettingsErrorCode> error = result.getError(); flutterResult.error( ErrorHandlerUtils.getErrorCode(error.getCode()), error.getMessage(), ErrorHandlerUtils.getDebugErrorObject(error.getDebugCode(), error.getDebugMessage())); return; } flutterResult.success(null); } }; readerSettingCallbackRef = ReaderSdk.readerManager() .addReaderSettingsActivityCallback(readerSettingsCallback); ReaderSdk.readerManager().startReaderSettingsActivity(currentContext); } public void setContext(Context context) { this.currentContext = context; } }
true
bfe21d2720ac60ad31e79732d5f77a03eba61884
Java
janusor/Dispatch
/src/main/java/com/ttd/controller/UserInfoController.java
UTF-8
4,287
2.09375
2
[]
no_license
package com.ttd.controller; import java.util.Date; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.ttd.auth.AuthType; import com.ttd.auth.Authentication; import com.ttd.controller.base.BaseController; import com.ttd.domain.UserInfo; import com.ttd.domain.base.Message; import com.ttd.domain.base.Page; import com.ttd.service.UserInfoService; import com.ttd.utils.LongUtils; /** * Controller * @author fwen * @since 2016-04-07 */ @Controller("userInfoController") @RequestMapping(value = "/userInfo", method = {RequestMethod.GET, RequestMethod.POST}) public class UserInfoController extends BaseController { @Resource private UserInfoService userInfoService; /** * @return * @throws Exception */ // @ActionControllerLog(channel="web",action="userInfo",title="打开列表",isSaveRequestData=true) @RequestMapping @Authentication(type = AuthType.OPENAPI, code = "order_confirm") public ModelAndView content() throws Exception { // return toResult("userInfo/userInfo", null); return null; } // @ActionControllerLog(channel="web",action="userInfo",title="获取列表数据",isSaveRequestData=true) @RequestMapping(value = "/list") @Authentication(type = AuthType.OPENAPI, code = "userInfoList") public ModelAndView list(Page<UserInfo> page, UserInfo userInfo) { Message message = Message.success(); // 分页查询 page = userInfoService.selectPage(userInfo, page); // 设置查询结果 /* message.setItems(page.getResult()); message.setPageNum(page.getPageNum()); message.setPageSize(page.getPageSize()); message.setTotalCount(page.getTotalCount());*/ return toJSON(message); } /** * 保存信息 * @return */ // @ActionControllerLog(channel="web",action="userInfo",title="保存数据",isSaveRequestData=true) @RequestMapping(value = "/save") @Authentication(type = AuthType.OPENAPI, code = "userInfoList") public ModelAndView save(UserInfo userInfo) { int result = 0; try { /* if(LongUtils.greatThanZero(userInfo.getUserInfoId())){ userInfo.setUpdator(getLoginUser().getId()); userInfo.setUpdated(new Date()); result = userInfoService.updateByKey(userInfo); } else { userInfo.setCreator(getLoginUser().getId()); userInfo.setUpdator(getLoginUser().getId()); result = userInfoService.insertEntry(userInfo); }*/ } catch (Exception e) { LOGGER.error("新增或修改自动任务出错:{}", e.toString(), e); } return toJSON(result > 0 ? Message.success("保存信息成功!") : Message.failure("保存信息失败,请检查输入或联系管理员!")); } /** * 删除信息 * @return */ // @ActionControllerLog(channel="web",action="userInfo",title="删除数据",isSaveRequestData=true) @RequestMapping(value = "/del-{id}", method = {RequestMethod.DELETE}) @Authentication(type = AuthType.OPENAPI, code = "userInfoList") public ModelAndView del(@PathVariable(value = "id") Long userInfoId) { int result = userInfoService.deleteByKey(userInfoId); return toJSON(result > 0 ? Message.success("删除成功!") : Message.failure("删除失败,请检查输入或联系管理员!")); } /** * 查看信息 * @return */ // @ActionControllerLog(channel="web",action="userInfo",title="查看详情",isSaveRequestData=true) @RequestMapping(value = "/view-{id}") @Authentication(type = AuthType.OPENAPI, code = "userInfoList") public ModelAndView view(@PathVariable(value = "id") Long userInfoId) { LOGGER.info("查看{}信息", userInfoId); if(!LongUtils.greatThanZero(userInfoId)){ return toJSON(Message.failure("ID不合法!")); } UserInfo userInfo = userInfoService.selectEntry(userInfoId); if(userInfo == null){ return toJSON(Message.failure("未查询到相应信息!")); } Message result = Message.success(); // result.setData(userInfo); return toJSON(result); } }
true
74d0fcb6b4e5c0aa0e1a2fc69c42ae11d7b48e0b
Java
DenSev/multimodule-test
/multimodule-enums/src/main/java/com/densev/multimodule/enums/TypeWorker.java
UTF-8
238
1.992188
2
[]
no_license
package com.densev.multimodule.enums; /** * Created by Dzianis_Sevastseyenk on 11/16/2016. */ public class TypeWorker { public static <T extends TypeParent> void work(T param){ System.out.println(param.getName()); } }
true
c4461c3eed589718216864d8337f7726988db713
Java
itboojum/deep-in-springboot
/src/main/java/com/boojum/deepinspringboot/service/UmsAdminCacheService.java
UTF-8
616
1.820313
2
[]
no_license
package com.boojum.deepinspringboot.service; import com.boojum.deepinspringboot.entity.UmsAdmin; import java.util.List; /** * 后台用户缓存操作类 * Created by boojum on 2020/4/6. */ public interface UmsAdminCacheService { /** * 删除后台用户缓存 * @param adminId */ void delAdmin(Long adminId); void delResourceList(Long adminId); void delResourceListByRole(Long roleId); void delResourceListByRoleIds(List<Long> roleIds); void delResourceListByResource(Long resourceId); UmsAdmin getAdmin(String username); void setAdmin(UmsAdmin admin); }
true
7fee3f80f9f1fa499c4480960d5e11663d97c111
Java
brunovicentealves/sistema-venda-jsp-servelet-jstl-mysql
/src/java/Modelo/ClienteDAO.java
UTF-8
5,649
2.53125
3
[]
no_license
/* * 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 Modelo; import Config.Conexao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * * @author bruno.alves */ public class ClienteDAO { Cliente cliente = new Cliente(); Conexao cn = new Conexao(); Connection con; PreparedStatement ps; ResultSet rs; public List listarCliente() { String sql = "select * from cliente"; List<Cliente> lista = new ArrayList<Cliente>(); try { con = cn.conexao(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { Cliente cliente = new Cliente(); cliente.setIdcliente(Integer.parseInt(rs.getString("idcliente"))); cliente.setNome(rs.getString("nome")); cliente.setCpf(rs.getString("cpf")); cliente.setTelefone(rs.getString("telefone")); cliente.setEndereco(rs.getString("endereco")); cliente.setNumero(rs.getString("numero")); cliente.setCidade(rs.getString("cidade")); cliente.setBairro(rs.getString("bairro")); cliente.setCep(Integer.parseInt(rs.getString("cep"))); lista.add(cliente); } } catch (Exception e) { } return lista; } public String cadastrarCliente(Cliente cli) { String sql = "insert into cliente(nome,cpf,telefone,endereco,numero,cidade,bairro,cep) values(?,?,?,?,?,?,?,?)"; String resposta; try { con = cn.conexao(); ps = con.prepareStatement(sql); ps.setString(1, cli.getNome()); ps.setString(2, cli.getCpf()); ps.setString(3, cli.getTelefone()); ps.setString(4, cli.getEndereco()); ps.setString(5, cli.getNumero()); ps.setString(6, cli.getCidade()); ps.setString(7, cli.getBairro()); ps.setString(8, Integer.toString(cli.getCep())); ps.executeUpdate(); resposta = "cadastrado com sucesso"; } catch (Exception e) { resposta = e.getMessage(); } return resposta; } public Cliente listarClienteId(int id) { String sql = "select idcliente,nome,cpf,telefone,endereco,numero,cidade,bairro,cep from cliente where idcliente=" + id; try { con = cn.conexao(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { cliente.setIdcliente(Integer.parseInt(rs.getString("idcliente"))); cliente.setNome(rs.getString("nome")); cliente.setCpf(rs.getString("cpf")); cliente.setTelefone(rs.getString("telefone")); cliente.setEndereco(rs.getString("endereco")); cliente.setNumero(rs.getString("numero")); cliente.setCidade(rs.getString("cidade")); cliente.setBairro(rs.getString("bairro")); cliente.setCep(Integer.parseInt(rs.getString("cep"))); } } catch (Exception e) { } return cliente; } public String editarCliente(Cliente cli) { String sql = "update cliente set nome=?,cpf=?,telefone=?,endereco=?,numero=?,cidade=?,bairro=?,cep=? where idcliente=?"; String resposta; try { con = cn.conexao(); ps = con.prepareStatement(sql); ps.setString(1, cli.getNome()); ps.setString(2, cli.getCpf()); ps.setString(3, cli.getTelefone()); ps.setString(4, cli.getEndereco()); ps.setString(5, cli.getNumero()); ps.setString(6, cli.getCidade()); ps.setString(7, cli.getBairro()); ps.setInt(8, cli.getCep()); ps.setInt(9,cli.getIdcliente()); ps.executeUpdate(); resposta = "alterado com sucesso"; } catch (Exception e) { resposta = e.getMessage(); } return resposta; } public String deleteCliente(int id) { String sql = "DELETE FROM cliente WHERE idcliente=" + id; String resposta = ""; try { con = cn.conexao(); ps = con.prepareStatement(sql); ps.executeUpdate(); } catch (Exception e) { } return resposta; } public Cliente buscarCliente(String cpf){ String sql ="select * from cliente where cpf="+cpf; try { con = cn.conexao(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()){ cliente.setIdcliente(Integer.parseInt(rs.getString("idcliente"))); cliente.setNome(rs.getString("nome")); cliente.setCpf(rs.getString("cpf")); cliente.setTelefone(rs.getString("telefone")); cliente.setEndereco(rs.getString("endereco")); cliente.setNumero(rs.getString("numero")); cliente.setCidade(rs.getString("cidade")); cliente.setBairro(rs.getString("bairro")); cliente.setCep(Integer.parseInt(rs.getString("cep"))); } } catch (Exception e) { } return cliente; } }
true
5666a19615ad6b9913b1d8e35a3ec574774e0d56
Java
AuroraLS3/ROM-tools
/Rom-tools/src/main/java/com/djrapitops/rom/frontend/javafx/views/SettingsView.java
UTF-8
2,466
2.78125
3
[ "MIT" ]
permissive
package com.djrapitops.rom.frontend.javafx.views; import com.djrapitops.rom.backend.settings.Settings; import com.djrapitops.rom.frontend.javafx.Style; import com.jfoenix.controls.JFXCheckBox; import javafx.geometry.Insets; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; /** * Settings view in the UI. * * @author Rsl1122 */ public class SettingsView extends BorderPane { public SettingsView(BorderPane mainContainer) { prefWidthProperty().bind(mainContainer.widthProperty()); ScrollPane scrollPane = new ScrollPane(); scrollPane.prefWidthProperty().bind(widthProperty()); VBox container = new VBox(); container.prefWidthProperty().bind(scrollPane.widthProperty()); container.setPadding(new Insets(10)); for (Settings setting : Settings.values()) { BorderPane settingLine = new BorderPane(); settingLine.setLeft(new Text(setting.getLabel())); switch (setting.getSettingClass().getSimpleName()) { case "String": TextField field = new TextField(setting.asString()); field.setStyle(Style.BUTTON_SQUARE); field.textProperty().addListener((observable, oldValue, newValue) -> { setting.setValue(newValue); if (!setting.isValidValue(newValue)) { field.setStyle(Style.BUTTON_SQUARE + Style.RED_FONT); } else { field.setStyle(Style.BUTTON_SQUARE + Style.BLACK_FONT); } }); settingLine.setRight(field); break; case "Boolean": JFXCheckBox checkBox = new JFXCheckBox(); checkBox.setSelected(setting.asBoolean()); checkBox.setStyle(Style.CHECKBOX_PURPLE); checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> setting.setValue(newValue)); settingLine.setRight(checkBox); break; default: break; } container.getChildren().add(settingLine); } scrollPane.setContent(container); setCenter(scrollPane); } }
true
4ba1c43e2022462bbc16940a0e37ab4667ce83db
Java
Andreas237/AndroidPolicyAutomation
/ExtractedJars/Health_com.huawei.health/javafiles/o/nj.java
UTF-8
6,746
2.234375
2
[ "MIT" ]
permissive
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package o; import android.graphics.*; import com.github.mikephil.charting.data.Entry; // Referenced classes of package o: // nl, oc, mr, ma, // oa, ml, mz, la, // mh public abstract class nj extends nl { public nj(la la, oa oa1) { super(oa1); // 0 0:aload_0 // 1 1:aload_2 // 2 2:invokespecial #16 <Method void nl(oa)> i = la; // 3 5:aload_0 // 4 6:aload_1 // 5 7:putfield #18 <Field la i> h = new Paint(1); // 6 10:aload_0 // 7 11:new #20 <Class Paint> // 8 14:dup // 9 15:iconst_1 // 10 16:invokespecial #23 <Method void Paint(int)> // 11 19:putfield #25 <Field Paint h> h.setStyle(android.graphics.Paint.Style.FILL); // 12 22:aload_0 // 13 23:getfield #25 <Field Paint h> // 14 26:getstatic #31 <Field android.graphics.Paint$Style android.graphics.Paint$Style.FILL> // 15 29:invokevirtual #35 <Method void Paint.setStyle(android.graphics.Paint$Style)> g = new Paint(4); // 16 32:aload_0 // 17 33:new #20 <Class Paint> // 18 36:dup // 19 37:iconst_4 // 20 38:invokespecial #23 <Method void Paint(int)> // 21 41:putfield #37 <Field Paint g> n = new Paint(1); // 22 44:aload_0 // 23 45:new #20 <Class Paint> // 24 48:dup // 25 49:iconst_1 // 26 50:invokespecial #23 <Method void Paint(int)> // 27 53:putfield #39 <Field Paint n> n.setColor(Color.rgb(63, 63, 63)); // 28 56:aload_0 // 29 57:getfield #39 <Field Paint n> // 30 60:bipush 63 // 31 62:bipush 63 // 32 64:bipush 63 // 33 66:invokestatic #45 <Method int Color.rgb(int, int, int)> // 34 69:invokevirtual #48 <Method void Paint.setColor(int)> n.setTextAlign(android.graphics.Paint.Align.CENTER); // 35 72:aload_0 // 36 73:getfield #39 <Field Paint n> // 37 76:getstatic #54 <Field android.graphics.Paint$Align android.graphics.Paint$Align.CENTER> // 38 79:invokevirtual #58 <Method void Paint.setTextAlign(android.graphics.Paint$Align)> n.setTextSize(oc.b(9F)); // 39 82:aload_0 // 40 83:getfield #39 <Field Paint n> // 41 86:ldc1 #59 <Float 9F> // 42 88:invokestatic #65 <Method float oc.b(float)> // 43 91:invokevirtual #69 <Method void Paint.setTextSize(float)> k = new Paint(1); // 44 94:aload_0 // 45 95:new #20 <Class Paint> // 46 98:dup // 47 99:iconst_1 // 48 100:invokespecial #23 <Method void Paint(int)> // 49 103:putfield #71 <Field Paint k> k.setStyle(android.graphics.Paint.Style.STROKE); // 50 106:aload_0 // 51 107:getfield #71 <Field Paint k> // 52 110:getstatic #74 <Field android.graphics.Paint$Style android.graphics.Paint$Style.STROKE> // 53 113:invokevirtual #35 <Method void Paint.setStyle(android.graphics.Paint$Style)> k.setStrokeWidth(2.0F); // 54 116:aload_0 // 55 117:getfield #71 <Field Paint k> // 56 120:fconst_2 // 57 121:invokevirtual #77 <Method void Paint.setStrokeWidth(float)> k.setColor(Color.rgb(255, 187, 115)); // 58 124:aload_0 // 59 125:getfield #71 <Field Paint k> // 60 128:sipush 255 // 61 131:sipush 187 // 62 134:bipush 115 // 63 136:invokestatic #45 <Method int Color.rgb(int, int, int)> // 64 139:invokevirtual #48 <Method void Paint.setColor(int)> // 65 142:return } public abstract void a(Canvas canvas); protected boolean c(mr mr1) { return (float)mr1.getData().o() < (float)mr1.getMaxVisibleCount() * l.u(); // 0 0:aload_1 // 1 1:invokeinterface #88 <Method ma mr.getData()> // 2 6:invokevirtual #94 <Method int ma.o()> // 3 9:i2f // 4 10:aload_1 // 5 11:invokeinterface #97 <Method int mr.getMaxVisibleCount()> // 6 16:i2f // 7 17:aload_0 // 8 18:getfield #101 <Field oa l> // 9 21:invokevirtual #107 <Method float oa.u()> // 10 24:fmul // 11 25:fcmpg // 12 26:ifge 31 // 13 29:iconst_1 // 14 30:ireturn // 15 31:iconst_0 // 16 32:ireturn } public abstract void d(Canvas canvas); public void d(Canvas canvas, ml ml1, float f, Entry entry, int j, float f1, float f2, int l) { n.setColor(l); // 0 0:aload_0 // 1 1:getfield #39 <Field Paint n> // 2 4:iload 8 // 3 6:invokevirtual #48 <Method void Paint.setColor(int)> canvas.drawText(ml1.b(f, entry, j, this.l), f1, f2, n); // 4 9:aload_1 // 5 10:aload_2 // 6 11:fload_3 // 7 12:aload 4 // 8 14:iload 5 // 9 16:aload_0 // 10 17:getfield #101 <Field oa l> // 11 20:invokeinterface #114 <Method String ml.b(float, Entry, int, oa)> // 12 25:fload 6 // 13 27:fload 7 // 14 29:aload_0 // 15 30:getfield #39 <Field Paint n> // 16 33:invokevirtual #120 <Method void Canvas.drawText(String, float, float, Paint)> // 17 36:return } public abstract void d(Canvas canvas, mh amh[]); public abstract void e(); public abstract void e(Canvas canvas); protected void e(mz mz1) { n.setTypeface(mz1.r()); // 0 0:aload_0 // 1 1:getfield #39 <Field Paint n> // 2 4:aload_1 // 3 5:invokeinterface #130 <Method android.graphics.Typeface mz.r()> // 4 10:invokevirtual #134 <Method android.graphics.Typeface Paint.setTypeface(android.graphics.Typeface)> // 5 13:pop n.setTextSize(mz1.s()); // 6 14:aload_0 // 7 15:getfield #39 <Field Paint n> // 8 18:aload_1 // 9 19:invokeinterface #137 <Method float mz.s()> // 10 24:invokevirtual #69 <Method void Paint.setTextSize(float)> // 11 27:return } protected Paint g; protected Paint h; protected la i; protected Paint k; protected Paint n; }
true
42da06ecd4abc086902d7eb252a5a414bfe88e2b
Java
franspaco/AndroidClass
/TestGUIStuff/app/src/main/java/com/franspaco/testguistuff/MainActivity.java
UTF-8
1,077
2.265625
2
[]
no_license
package com.franspaco.testguistuff; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void btnSave_onClick(View view) { sendToast("Click " + ((Button)findViewById(view.getId())).getText().toString()); } public void sendToast(String str){ Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, str, duration); toast.show(); } public void autoSave_onClick(View view) { sendToast("Checkbox is " + ((CheckBox)view).isChecked()); ((CheckBox)findViewById(R.id.checkBox2)).setChecked(true); } }
true
4c6d5e1719251d5588bdc6ab3e8219433bb18b86
Java
cimav-pruebas/RH01
/src/main/java/cimav/client/view/common/EmpleadoHistoListCell.java
UTF-8
11,454
1.96875
2
[]
no_license
/* * 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 cimav.client.view.common; import cimav.client.data.domain.EGrupo; import cimav.client.data.domain.EmpleadoHisto; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.query.client.GQuery; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Window; import com.google.gwt.view.client.SingleSelectionModel; /** * * @author calderon */ public class EmpleadoHistoListCell extends AbstractCell<EmpleadoHisto> { private final SingleSelectionModel<EmpleadoHisto> selectionModel; private String colorSelected; public EmpleadoHistoListCell(SingleSelectionModel<EmpleadoHisto> selectionModel) { this.selectionModel = selectionModel; this.colorSelected = "#628cd5"; } public void setSelectable(boolean selectable, int empIdSel) { if (selectable) { colorSelected = "#628cd5"; } else { colorSelected = "lightgray"; // "#f0ad4e"; } GQuery.$("#td_selec_" + empIdSel + "_left").css("background-color", colorSelected); GQuery.$("#td_selec_" + empIdSel + "_right").css("background-color", colorSelected); } @Override public void render(Cell.Context context, EmpleadoHisto value, SafeHtmlBuilder sb) { if (value == null) { return; } boolean isSelected = this.selectionModel != null && this.selectionModel.getSelectedObject() != null && this.selectionModel.getSelectedObject().equals(value); String es_null = "---"; String grupoStr = value.getGrupo() != null ? value.getGrupo().getCode() : es_null; boolean tieneEstimulos = EGrupo.CYT.equals(value.getGrupo()); if (tieneEstimulos) { String estimulos = value.getEstimulosProductividad() != null ? "" + value.getEstimulosProductividad() : es_null; grupoStr = grupoStr + "(" + estimulos + ")"; } String estimulosCyt = value.getEstimulosProductividad() != null ? "" + value.getEstimulosProductividad() : es_null; // String deptoCodeStr = value.getDepartamento() != null ? value.getDepartamento().getCode() : es_null; // String deptoNameStr = value.getDepartamento() != null ? value.getDepartamento().getName() : es_null; // String nivelStr = value.getNivel() != null ? value.getNivel().getCode() : es_null; // String nivelNombreStr = value.getNivel() != null ? value.getNivel().getName(): es_null; // String sedeStr = value.getSede() != null ? value.getSede().getAbrev() : es_null; // DateTimeFormat dtf = DateTimeFormat.getFormat("dd/MMM/yyyy"); // String fechaAntStr = dtf.format(value.getFechaAntiguedad()); // String diasMesesAniosStr = "Nulo"; // if (value.getPantYears() != null) { // diasMesesAniosStr = value.getPantYears() + " años(s), " // + value.getPantMonths() + " mese(s), " // + value.getPantDayOdd() + " días(s)"; // } String td_selec_id = "td_selec_" + value.getId(); String html = "<table width='100%' cellspacing='0' cellpadding='0' style='cursor: pointer; text-align: left; vertical-align: middle; border-bottom:1px solid lightgray;'>\n" + " <tbody> \n" + " <tr >\n" + " <td rowspan='6' id='" + td_selec_id + "_left' class'td_selection' style='height:auto; width: 5px; SELECTED_COLOR_REEMPLAZO'></td>\n" + " <td colspan='3' style='height:10px;'></td>\n" + " <td rowspan='6' id='" + td_selec_id + "_right' class'td_selection' style='height:auto; width: 5px; SELECTED_COLOR_REEMPLAZO'></td>\n" + " </tr>\n" + " <tr>\n" + " <td width='78px' rowspan='3' style='text-align: center;'>" + " <img data-toggle='tooltip' data-placement='left' title='TOOL_TIP_ID_REEMPLAZO' src='URL_FOTO_REEMPLAZO' style='border:1px solid lightgray; margin-top: 3px; border-radius:50%; padding:2px;'/>" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan='2' style='vertical-align: top;'><h5 style='margin-top: 0px; margin-bottom: 0px;'>NOMBRE_REEMPLAZO</h5></td>\n" + " </tr>\n" + " <tr >\n" + " <td colspan='1' style='line-height: 1.8;'> " + " <code class='label-cyt-grp-niv'><span >CODE_REEMPLAZO</span></code> " + " <code class='label-cyt-grp-niv'><span >GRUPO_REEMPLAZO</span></code> " + " <code class='label-cyt-grp-niv' data-toggle='tooltip' data-placement='left' title='TOOL_TIP_NIVEL_REEMPLAZO'><span >NIVEL_REEMPLAZO</span></code> " + " <code class='label-cyt-grp-niv'><span >SEDE_REEMPLAZO</span></code> " + " <code class='label-cyt-grp-niv' data-toggle='tooltip' data-placement='left' title='DATO_ANTIGUEDAD_REEMPLAZO'><span >FECHA_ANTIGUEDAD_REEMPLAZO</span></code> " + " </td>\n" + " </tr>\n" + " <tr style='border-bottom:1px solid lightgray;'>\n" + " <td style='text-align:center;' ></td>\n" + " <td colspan='3' style='height:10px;'></td>\n" + " </tr>\n" + " </tbody> " + "</table>"; html = "<table width='100%' cellspacing='0' cellpadding='0' style='cursor: pointer; text-align: left; vertical-align: middle; border-bottom:1px solid lightgray;'>\n" + " <tbody> \n" + " <tr >\n" + " <td colspan='2' style='height:10px; font-size:x-small;'>1:1,1:2</td>\n" + " </tr>\n" + " <tr >\n" + " <td style='width:80px; text-align: center; vertical-align: top; padding-top:2px;'><code style='background-color:blue; color:white; font-size:larger;'>2016|01</code></td>\n" + " <td style=''>" + " <table style'margin-left: 20px;'><tbody>" + " <tr>" + " <td style='text-align: right; vertical-align: bottom; padding-bottom: 2px;'>fecha ingreso</td><td style='padding-left: 4px; font-size: large;'>10/01/2010</td><td>1:3</td><td>1:4</td><td>1:5</td><td>1:6</td><td>1:7</td>" + " </tr>" + " <tr>" + " <td style='text-align: right; vertical-align: bottom;padding-bottom: 2px;'>fecha antigüedad</td><td style='padding-left: 4px; font-size: large;'>10/Ene/2010</td><td>2:3</td><td>2:4</td><td>2:5</td><td>2:6</td><td>2:7</td>" + " </tr>" + " <tr>" + " <td style='text-align: right; vertical-align: bottom; padding-bottom: 2px;'>fecha baja</td><td style='padding-left: 4px; font-size: large;'>---</td><td>3:3</td><td>3:4</td><td>3:5</td><td>3:6</td><td>3:7</td>" + " </tr>" + " <tr>" + " <td style='text-align: right; vertical-align: bottom; padding-bottom: 2px;'>...</td><td style='padding-left: 4px; font-size: large;'>---</td><td>4:3</td><td>4:4</td><td>4:5</td><td>4:6</td><td>4:7</td>" + " </tr>" + " </tbody></table>" + " </td>\n" + " </tr>\n" + " <tr >\n" + " <td colspan='2' style='height:10px; font-size:x-small;'>3:1,3:2</td>\n" + " </tr>\n" + " </tbody> " + "</table>"; if (isSelected) { html = html.replace("SELECTED_COLOR_REEMPLAZO", "background-color: " + colorSelected + ";"); // 628cd5;"); } else if (value.isDirty() != null && value.isDirty()) { html = html.replace("SELECTED_COLOR_REEMPLAZO", "background-color: lightgray;"); } else { html = html.replace("SELECTED_COLOR_REEMPLAZO", "background-color: #F8F8F8;"); } try { String idReem = "---"; if (value.getId() != null) { idReem = value.getId().toString(); } html = html.replace("CODE_REEMPLAZO", chkStrNull(value.getCode())); // html = html.replace("URL_FOTO_REEMPLAZO", chkStrNull(value.getUrlPhoto())); html = html.replace("NOMBRE_REEMPLAZO", chkStrNull(value.getName())); html = html.replace("GRUPO_REEMPLAZO", chkStrNull(grupoStr)); // html = html.replace("TOOL_TIP_NIVEL_REEMPLAZO", chkStrNull(nivelNombreStr)); // html = html.replace("NIVEL_REEMPLAZO", chkStrNull(nivelStr)); // html = html.replace("DEPTO_CODIGO_REEMPLAZO", chkStrNull(deptoCodeStr)); // html = html.replace("TOOL_TIP_DEPTO_REEMPLAZO", chkStrNull(deptoNameStr)); // html = html.replace("SEDE_REEMPLAZO", chkStrNull(sedeStr)); // html = html.replace("FECHA_ANTIGUEDAD_REEMPLAZO", chkStrNull(fechaAntStr)); // html = html.replace("DATO_ANTIGUEDAD_REEMPLAZO", chkStrNull(diasMesesAniosStr)); if (value.getId() != null) { html = html.replace("ID_REEMPLAZO", value.getId().toString()); } else { html = html.replace("ID_REEMPLAZO", "---"); } sb.appendHtmlConstant(html); } catch (Exception e) { Window.alert("Catch it! " + html); } } private String chkStrNull(String str) { String r = str != null ? str.trim() : "---"; return r; } // public static native String camelize(String str)/*-{ // return (str.match(/\-/gi) ? str.toLowerCase().replace(/\-(\w)/gi, function(a, c){return c.toUpperCase();}) : str); // }-*/; // // public static String capitalize(String value) { // return value == null ? value : value.substring(0, 1).toUpperCase() + value.substring(1).toLowerCase(); // } // /** * Truncate a string and add an ellipsis ('...') to the end if it exceeds * the specified length. * * @param value the string to truncate * @param len the maximum length to allow before truncating * @return the converted text */ public String ellipse(String value, int len) { if (value != null && value.length() > len) { return value.substring(0, len - 3) + "..."; } return value; } }
true
44a55216a3315c0a1ae72eed4bc5d682dd8f1f18
Java
Kopyn/School_Project_2
/src/IQueue.java
WINDOWS-1250
2,577
3.109375
3
[]
no_license
public interface IQueue<T> { public void enqueue(T o) throws FullQueueException; public T dequeue() throws EmptyQueueException; public boolean isEmpty(); public boolean isFull(); public int size(); public T first() throws FullQueueException; public void addWithPriority(T o); public void naKolejke(); public String getKlasa(); public int getNulle(); } //fifo /*if(aktywnyProces().getCzasZgloszenia()+aktywnyProces().getCzasWykonania()<i) { lista.peek().setCzasOczekiwania(i-lista.peek().getCzasZgloszenia()); } if(lista.peek()!=null) { if(lista.peek().czyWykonany()==false) { lista.peek().setPozostalyCzas(lista.peek().getPozostalyCzas()-1); if(lista.peek().getPozostalyCzas()==0) { lista.peek().czasZakonczenia=i; lista.peek().setWykonany(true); } }else { s.ilPrzelaczen++; s.dodajDoStatystyki(lista.peek()); lista.poll(); if(lista.peek()!=null) lista.peek().czasRozpoczecia=i; } //System.out.println(i); System.out.println(lista.peek()); //System.out.println(nastProces); } else return; }*/ //rot /* if(a>=procesy.size()) { a=0; } b=a+1;//potrzebne do oceny, czy przecza procesy if(b>=procesy.size()) { b=0; } if(a!=b) czasNastZgloszenia=procesy.get(b).getCzasZgloszenia(); System.out.println("czasNastZgloszenia: "+czasNastZgloszenia); System.out.println(this.aktywnyProces()); if(procesy.get(a).doKoncaKwantu>0) {//rozpoczynanie pracy na okres przydzielonego czasu procesy.get(a).setPozostalyCzas(procesy.get(a).getPozostalyCzas()-1); if(procesy.get(a).getPozostalyCzas()==0) {//zmiana pozostaego czasu wykonywana jest lini wyej, wic warunek ten istnieje w celu zgodnoci czasu zakoczenia procesy.get(a).setWykonany(true); procesy.get(a).czasZakonczenia=i; s.dodajDoStatystyki(procesy.get(a)); procesy.remove(a); return; } procesy.get(a).doKoncaKwantu--; return; } procesy.get(a).doKoncaKwantu=Rot.kwant; if(czasNastZgloszenia>i) { a=0;//jesli nie pojawi sie zadne zadanie-idz na poczatek kolejki procesy.get(a).setPozostalyCzas(procesy.get(a).getPozostalyCzas()-1); if(procesy.get(a).getPozostalyCzas()==0) { procesy.get(a).setWykonany(true); procesy.get(a).czasZakonczenia=i; s.dodajDoStatystyki(procesy.get(a)); procesy.remove(a); return; } procesy.get(a).doKoncaKwantu=Rot.kwant; //return; }else { s.ilPrzelaczen++;//przelaczenie trwa 1 jednostke czasu i jest doliczane do czasu oczekiwania nastepnego procesu a++; //return; } */
true
80c0e97f768ce8fba197f5332bc9da3bb83169d7
Java
m41na/zesty-router
/router-core/src/main/java/com/practicaldime/router/core/servlet/HandlerResult.java
UTF-8
631
2.40625
2
[]
no_license
package com.practicaldime.router.core.servlet; public class HandlerResult { private final Long startInMillis; private Boolean status = Boolean.TRUE; public HandlerResult() { this.startInMillis = System.currentTimeMillis(); } public static HandlerResult build(Boolean status) { HandlerResult res = new HandlerResult(); res.status = status; return res; } public Boolean isSuccess() { return this.status; } public Long updateStatus(Boolean status) { this.status = status; return System.currentTimeMillis() - this.startInMillis; } }
true
1e162eeaf43e01644cfd4431312d9928da97704f
Java
tomzcs/ProjectEmergencyUser
/app/src/main/java/com/example/tomz4th_chaiyot/projectemergencyuser/dao/RateDao.java
UTF-8
586
2.296875
2
[]
no_license
package com.example.tomz4th_chaiyot.projectemergencyuser.dao; import com.google.gson.annotations.SerializedName; /** * Created by toMz4th-ChaiYot on 12/26/2016. */ public class RateDao { @SerializedName("total") private float total; @SerializedName("count") private float count; public RateDao(){} public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } public float getCount() { return count; } public void setCount(float count) { this.count = count; } }
true
65aeb09d697aa952e70049704cd76a33097f68fb
Java
novoda/download-manager
/library/src/main/java/com/novoda/downloadmanager/WrappedOkHttpClient.java
UTF-8
967
2.671875
3
[ "Apache-2.0" ]
permissive
package com.novoda.downloadmanager; import java.io.IOException; import java.util.Map; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; class WrappedOkHttpClient implements HttpClient { private final OkHttpClient httpClient; WrappedOkHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public NetworkResponse execute(NetworkRequest request) throws IOException { Request.Builder requestBuilder = new Request.Builder() .url(request.url()); if (request.method() == NetworkRequest.Method.HEAD) { requestBuilder = requestBuilder.head(); } for (Map.Entry<String, String> entry : request.headers().entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } Call call = httpClient.newCall(requestBuilder.build()); return new WrappedOkHttpResponse(call.execute()); } }
true
ae4f8c9c38fe1c15df78a1d0adffa5b75799263e
Java
AnirudhMayuram/College_App
/app/src/main/java/anirudh/svct/auto_profile.java
UTF-8
502
1.796875
2
[]
no_license
package anirudh.svct; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; public class auto_profile extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_profile); WebView webView=(WebView)findViewById(R.id.auto_profile_web); webView.loadUrl("file:///android_asset/auto_profile.html"); } }
true
21dae5258ededcd02b2244c230fd197b72ffafc8
Java
JuanDavid98S/recomposicion-inversiones
/Inversiones - Backend/src/main/java/com/segbol/inversiones/dominio/repositorio/IRepositorioAutenticacion.java
UTF-8
401
2.1875
2
[]
no_license
package com.segbol.inversiones.dominio.repositorio; import com.segbol.inversiones.persistencia.entidades.Usuario; import java.util.ArrayList; //Interfaz para definir los métodos abstractos del repositorio de autenticación public interface IRepositorioAutenticacion { Usuario obtenerUsuario(Integer idUsuario); ArrayList<Usuario> listarUsuarios(); ArrayList<Usuario> listarAdmins(); }
true
f059ff4bee910e4c0f89b74f024b11a5928c0eaf
Java
zhongxingyu/Seer
/Diff-Raw-Data/35/35_eb77f36efe3d36af21250e36e322368f261ae107/ComponentCreationOperationEx/35_eb77f36efe3d36af21250e36e322368f261ae107_ComponentCreationOperationEx_s.java
UTF-8
4,547
1.679688
2
[]
no_license
/******************************************************************************* * Copyright (c) 2003, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.common.componentcore.internal.operation; import java.util.List; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.emf.common.util.EList; import org.eclipse.jem.util.emf.workbench.ProjectUtilities; import org.eclipse.jem.util.logger.proxy.Logger; import org.eclipse.wst.common.componentcore.ComponentCore; import org.eclipse.wst.common.componentcore.datamodel.properties.IComponentCreationDataModelProperties; import org.eclipse.wst.common.componentcore.internal.ComponentType; import org.eclipse.wst.common.componentcore.internal.ComponentcoreFactory; import org.eclipse.wst.common.componentcore.internal.StructureEdit; import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; import org.eclipse.wst.common.frameworks.datamodel.properties.IFlexibleProjectCreationDataModelProperties; public abstract class ComponentCreationOperationEx extends AbstractDataModelOperation implements IComponentCreationDataModelProperties { public ComponentCreationOperationEx(IDataModel model) { super(model); } public IStatus execute(String componentType, IProgressMonitor monitor, IAdaptable info) { createProjectIfNeeded(monitor, info); try { createAndLinkJ2EEComponents(); } catch (CoreException e) { Logger.getLogger().log(e); } setupComponentType(componentType); return OK_STATUS; } private void createProjectIfNeeded(IProgressMonitor monitor, IAdaptable info) { Object dm = model.getNestedModel(NESTED_PROJECT_CREATION_DM); if(dm == null) return; String projName = ((IDataModel)dm).getStringProperty(IFlexibleProjectCreationDataModelProperties.PROJECT_NAME); IProject proj = ProjectUtilities.getProject(projName); if(projName == null || projName.equals("") || proj.exists()) return; IDataModelOperation op = ((IDataModel)dm).getDefaultOperation(); try { op.execute(monitor, info); } catch (ExecutionException e) { e.printStackTrace(); } } // to make it abstract protected abstract void createAndLinkJ2EEComponents() throws CoreException; protected void setupComponentType(String typeID) { IVirtualComponent component = ComponentCore.createComponent(getProject(), model.getStringProperty(ComponentCreationDataModelProvider.COMPONENT_DEPLOY_NAME)); ComponentType componentType = ComponentcoreFactory.eINSTANCE.createComponentType(); componentType.setComponentTypeId(typeID); componentType.setVersion(getVersion()); List newProps = getProperties(); if (newProps != null && !newProps.isEmpty()) { EList existingProps = componentType.getProperties(); for (int i = 0; i < newProps.size(); i++) { existingProps.add(newProps.get(i)); } } StructureEdit.setComponentType(component, componentType); } protected IProject getProject() { String name = model.getStringProperty(PROJECT_NAME); return ProjectUtilities.getProject(name); } protected String getComponentName() { return model.getStringProperty(COMPONENT_NAME); } public String getComponentDeployName() { return model.getStringProperty(COMPONENT_DEPLOY_NAME); } protected abstract String getVersion(); protected abstract List getProperties(); }
true
d7f72463a3646720c3f56cde53700bd015dda859
Java
bellmit/aq-parent
/aq-facade-strategy/src/main/java/com/aq/facade/entity/Strategy.java
UTF-8
1,359
2.140625
2
[]
no_license
package com.aq.facade.entity; import lombok.Data; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 策略表 * * @author 熊克文 * @date 2018-02-08 */ @Table(name = "aq_strategy") @Data public class Strategy implements Serializable { /** * 主键id */ @Id private Integer id; /** * 发布者头像 */ @Column(name = "publisherPhoto") private String publisherPhoto; /** * 发布者名称 */ @Column(name = "publisherName") private String publisherName; /** * 开始时间 */ @Column(name = "beginDate") private Date beginDate; /** * 创建时间 */ @Column(name = "createTime") private Date createTime; /** * 创建人 */ @Column(name = "createId") private Integer createId; /** * 策略名称 */ @Column(name = "strategyName") private String strategyName; /** * 策略描述 */ @Column(name = "strategyDesc") private String strategyDesc; /** * 上传py文件名称 */ @Column(name = "fileName") private String fileName; /** * 价格 */ @Column(name = "price") private BigDecimal price; }
true
d2069337c5507816ec4b9d216675bb3b604616b9
Java
liurenjin/hippo-site-toolkit
/client/src/test/java/org/hippoecm/hst/component/support/bean/TestBaseHstComponent.java
UTF-8
4,489
1.757813
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2008-2013 Hippo B.V. (http://www.onehippo.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. */ package org.hippoecm.hst.component.support.bean; import java.awt.Color; import java.lang.reflect.Method; import org.apache.commons.proxy.Invoker; import org.hippoecm.hst.content.beans.Node; import org.hippoecm.hst.content.beans.standard.HippoDocument; import org.hippoecm.hst.core.component.HstParameterInfoProxyFactoryImpl; import org.hippoecm.hst.core.request.ComponentConfiguration; import org.hippoecm.hst.core.request.HstRequestContext; import org.hippoecm.hst.mock.core.component.MockHstRequest; import org.hippoecm.hst.proxy.ProxyFactory; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.web.MockServletContext; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * TestBaseHstComponent * @version $Id$ */ public class TestBaseHstComponent { private MockServletContext servletContext; private ComponentConfiguration componentConfig; private HstRequestContext requestContext; @Before public void setUp() throws Exception { servletContext = new MockServletContext(new ClassPathXmlApplicationContext()); componentConfig = createNiceMock(ComponentConfiguration.class); replay(componentConfig); requestContext = createNiceMock(HstRequestContext.class); expect(requestContext.getParameterInfoProxyFactory()).andReturn(new HstParameterInfoProxyFactoryImpl()).anyTimes(); replay(requestContext); } @Test public void testGetParametersInfo() throws Exception { // create a dummy component configuration for test. ProxyFactory factory = new ProxyFactory(); ComponentConfiguration compConfig = (ComponentConfiguration) factory.createInvokerProxy(new Invoker() { public Object invoke(Object o, Method m, Object[] args) throws Throwable { if (args == null) { return null; } else { if ("pagesize".equals(args[0])) { return "10"; } else if ("description".equals(args[0])) { return "Test description"; } else if ("color".equals(args[0])) { return "#ff0000"; } } return null; } }, new Class [] { ComponentConfiguration.class }); // now initialize the component with the component configuration ANewsArticleComponent component = new ANewsArticleComponent(); component.init(servletContext, compConfig); // do testing now.. MockHstRequest hstRequest = new MockHstRequest(); // set dummy requestcontext hstRequest.setRequestContext(requestContext); ANewsArticleComponentParametersInfo paramsInfo = component.getComponentParametersInfo(hstRequest); assertNotNull(paramsInfo); assertEquals(10, paramsInfo.getPageSize()); assertEquals("Test description", paramsInfo.getDescription()); assertEquals(Color.RED, paramsInfo.getColor()); // should return same object for the same hstRequest. assertTrue(paramsInfo == component.getComponentParametersInfo(hstRequest)); assertEquals("testValue", paramsInfo.getHiddenPropertyInChannelManagerUI()); } @Node(jcrType="test:textdocument") public static class TextBean extends HippoDocument { } @Node(jcrType="test:comment") public static class CommentBean extends HippoDocument { } }
true
1e512e8b511a52fcb8cdd5c3a8c5647a2d04dfba
Java
juanmanu45/parcial2
/src/java/VO/Relacion_laboral.java
UTF-8
2,546
1.929688
2
[]
no_license
/* * 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 VO; /** * * @author LabingXEON */ public class Relacion_laboral { private int cedula_emple; private int id_rela; private String estatus; private String fecha_ingre; private String depto; private String puesto; private String turno; private String tipo_sueldo; private String tipo_regimen; public Relacion_laboral(int cedula_emple, int id_rela, String estatus, String fecha_ingre, String depto, String puesto, String turno, String tipo_sueldo, String tipo_regimen) { this.cedula_emple = cedula_emple; this.id_rela = id_rela; this.estatus = estatus; this.fecha_ingre = fecha_ingre; this.depto = depto; this.puesto = puesto; this.turno = turno; this.tipo_sueldo = tipo_sueldo; this.tipo_regimen = tipo_regimen; } public String getDepto() { return depto; } public void setDepto(String depto) { this.depto = depto; } public String getPuesto() { return puesto; } public void setPuesto(String puesto) { this.puesto = puesto; } public String getTurno() { return turno; } public void setTurno(String turno) { this.turno = turno; } public String getTipo_sueldo() { return tipo_sueldo; } public void setTipo_sueldo(String tipo_sueldo) { this.tipo_sueldo = tipo_sueldo; } public String getTipo_regimen() { return tipo_regimen; } public void setTipo_regimen(String tipo_regimen) { this.tipo_regimen = tipo_regimen; } public int getCedula_emple() { return cedula_emple; } public void setCedula_emple(int cedula_emple) { this.cedula_emple = cedula_emple; } public int getId_rela() { return id_rela; } public void setId_rela(int id_rela) { this.id_rela = id_rela; } public String getEstatus() { return estatus; } public void setEstatus(String estatus) { this.estatus = estatus; } public String getFecha_ingre() { return fecha_ingre; } public void setFecha_ingre(String fecha_ingre) { this.fecha_ingre = fecha_ingre; } }
true
4e30761707c0d57c465b237215e81faa08845da0
Java
chebopav/sights
/sights/src/main/java/com/project/services/ExcursionService.java
UTF-8
4,013
2.5
2
[]
no_license
package com.project.services; import com.project.entity.data.Excursion; import com.project.entity.data.Museum; import com.project.entity.data.NeedDate; import com.project.entity.data.address.City; import com.project.exceptions.DataException; import com.project.repository.CityRepository; import com.project.repository.ExcursionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class ExcursionService { private ExcursionRepository repository; private CityRepository cityRepository; @Autowired public ExcursionService(ExcursionRepository repository, CityRepository cityRepository) { this.repository = repository; this.cityRepository = cityRepository; } public ExcursionRepository getRepository() { return repository; } public Excursion addExcursion(Excursion excursion) throws DataException { if(repository.existsById(excursion.getId())){ throw new DataException("Экскурсия уже существует"); } return repository.save(excursion); } public Excursion updateExcursion(Excursion excursion) throws DataException { if(!repository.existsById(excursion.getId())){ throw new DataException("Экскурсия не существует"); } return repository.save(excursion); } public Page<Excursion> getPageOfExcursions(int page, int size) throws DataException { Pageable pageable = PageRequest.of(page, size); Page<Excursion> excursionPage = repository.findAll(pageable); if (excursionPage.isEmpty()){ throw new DataException("Записи экскурсий не найдены"); } return excursionPage; } public Optional<Excursion> getExcursionById(long id) throws DataException { Optional<Excursion> result = repository.findById(id); if (result.isEmpty()){ throw new DataException("Экскурсия не найдена"); } return result; } public void deleteExcursionById(long id) throws DataException { if (!repository.existsById(id)){ throw new DataException("Экскурсия не найдена"); } repository.deleteById(id); } public Iterable<Excursion> getExcursionsByType(Excursion.Type type) throws DataException { int i = type.ordinal(); Iterable<Excursion> result = repository.getExcursionByType(i); if (result == null) throw new DataException("Экскурсии не найдены"); return result; } public Excursion getExcursionByName(String name) throws DataException { Excursion result = repository.findByName(name); if (result == null) throw new DataException("Экскурсия не найдена"); return result; } public List<Excursion> getAllExcursionsToDateInCity(NeedDate date, City city){ List<Excursion> excursions = repository.getAllEventsToDate(date.getDate()); List<Excursion> result = new ArrayList<>(); for (Excursion excursion : excursions) { if(excursion.getCity().equals(city)){ result.add(excursion); } } return result; } public List<Excursion> getAllExcursionsOfCity(int cityId){ City selectedCity = cityRepository.findById(cityId).get(); return repository.getAllExcursionsOfCity(selectedCity); } public Excursion getRandomEventToDateInCity(NeedDate date, City city){ List<Excursion> events = getAllExcursionsToDateInCity(date, city); return events.get((int)(Math.random() * events.size())); } }
true
4ddc9d4c99730f4a5db7ad8c2af74b3b920ae8a0
Java
yhansol145/K01Java
/src/ex17collection/Ex04HashSet1.java
UTF-8
3,626
4.0625
4
[]
no_license
package ex17collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import common.Teacher; /* HashSet 컬렉션 : Set 계열의 인터페이스를 구현한 컬렉션으로 - 객체가 순서없이 저장된다. - 객체의 중복저장을 기본적으로 허용하지 않는다. 단, 기본클래스가 아닌 새롭게 저의한 클래스라면 hashCode(), equals()를 적절히 오버라이딩하여 정의해야 한다. - List가 배열의 성격이라면, Set은 집합의 성격을 가진다. */ public class Ex04HashSet1 { public static void main(String[] args) { //1] set 컬렉션 생성 HashSet<Object> set = new HashSet<Object>(); //2] 다양한 객체 생성 String strObject1 = "JAVA"; String strObject2 = new String("KOSMO61rl"); Date dateObject = new Date(); int number = 100; Teacher teacher = new Teacher("김봉두", 55, "체육"); //3] 객체저장 : add()메소드를 통해 저장되고, 문제가 없다면 true가 반환된다. System.out.println(set.add(strObject1));//true반환 set.add(strObject2); set.add(dateObject); set.add(number); //<- Integer객체로 Boxing처리후 저장됨 set.add(teacher); //4] 저장된 객체수 출력 : 5개 System.out.println("[중복저장전 객체수]:"+ set.size()); //5개 //5-1] 기본 클래스형 객체 중복저장 // : 기본클래스인 경우 별도의 오버라이딩 처리없이도 중복이 제거된다. 따라서 아래의 경우 false가 반환된다. System.out.println(set.add(strObject2) ? "저장성공" : "저장실패"); System.out.println("[중복(String)저장후 객체수]:"+ set.size());//5개 //5-2] 개발자가 정의한 객체 중복저장 // : 사용자 정의 클래스인 경우 hashCode, equals메소드를 오버라이딩 하지 않으면 중복저장이 허용된다. // : 아래의 경우 저장에 성공하여 true가 반환된다. Teacher teacher2 = new Teacher("김봉두", 55, "체육"); System.out.println(set.add(teacher2) ? "성공" : "실패"); //성공 System.out.println("[중복(teacher2)저장후 객체수]:"+ set.size());//6개 //6] 저장된객체출력 : 순서없이 저장되므로 출력의 순서도 지정할 수 없다. Iterator itr = set.iterator(); //이터레이터 객체 생성 및 준비 while(itr.hasNext()) { //추출할 객체가 있는지 확인 후 Object object = itr.next(); //추출 if(object instanceof String) { System.out.println("String타입:"+ object); } else if(object instanceof Date) { System.out.println("Date타입:"+ object); } else if(object instanceof Integer) { System.out.println("Integer타입:"+ object); } else if(object instanceof Teacher) { System.out.println("Teacher타입:"+ object); } else { System.out.println("넌 뭐임??-_-;"); } }//end of while //객체의 존재여부 확인 System.out.println(set.contains(strObject1) ? "strObject1있다" : "strObject1없다"); System.out.println(set.contains("JaVa") ? "JaVa있다" : "JaVa없다"); //객체 삭제 System.out.println(set.remove(strObject2) ? "strObject2삭제성공" : "strObject2삭제실패"); System.out.println(set.remove("Android") ? "Androide삭제성공" : "Android삭제실패"); System.out.println("[삭제 후 객체수]"+ set.size()); //전체삭제 System.out.println("전체삭제:"+ set.removeAll(set)); System.out.println("[전체 삭제후 객체 수]:"+ set.size()); } }
true
9918a4e67af1270474ab7f24a301bba724fe9e9a
Java
newSue/SFABASE
/src/main/java/com/winchannel/mss/visit/service/VisitPhotoManagerSfa.java
UTF-8
14,335
2.140625
2
[]
no_license
package com.winchannel.mss.visit.service; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.upload.FormFile; import com.winchannel.base.utils.AppContext; import com.winchannel.core.dao.HibernateEntityDao; import com.winchannel.core.exception.BusinessException; import com.winchannel.core.utils.DateUtils; import com.winchannel.core.utils.FileTypeDetectUtils; import com.winchannel.mss.visit.model.VisitPhotoSfa; /** * 为方便 维护 从BaseMdm包中移过来. * @author chenxiangguo * */ public class VisitPhotoManagerSfa extends HibernateEntityDao<VisitPhotoSfa> { private static final Log log = LogFactory.getLog("VisitPhotoManager"); public List<VisitPhotoSfa> getVisitPhotoByID(String id) { StringBuffer queryString = new StringBuffer("from VisitPhotoSfa where 1=1"); queryString.append(" and img_Id ='").append(id + "'"); return this.findEntity(VisitPhotoSfa.class,queryString.toString()); } public String getStorePhotoJson(String storeId) { String where = ""; if (StringUtils.isNotBlank(storeId)) { where = " and STORE_ID=" + storeId; } String sql = "select * from V_MOBILE_JSON_STORE_PHOTO where 1=1 " + where; List<Object[]> list = this.executeSqlQuery(sql); JSONArray res = new JSONArray(); for (Object[] o : list) { JSONObject obj = new JSONObject(); obj.put("namea", o[0] != null ? o[0] + "" : null); obj.put("nameb", o[1] != null ? o[1] + "" : null); obj.put("namec", o[2] != null ? o[2] + "" : null); obj.put("grorname", o[3] != null ? o[3] + "" : null); obj.put("gropname", o[4] != null ? o[4] + "" : null); obj.put("grocname", o[5] != null ? o[5] + "" : null); obj.put("storecode", o[6] != null ? o[6] + "" : null); obj.put("storename", o[7] != null ? o[7] + "" : null); obj.put("photo", o[8] != null ? o[8] + "" : null); obj.put("lon", o[9] != null ? o[9] + "" : null); obj.put("lat", o[10] != null ? o[10] + "" : null); res.add(obj); } return res.toString(); } /** * @param productName * 产品名 * @param photoFile * 上传文件路径 * @param request * 用来得到服务器上的路径 * @return 工程的相对路径 上传图片 */ public String upPhoto(String productName, FormFile photoFile, HttpServletRequest request) { String re = null; String path = null; // 在 DMS 与 SFA 中通用的图片存储路径,目前为 photos 目录 String imgsrc = null; if (null == request.getAttribute("imgsrc")) { imgsrc = "photos"; } else { // photos imgsrc = request.getAttribute("imgsrc").toString().toLowerCase(); } File file; if (!AppContext.hasHomeRoot()) { // throw new BusinessException("mdmPage", "mdm.appHomeNotExist"); path = request.getSession().getServletContext().getRealPath("/"); path = path + imgsrc + File.separator; // path--->.....webapps\root\photos\ file = new File(path); if (!file.exists()) { // 没有APP_HOME时,检验photos目录 // 如果在root下面也找不到 photos 目录,那就自动建立 file.mkdirs(); } } else { path = AppContext.HOME_ROOT; path = path + imgsrc + File.separator; // path--->.....APP_HOME\photos\ file = new File(path); if (!file.exists()) { // 有APP_HOME但是没有photos目录时,回归root // 如果 APP_HOME 之下没有photos目录,则回归root目录 path = request.getSession().getServletContext() .getRealPath("/"); // path--->.....webapps\root\photos\ path = path + imgsrc + File.separator; file = new File(path); // 有APP_HOME但是没有photos目录时,检验 root 目录下的photos 目录 if (!file.exists()) { // 如果在root下面也找不到 photos 目录,那就自动在APP_HOME中建立photos目录 path = AppContext.HOME_ROOT; path = path + imgsrc + File.separator; // path--->.....APP_HOME\photos\ file = new File(path); file.mkdirs(); } } } String photoURL = photoFile.getFileName(); if (!photoURL.toLowerCase().endsWith("jpg") && !photoURL.toLowerCase().endsWith("jpeg") && !photoURL.toLowerCase().endsWith("gif") && !photoURL.toLowerCase().endsWith("png")) { throw new BusinessException( "Only the image of jpg/jpeg/gif/png type can be handled!"); } String dateString = DateUtils.format(Calendar.getInstance().getTime(), "yyyy-MM-dd"); path = path + dateString + File.separator; file = new File(path); if (!file.exists()) { file.mkdirs(); // 要求手动建立存放图片的photos目录,但是可以自动创建对应的日期目录 } DataInputStream dis = null; DataOutputStream dos = null; OutputStream ops = null; File outFile = null; try { dis = new DataInputStream(new BufferedInputStream( photoFile.getInputStream())); re = path + imgsrc.substring(0, 5); // photos--->photo re = re + "_"; re = re + productName + (new Date()).getTime() + photoURL.substring(photoURL.lastIndexOf(".")); outFile = new File(re); ops = new FileOutputStream(outFile); dos = new DataOutputStream(new BufferedOutputStream(ops)); int bufferLength = 8096; byte[] buffer = new byte[bufferLength]; int readCount = 0; readCount = dis.read(buffer, 0, bufferLength); while (readCount > 0) { dos.write(buffer, 0, readCount); dos.flush(); readCount = dis.read(buffer, 0, bufferLength); } dos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.fileNotFound"); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.ioError"); } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.closeInputFileError"); } } if (dos != null) { try { dos.close(); ops.close(); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.closeOutputFileError"); } } } if (re != null) { re = re.substring( re.indexOf(File.separator + imgsrc + File.separator)) .replace(File.separator, "/"); } return re; } public static void doViewPhotoWithAction(ServletRequest request, ServletResponse response) throws Exception { boolean canwork = true; HttpServletRequest http_req = null; String remote_ip = null; String url = null; HttpServletResponse http_resp = null; String path = null; String keyword = null; try { http_req = (HttpServletRequest) request; remote_ip = http_req.getRemoteAddr(); // 针对传递参数做判断 if (StringUtils.isNotBlank(http_req.getParameter("imgurl"))) { url = http_req.getParameter("imgurl").toLowerCase(); } else { throw new BusinessException( "Parameter imgurl is not available."); } if (StringUtils.isNotBlank(http_req.getParameter("imgsrc"))) { keyword = http_req.getParameter("imgsrc").toLowerCase(); } else { keyword = "photos"; // throw new // BusinessException("Parameter imgsrc is not available."); } if (!url.endsWith("jpg") && !url.endsWith("jpeg") && !url.endsWith("gif") && !url.endsWith("png")) { throw new BusinessException( "Only the image of jpg/jpeg/gif/png type can be handled!"); } log.info("doViewPhotoWithAction, remote_ip:" + remote_ip + " | url=" + url); http_resp = (HttpServletResponse) response; http_resp.setDateHeader("Expires", 0); http_resp.setHeader("Accept-Ranges", "bytes"); String webapp_path = http_req.getSession().getServletContext() .getRealPath("/"); String apphome_path = AppContext.HOME_ROOT; String img_url = url .substring(url.lastIndexOf("/" + keyword + "/")); // 按照APP_HOME优先的原则,顺序尝试可能存放文件的APP_HOME目录及webapps目录 File tempfile = null; path = apphome_path; path = path + img_url; path = path.replace('/', File.separatorChar); tempfile = new File(path); if (tempfile.exists()) { // use APP_HOME as this path for photos } else { path = webapp_path; path = path + img_url; path = path.replace('/', File.separatorChar); tempfile = new File(path); if (tempfile.exists()) { // use webapps as this path for photos } else { // throw new // BusinessException("Can not found this file in APP_HOME or webapps path."); canwork = false; log.error("Can not found this file in APP_HOME or webapps path:" + path); } } } catch (Exception ex) { canwork = false; log.error("error, remote_ip = " + request.getRemoteAddr(), ex); throw ex; } // 检测图片类型 String fileType = FileTypeDetectUtils.getFileType(path); String contentType = "image/"; if (fileType != null) { contentType += fileType; } else { contentType += "*"; } http_resp.setContentType(contentType); log.info("The image contentType is : " + contentType); // has error before? if (true == canwork) { doSendFile(path, http_resp); } else {// has error before // nothing to do here! } } public static void doViewPhotoWithFilter(ServletRequest request, ServletResponse response) throws Exception { boolean canwork = true; HttpServletRequest http_req = null; String remote_ip = null; String url = null; HttpServletResponse http_resp = null; String path = null; String keyword = null; try { http_req = (HttpServletRequest) request; remote_ip = http_req.getRemoteAddr(); url = http_req.getRequestURI().toLowerCase(); if (!url.toLowerCase().endsWith("jpg") && !url.toLowerCase().endsWith("jpeg") && !url.toLowerCase().endsWith("gif") && !url.toLowerCase().endsWith("png")) { throw new BusinessException( "Only the image of jpg/jpeg/gif/png type can be handled!"); } log.info("doViewPhotoWithFilter, remote_ip:" + remote_ip + " | url=" + url); http_resp = (HttpServletResponse) response; http_resp.setDateHeader("Expires", 0); http_resp.setHeader("Accept-Ranges", "bytes"); String webapp_path = http_req.getSession().getServletContext() .getRealPath("/"); String apphome_path = AppContext.HOME_ROOT; keyword = "photos"; String img_url = url .substring(url.lastIndexOf("/" + keyword + "/")); // 按照APP_HOME优先的原则,顺序尝试可能存放文件的APP_HOME目录及webapps目录 File tempfile = null; path = apphome_path; path = path + img_url; path = path.replace('/', File.separatorChar); tempfile = new File(path); if (tempfile.exists()) { // use APP_HOME as this path for photos } else { path = webapp_path; path = path + img_url; path = path.replace('/', File.separatorChar); tempfile = new File(path); if (tempfile.exists()) { // use webapps as this path for photos } else { throw new BusinessException( "Can not found this file in APP_HOME or webapps path."); } } } catch (Exception ex) { canwork = false; log.error("error, remote_ip = " + request.getRemoteAddr(), ex); throw ex; } // 检测图片类型 String fileType = FileTypeDetectUtils.getFileType(path); String contentType = "image/"; if (fileType != null) { contentType += fileType; } else { contentType += "*"; } http_resp.setContentType(contentType); log.info("The image contentType is : " + contentType); // has error before? if (true == canwork) { doSendFile(path, http_resp); } else {// has error before // nothing to do here! } } private static void doSendFile(String path, HttpServletResponse http_resp) throws Exception { DataInputStream dis = null; DataOutputStream dos = null; OutputStream ops = null; try { dis = new DataInputStream(new BufferedInputStream( new FileInputStream(path))); http_resp.setContentLength(dis.available()); ops = http_resp.getOutputStream(); dos = new DataOutputStream(new BufferedOutputStream(ops)); int bufferLength = 8096; byte[] buffer = new byte[bufferLength]; int readCount = 0; readCount = dis.read(buffer, 0, bufferLength); while (readCount > 0) { dos.write(buffer, 0, readCount); dos.flush(); readCount = dis.read(buffer, 0, bufferLength); } dos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.fileNotFound"); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.ioError"); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.closeInputFileError"); } } if (dos != null) { try { dos.close(); ops.close(); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("base", "common.upPhoto.closeOutputFileError"); } } } } }
true
029e52c44194cebb998ffb009be0c3c83715fbd1
Java
ericisme/ruiyi_base
/src/main/java/cn/unis/service/interfaces/IGameCenterService.java
UTF-8
13,900
1.695313
2
[]
no_license
package cn.unis.service.interfaces; import java.util.List; import org.scribe.model.Token; import cn.unis.transit.App; import cn.unis.transit.Arcade; import cn.unis.transit.BaseReturnValue; import cn.unis.transit.BaseReturnValues; import cn.unis.transit.ChargeToSycoin; import cn.unis.transit.Consumer; import cn.unis.transit.GameCenterDetailInfo; import cn.unis.transit.GameCenterSimpleInfo; import cn.unis.transit.UserDetailInfo; import cn.unis.transit.UserGameWallet; import cn.unis.transit.WaloGameSimpleInfo; import cn.unis.transit.exchange.ExchangeReturn; import cn.unis.transit.ticket.TicketBalance; import cn.unis.transit.ticket.TicketDebitReturns; import cn.unis.transit.ticket.TicketDebitRollBackReturns; import cn.unis.transit.token.ChargeToToken; import cn.unis.transit.token.TokenBalance; import cn.unis.transit.userWallet.Sycoin; import cn.unis.transit.userWallet.UserGameCenterTicket; import cn.unis.transit.userWallet.UserGameCenterWallet; import cn.unis.transit.userWallet.UserWallet; import cn.unis.transit.achievement.AchievementPaymentReturns; import cn.unis.transit.achievement.AchievementPaymentRollBackReturns; import cn.unis.transit.chargeRecord.Page; import cn.unis.transit.chargeRecord.SycoinExchangeRecord; import cn.unis.transit.chargeRecord.SycoinRechargeRecord; import cn.unis.transit.chargeRecord.TokensRechargeRecord; import cn.unis.transit.chargeRecord.TokensRechargeRecordNew; /** * walo游戏平台Oauth服务 管理类.service接口 * * @author eric */ public interface IGameCenterService { /** * 根据查询条件,查询值,获得会员kdy分页列表 * @param page_num * @param item_per_page * @param filter_key * @param filter_value * @return */ public BaseReturnValues<String> queryUserList(int page_num , int item_per_page, String filter_key, String filter_value ); /** * 获得全部会员kdy分页列表 * @param page_num * @param item_per_page * @return */ public BaseReturnValues<String> queryUserList(int page_num , int item_per_page); /** * 根据user_key,获得user 实体信息,string * @param user_key * @param fields fields=key,username,handle_name,grade,email,phone,timezone,country,lang,personal_status,registered_arcades,achievement_score,accumulated_ascore,registered_at,expire,status * @return */ public BaseReturnValue<UserDetailInfo> getUserDetailInfoByUserKey(String user_key, String fields); /** * 用户在某一个游场上的 代币数 根彩票数,还有last_update的时间 * @param user_key * @param game_center_key * @return */ public BaseReturnValue<UserGameCenterWallet> getBalanceByUserKeyAndGameCenterKey(String user_key, String game_center_key); /** * 根据game_center_key获得游戏列表 */ public BaseReturnValues<WaloGameSimpleInfo> getWaloArcadeGamesByGameCenterKey(String game_center_key); /** * 获得某个用户在某个游场,某个游戏的登录次数 */ public BaseReturnValues<WaloGameSimpleInfo> getUserLoginCountByGameCenterKeyAndGameConsumerKey(String user_key, String game_center_key, String game_consumber_key); /** *根据user_key,获得用户在各游场的钱包信息 */ public BaseReturnValue<UserWallet> getUserWalletsByUserKey(String user_key); /** *游场报表api,總派票/總投幣 (不同遊戲) *直接返回json. */ public String reprotTxByGame(String game_center_key); /** *游场报表api,指定日期(派票/投幣)(不同遊戲),指定游戏,日期格式 YYYY-MM-DD *直接返回json. */ public String game_daily_tx_report(String game_center_key, String begin_date, String until_date, String consumer_key); /** *游场报表api,指定日期(派票/投幣)(不同遊戲), 日期格式 YYYY-MM-DD *直接返回json. */ public String game_daily_tx_report(String game_center_key, String begin_date, String until_date); /** *個別機台派票/投币, 日期格式 YYYY-MM-DD *直接返回json. */ public String arcade_daily_tx_report(String cuk, String begin_date, String until_date); /** * 根据 gameConterKey 获得 游乐场 基本信息 * @param gameCenterKey * @return */ public String getGameCenterJsonByGameCenterKey(String gameCenterKey); /** * 取得 分数 html * @return */ public String getScoresHtml(); /** * 根据 gameConterKey 获得 游乐场 详细信息 * @param gameCenterKey */ public BaseReturnValue<GameCenterDetailInfo> getGameCenter(String gameCenterKey); /** * 根据 省代码 获得分页game_center列表 * * @param province_code * @param page_num * @param item_per_page * @return */ public BaseReturnValues<GameCenterSimpleInfo> getGameCentersByProvinceCode(String province_code, int page_num, int item_per_page); /** * 根据 市代码 获得分页game_center列表 * * @param province_code * @param page_num * @param item_per_page * @return */ public BaseReturnValues<GameCenterSimpleInfo> getGameCentersByCityCode(String city_code, int page_num, int item_per_page); /** * 根据 省代码 获得全部game_center列表 */ public BaseReturnValues<GameCenterSimpleInfo> getGameCentersByProvinceCode(String province_code); /** * 根据 市代码 获得全部game_center列表 */ public BaseReturnValues<GameCenterSimpleInfo> getGameCentersByCityCode(String city_code); /** * 根据game_center_key获得分页arcade列表 * * @param game_center_key * @param page_num * @param item_per_page * @return */ public BaseReturnValues<Arcade> getArcadeMachinesOfGameCenter(String game_center_key, int page_num, int item_per_page); /** * 获得所有walo app(app为consumer的上级) */ public BaseReturnValues<App> getAllApp(); /** * 获得所有充值consumer(游戏)列表 */ public List<Consumer> getAllChargeableConsumer(); /** * 根据user_key获得consumer列表 */ public BaseReturnValues<Consumer> getConsumersUserKey(String user_key); /** * 根据user_key获得充值consumer(游戏)列表 */ public BaseReturnValues<Consumer> getChargeableConsumerListByUserKey(String user_key); /** * 根据user_key查询用户的 游币钱包(以前叫世宇币) */ public BaseReturnValue<Sycoin> getSycoinByUserKey(String user_key); /** * 根据user_key查询用户的 实体币钱包 */ public BaseReturnValue<TokenBalance> getTokenBalanceByUserKey(String user_key); /** * 获得所有game_center */ public BaseReturnValues<GameCenterSimpleInfo> getAllGameCenter(); /** * 根据user_key, consumer_key获得钱包列表 */ public BaseReturnValues<UserGameWallet> getUserGameWalletListByUserKeyAndConsumerKey(String user_key, String consumer_key); /** * 根据user_key, consumer_key, game_center_key获得游戏钱包 */ public BaseReturnValue<UserGameWallet> getUserGameWallet(String user_key, String consumer_key, String game_center_key); /** * 根据user_key,game_center_key,获得用户在某个游场的彩票结余 */ public BaseReturnValue<UserGameCenterTicket> getTicketsByUserKeyAndGameCenterKey(String user_key, String game_center_key); /** * 根据consumer_key获得consumer_detail(游戏详细) */ public BaseReturnValue<Consumer> getConsumerDetail(String consumer_key); /** * 用户游币钱包(以前叫世宇币)充值 * @param user_key 要充值的用户key * @param amount 要充值的数量,游币(以前叫世宇币) * @param sign 加密签名,AES(json_data),json_data 例子:{"outTradeNo":"fsdfdsf88fhdsfhsda8fh3","date_time":"2013-12-12 10:10:10",payMoney":"100.05} * @return */ public BaseReturnValue<ChargeToSycoin> chargeToSycoin(String user_key, Integer amount, String sign ); /** * 用户游戏钱包充值 * @param user_key 要充值的用户key * @param consumer_key 要充值钱包的游戏key * @param game_center_key 要充值钱包的游场key * @param amount 要充值的数量,世宇币 * @param sign 加密签名,AES(json_data),json_data 例子:{"outTradeNo":"fsdfdsf88fhdsfhsda8fh3","date_time":"2013-12-12 10:10:10","payMoney":100.05} * @return */ public BaseReturnValue<ChargeToSycoin> chargeToGameToken(String user_key, String consumer_key, String game_center_key, Integer amount, String sign ); /** * 用户实体币钱包充值 * @param user_key 要充值的用户key * @param amount 要充值的数量,世宇币 * @param sign 加密签名,AES(json_data),json_data 例子:{"outTradeNo":"fsdfdsf88fhdsfhsda8fh3","date_time":"2013-12-12 10:10:10",payMoney":"100.05} * @return */ public BaseReturnValue<ChargeToToken> chargeToToken(String user_key, Integer amount, String sign ); /** * 取得3-legged 的RequestToken * @return */ public Token get3LeggedRequestToken(String callback_path); /** * 取得3-legged 的AccessToken * @param requestToken * @param oauth_verifier * @return */ public Token get3LeggedAccessToken(Token requestToken, String oauth_verifier); /** * walo帐号注销/登出 * @param accessToken 帐号登录后的accessToken. * @return */ public String logout3Legged(Token accessToken); /** * 用户详细资料,3-legged * @param accessToken 帐号登录后的accessToken. */ public BaseReturnValue<UserDetailInfo> getAccountInfo(Token accessToken); /** * 用户彩票结余,3-legged * @param accessToken 帐号登录后的accessToken. */ public BaseReturnValue<TicketBalance> getAccountTicketBalance(Token accessToken); /** * 彩票 扣减, 3-legged * @param accessToken 3-legged-accessToken * @param amount 要扣减的世宇彩票数目 * @return BaseReturnValue<AchievementPaymentReturns> * err_num=0时为成功,err_num=402时为彩票不够用于扣减 * 成功后TicketDebitRetuns里的tx_code用于退款使用,请保存到数据库 */ public BaseReturnValue<TicketDebitReturns> ticketDebit(Token accessToken, Integer amount); /** * 回退已扣减的 彩票,用于交易不成功时的退款, 3-legged * @param accessToken * @param tx_code * @return BaseReturnValue<AchievementPaymentReturns> * err_num=0 时为成功回退, * err_num=404 时为没找到对应的tx_code的扣减记录, * err_num=410 时为该tx_code已经被回退过了 */ public BaseReturnValue<TicketDebitRollBackReturns> ticketDebitRollBack(Token accessToken, String tx_code); /** * 用户实体币结余,3-legged */ public BaseReturnValue<TokenBalance> getAccountTokenBalance(Token accessToken); /** * 用户资料修,3-legged * @param accessToken 帐号登录后的accessToken. * @param edit_field 修改的字段,只允许修改handle_name,phone,personal_status * @param edit_value 要修改字段的值 */ public String editAccountProfile(Token accessToken, String edit_field, String edit_value, String original_handle_name); /** * 用户世宇币,3-legged */ public BaseReturnValue<Sycoin> getSycoin(Token accessToken); /** * 用户 世宇币,游场彩票,游戏钱包,3-legged */ public BaseReturnValue<UserWallet> getWallet(Token accessToken); /** * * 用户游戏币充值,使用世宇币充值游戏币,3-legged * * @param accessToken 3-legged-accessToken * @param amount 要充值 的世宇币数目 * @param consumer_key 要充值 的游戏key * @param game_center_key 要充值的游场key * @param rate 充值游戏代币比率 * @return */ public BaseReturnValue<ExchangeReturn> accountExchange(Token accessToken, Integer amount, String consumer_key, String game_center_key, Integer rate); /** * 世宇币充值记录,3-legged * @param accessToken 3-legged-accessToken * @param pg 页数 * @param rpp 每页条数 * @return */ public BaseReturnValue<Page<SycoinRechargeRecord>> sycoinRechargeReport(Token accessToken, Integer pg, Integer rpp); /** * 游戏币充值记录,3-legged * @param accessToken 3-legged-accessToken * @param pg 页数 * @param rpp 每页条数 * @return */ public BaseReturnValue<Page<TokensRechargeRecordNew>> tokensRechargeReport(Token accessToken, Integer pg, Integer rpp); /** * 世宇币兑换记录,3-legged * @param accessToken 3-legged-accessToken * @param pg 页数 * @param rpp 每页条数 * @return */ public BaseReturnValue<Page<SycoinExchangeRecord>> sycoinExchangeReport(Token accessToken, Integer pg, Integer rpp); /** * 世宇积分 扣减, 3-legged,已不用 * @param accessToken 3-legged-accessToken * @param amount 要扣减的世宇积分数目 * @return BaseReturnValue<AchievementPaymentReturns> * err_num=0 时为成功, * err_num=402 时为积分不够用于扣减, * 成功后AchievementPaymentReturns里的tx_code用于退款使用,请保存到数据库 */ public BaseReturnValue<AchievementPaymentReturns> achievementTxPayment(Token accessToken, Integer amount); /** * 回退已扣减的 世宇积分,用于交易不成功时的退款, 3-legged,已不用 * @param accessToken * @param tx_code * @return BaseReturnValue<AchievementPaymentReturns> * err_num=0 时为成功回退, * err_num=404 时为没找到对应的tx_code的扣减记录, * err_num=410 时为该tx_code已经被回退过了 */ public BaseReturnValue<AchievementPaymentRollBackReturns> achievementTxPaymentRollBack(Token accessToken, String tx_code); /** * 验证 一次性登录密码,并返回accessToken(需要用AES解密,密码IV与充值使用的一样) * @param user_key 用户key * @param ls 一次性登录密码 * @return */ public BaseReturnValue<String> getAccessTokenForSSO(String user_key, String ls); /** * test json string */ public String testJsonString(); }
true
9e16be60a943cac6ad7da1134808bca072577cf3
Java
ResearchInMotion/Rhombus-Java
/Unboxing/src/bright/InterviewQuestion/loop.java
UTF-8
329
2.78125
3
[]
no_license
package bright.InterviewQuestion; public class loop { public static void main(String[] args) { // TODO Auto-generated method stub int i=40; while(i<=100){ System.out.println("increment i :" +i); ++i; } /*decrement*/ int a=50; while(a>=10){ System.out.println("dec a" +a); --a; } } }
true
7aa51ac21cb6afca4893a551a9aeb572d44c58dc
Java
soon14/configcenter
/center/src/main/java/com/asiainfo/configcenter/center/entity/complex/CXAppInfoEntity.java
UTF-8
1,526
2.03125
2
[ "MIT" ]
permissive
package com.asiainfo.configcenter.center.entity.complex; import javax.persistence.Entity; import javax.persistence.Id; /** * 应用信息视图实体类 * Created by bawy on 2018/7/25 15:29. */ @Entity public class CXAppInfoEntity { private int id; private String appName; private String description; private int creator; private String createTime; private String creatorName; private String updateTime; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getCreator() { return creator; } public void setCreator(int creator) { this.creator = creator; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getCreatorName() { return creatorName; } public void setCreatorName(String creatorName) { this.creatorName = creatorName; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } }
true
e132346c136be0ae6cdc224fa4a63068fb0bd742
Java
Iscbr/viajesBackend
/src/main/java/com/api/travel/Entity/Ciudad.java
UTF-8
1,055
2.015625
2
[]
no_license
package com.api.travel.Entity; import com.api.travel.Util.View; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "ciudad") @Data public class Ciudad implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_ciudad", nullable = false, unique = true, updatable = false) @JsonView({View.Summary.class, View.Airport.class}) private Integer id; @Column(name = "nombre", length = 50) @JsonView({View.Summary.class, View.Airport.class}) private String nombre; @Column(name = "descripcion", length = 300) @JsonView({View.Summary.class, View.Airport.class}) private String descripcion; @Column(name = "activo") @JsonView(View.Summary.class) private Boolean activo; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "id_estado") @JsonView(View.Airport.class) private Estado estado; }
true
09e0190fc0b048176e888cc5a91414650b845bb8
Java
Ali-Git/DataStructure-Algorithms
/dynamic_programming/src/dynamic_programming/MinCoinGetSum.java
UTF-8
1,110
2.9375
3
[]
no_license
package dynamic_programming; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class MinCoinGetSum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc-- >0){ int v = sc.nextInt(); int n = sc.nextInt(); int res[] = new int[v+1]; for(int j=1; j<=v; j++){ res[j]=Integer.MAX_VALUE; } for(int i=0; i<n; i++) { int temp=sc.nextInt(); for(int j=1; j<=v; j++) { if(j>=temp) { int min=res[j]; if(res[j-temp]!=Integer.MAX_VALUE && res[j-temp]+1<min) min=res[j-temp]+1; res[j]=min; } } } if(res[v]==Integer.MAX_VALUE) System.out.println(-1); else System.out.println(res[v]); } } } /* 1 1785 23 56 51 13 57 30 10 86 7 6 62 55 2 82 50 89 94 91 64 16 61 72 35 3 Op-20 yours-19 1 11 3 3 5 9 OP-2 Yours-3 1 7 2 2 1 OP-4 1 13 4 7 2 3 6 OP-2 1 8777 5 86 7 43 67 6 OP-103 76 */
true
098564a2503c200d627b833069430e9c5216449d
Java
dayu07/activiti
/src/main/java/com/hx/activiti/demo/dao/ActCustomFormFieldDao.java
UTF-8
434
1.78125
2
[]
no_license
package com.hx.activiti.demo.dao; import com.hx.activiti.demo.model.ActCustomFormField; import java.util.List; public interface ActCustomFormFieldDao { List<ActCustomFormField> getByForm(String formId); ActCustomFormField getById(String fieldId); int save(ActCustomFormField field); int saveBatch(List<ActCustomFormField> list); int delByFormId(String formId); int update(ActCustomFormField field); }
true
2276ce411bedacce4217b7f4602fb570f3ebf077
Java
Hungka/doan
/MyPlaceAround/app/src/main/java/gson/Photo.java
UTF-8
157
1.523438
2
[]
no_license
package gson; import com.google.gson.JsonElement; /** * Created by TranManhHung on 04-Apr-16. */ public class Photo { JsonElement photo_reference; }
true
e76055e215a7a2aa2bd473784eb7071793bb7a05
Java
chocku1989/CoreJava
/training/src/com/training/weektwo/Deliverymain.java
UTF-8
576
2.78125
3
[]
no_license
package com.training.weektwo; import java.util.Scanner; public class Deliverymain { public static void main(String[] args) { System.out.println(Thread.currentThread().toString()); Scanner sc = new Scanner(System.in); System.out.println("Enter the Bolwer"); String Bolwer = sc.next(); System.out.println("Enter the Batsman name"); String Bastamn = sc.next(); Delivery d = new Delivery(); d.displayDeliveryDetails(Bolwer, Bastamn); System.out.println("Enter the run"); Long runs = sc.nextLong(); sc.close(); d.displayDeliveryDetails(runs); } }
true
1794caa1b8f490cd0bc62dd61b6f027f63a675fb
Java
RegrasMotor/horas
/motor-horaspersonas/src/test/java/unitary/HorasExtrasEspeciales.java
UTF-8
3,323
2.265625
2
[]
no_license
package unitary; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import base.JUnitBase; import com.prosegur.rulesEngine.factsmodel.horaspersonas.FactEscala; import com.prosegur.rulesEngine.factsmodel.horaspersonas.FactEsquemaOperativo; import com.prosegur.rulesEngine.factsmodel.horaspersonas.FactResponse; public class HorasExtrasEspeciales extends JUnitBase { private final static String rulesFile = "rules/horaspersonas/BRA/Horas Extras especiales.drl"; @BeforeClass public static void initialize() { initialize (rulesFile); } @Test public void comprobarAccion1() { //Escala SDF logger.setFileName( logsDir + this.getClass().getSimpleName() + ".comprobarAccion1" ); FactResponse factResponse = getResponse1(); ksession.insert(factResponse); ksession.insert(getEscalaSDF()); ksession.insert(getEsquema()); ksession.fireAllRules(); assertEquals(0, factResponse.getHorasExtrasEspeciales(), delta); } @Test public void comprobarAccion2() { //Escala SDF logger.setFileName( logsDir + this.getClass().getSimpleName() + ".comprobarAccion2" ); FactResponse factResponse = getResponse1(); ksession.insert(factResponse); ksession.insert(getEscalaCHNIF()); ksession.insert(getEsquema()); ksession.fireAllRules(); assertEquals(0, factResponse.getHorasExtrasEspeciales(), delta); } @Test public void comprobarAccion3() { //Con horas Extras Por persona logger.setFileName( logsDir + this.getClass().getSimpleName() + ".comprobarAccion3" ); FactResponse factResponse = getResponse1(); ksession.insert(factResponse); ksession.insert(getEscalaCHNIF()); ksession.fireAllRules(); assertEquals(60, factResponse.getHorasExtrasEspeciales(), delta); } @Test public void comprobarAccion4() { //Resto casos logger.setFileName( logsDir + this.getClass().getSimpleName() + ".comprobarAccion4" ); FactResponse factResponse = getResponse2(); ksession.insert(factResponse); ksession.insert(getEscalaCHNIF()); ksession.fireAllRules(); assertEquals(0, factResponse.getHorasExtrasEspeciales(), delta); } private FactResponse getResponse_datosComunes() { FactResponse factResponse = new FactResponse(); factResponse.setHorasExtras50Xpersona(20f); factResponse.setNumeroRealPersonas(3d); return factResponse; } private FactResponse getResponse1() { FactResponse factResponse = getResponse_datosComunes(); factResponse.setHorasExtrasXpersona(10f); return factResponse; } private FactResponse getResponse2() { FactResponse factResponse = getResponse_datosComunes(); factResponse.setHorasExtrasXpersona(0f); return factResponse; } private FactEscala getEscalaSDF() { FactEscala factEscala = new FactEscala(); factEscala.setId("SDF"); factEscala.setMediaJornada(true); return factEscala; } private FactEscala getEscalaCHNIF() { FactEscala factEscala = new FactEscala(); factEscala.setId("CHNIF"); factEscala.setMediaJornada(true); return factEscala; } private FactEsquemaOperativo getEsquema() { FactEsquemaOperativo factEsquemaOperativo = new FactEsquemaOperativo(); factEsquemaOperativo.setMediaJornada(true); return factEsquemaOperativo; } }
true
4798983792549d98659ac2da0799063e6e283222
Java
triceo/robozonky
/robozonky-app/src/test/java/com/github/robozonky/app/events/SessionEventsTest.java
UTF-8
6,283
1.929688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 The RoboZonky 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.github.robozonky.app.events; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.mockito.Mockito.*; import java.time.Duration; import java.util.UUID; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import com.github.robozonky.api.notifications.EventListener; import com.github.robozonky.api.notifications.ExecutionCompletedEvent; import com.github.robozonky.api.notifications.LoanDelinquent90DaysOrMoreEvent; import com.github.robozonky.api.remote.entities.Investment; import com.github.robozonky.api.remote.entities.Loan; import com.github.robozonky.app.events.impl.EventFactory; import com.github.robozonky.app.tenant.PowerTenant; import com.github.robozonky.internal.SessionInfoImpl; import com.github.robozonky.internal.remote.Zonky; import com.github.robozonky.test.mock.MockInvestmentBuilder; import com.github.robozonky.test.mock.MockLoanBuilder; class SessionEventsTest extends AbstractEventLeveragingTest { private final Zonky zonky = harmlessZonky(); private final PowerTenant tenant = mockTenant(zonky, false); private final PowerTenant tenantDry = mockTenant(zonky, true); @Test void lazyFireReturnsFuture() { final Loan l = MockLoanBuilder.fresh(); final Investment i = MockInvestmentBuilder.fresh(l, 200) .build(); final CompletableFuture<?> result = SessionEvents.forSession(mockSessionInfo()) .fire(EventFactory.loanNoLongerDelinquentLazy(() -> EventFactory.loanNoLongerDelinquent(i, l))); result.join(); // make sure it does not throw assertThat(getEventsRequested()).hasSize(1); } @Test void fireReturnsFuture() { final Loan l = MockLoanBuilder.fresh(); final Investment i = MockInvestmentBuilder.fresh(l, 200) .build(); final CompletableFuture<?> result = SessionEvents.forSession(mockSessionInfo()) .fire(EventFactory.loanNoLongerDelinquent(i, l)); result.join(); // make sure it does not throw assertThat(getEventsRequested()).hasSize(1); } @Test void identifiesEventTypeWhenClass() { Loan l = MockLoanBuilder.fresh(); Investment i = MockInvestmentBuilder.fresh(l, 200) .build(); final LoanDelinquent90DaysOrMoreEvent e = EventFactory.loanDelinquent90plus(i, l); assertThat(SessionEvents.getImplementingEvent(e.getClass())) .isEqualTo(LoanDelinquent90DaysOrMoreEvent.class); } @Test void identifiesEventTypeWhenInterface() { assertThat(SessionEvents.getImplementingEvent(LoanDelinquent90DaysOrMoreEvent.class)) .isEqualTo(LoanDelinquent90DaysOrMoreEvent.class); } @Test void registersListeners() { final EventFiringListener e = mock(EventFiringListener.class); assertThat(Events.forSession(tenant) .addListener(e)).isTrue(); assertThat(Events.forSession(tenant) .addListener(e)).isFalse(); assertThat(Events.forSession(tenant) .removeListener(e)).isTrue(); assertThat(Events.forSession(tenant) .removeListener(e)).isFalse(); assertThat(Events.forSession(tenant) .addListener(e)).isTrue(); } @SuppressWarnings("unchecked") @Test void callsListeners() { final ExecutionCompletedEvent s = EventFactory.executionCompleted(mockPortfolioOverview()); final SessionEvents events = Events.forSession(tenant); final EventFiringListener e = mock(EventFiringListener.class); final EventListener<ExecutionCompletedEvent> l = mock(EventListener.class); events.addListener(e); events.injectEventListener(l); final CompletableFuture<?> r = events.fire(s); assertTimeoutPreemptively(Duration.ofSeconds(5), r::join); assertThat(getEventsRequested()).isNotEmpty(); assertThat(getEventsReady()).isNotEmpty(); assertThat(getEventsFired()).isNotEmpty(); verify(l).handle(s, tenant.getSessionInfo()); } @SuppressWarnings("unchecked") @Test void callsListenersOnError() { final ExecutionCompletedEvent s = EventFactory.executionCompleted(mockPortfolioOverview()); final SessionEvents events = Events.forSession(tenant); final EventListener<ExecutionCompletedEvent> l = mock(EventListener.class); doThrow(IllegalStateException.class).when(l) .handle(any(), any()); events.injectEventListener(l); final CompletableFuture<?> r = events.fire(s); assertTimeoutPreemptively(Duration.ofSeconds(5), r::join); assertThat(this.getEventsFailed()).isNotEmpty(); } @Test void differentInstancesForDifferentUsernames() { final SessionEvents a = Events.forSession(tenant); assertThat(a.getSessionInfo() .getUsername()).isEqualTo(tenant.getSessionInfo() .getUsername()); final SessionEvents b = Events.forSession(tenantDry); assertThat(a.getSessionInfo() .getUsername()).isEqualTo(tenantDry.getSessionInfo() .getUsername()); assertThat(a) .isNotNull() .isSameAs(b); final PowerTenant t3 = mockTenant(); when(t3.getSessionInfo()).thenReturn(new SessionInfoImpl(UUID.randomUUID() .toString())); final SessionEvents c = Events.forSession(t3); assertThat(c.getSessionInfo()).isEqualTo(t3.getSessionInfo()); assertThat(a) .isNotNull() .isNotSameAs(c); } }
true
da4aa2bc953f22c784d5dc311b5d789018cffd59
Java
blyons3/vogella-tutorials
/junitgradle/com.vogella.unittest/lib/src/test/java/com/vogella/unittest/sortmethods/OrderAnnotationDemoTest.java
UTF-8
426
2.125
2
[]
no_license
package com.vogella.unittest.sortmethods; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class OrderAnnotationDemoTest { @Test @Order(1) void firstOne() { // test something here } @Test @Order(2) void secondOne() { // test something here } }
true
221a34e89cedeea5b1c539a202890a796d77de9f
Java
AndroidCodeJustFun/AndroidWidgets
/app/src/main/java/com/xiao/demo/arouter/ArouterActivity.java
UTF-8
710
1.9375
2
[ "Apache-2.0" ]
permissive
package com.xiao.demo.arouter; import android.support.v7.widget.CardView; import android.widget.Toast; import com.xiao.demo.R; import com.xiao.demo.base.BaseActivity; import butterknife.BindView; import butterknife.OnClick; /** * Created by xiao on 2017/9/4. */ public class ArouterActivity extends BaseActivity { @BindView(R.id.arouter_card_basicinfo) CardView arouterCardBasicinfo; @Override public int layoutRes() { return R.layout.activity_arouter; } @Override public void initView() { } @Override public void initData() { } @OnClick(R.id.arouter_card_basicinfo) public void onViewClicked() { Toast.makeText(this, "Go Basic Introduce Page", Toast.LENGTH_SHORT).show(); } }
true
c7d42496cbbc15917a761a657fa3699e8f10e4d6
Java
Raymond-JRLin/LintCode-Solutions-and-Notes
/majority-number-iii.java
UTF-8
2,507
3.828125
4
[]
no_license
// 48. Majority Number III // 中文English // Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. // // Find it. // // Example // Example 1: // // Input: [3,1,2,3,2,3,3,4,4,4] and k=3, // Output: 3. // Example 2: // // Input: [1,1,2] and k=3, // Output: 1. // Challenge // O(n) time and O(k) extra space // // Notice // There is only one majority number in the array. // public class Solution { /* * @param nums: A list of integers * @param k: An integer * @return: The majority number */ public int majorityNumber(List<Integer> nums, int k) { // write your code here if (nums == null || nums.size() == 0) { return -1; } int n = nums.size(); // 通过上一题 II, 再看 O(k) space, 那么能够想到要存 top(k - 1) 来进行 kk抵消, 可以使用 map 来存储 // 注意的是: 当 k - 1 个存储位置用完了后, 如果处理? 就是把所有的 count 都要 - 1, 然后移除变为 0 的 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // use map to record top(k - 1) for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { // new number, we need to check if map is full if (map.size() >= k) { removeCount(map); } map.put(num, 1); } } // reset all count to 0 for (int key : map.keySet()) { map.put(key, 0); } // loop given list to record absolute count of keys for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); if (map.get(num) > n / k) { return num; } } } return -1; } private void removeCount(Map<Integer, Integer> map) { Set<Integer> remove = new HashSet<Integer>(); for (int key : map.keySet()) { map.put(key, map.get(key) - 1); // we cannot delete right now, because of thread safety // if (map.get(key) == 0) { // map.remove(key); // } if (map.get(key) == 0) { remove.add(key); } } for (int key : remove) { map.remove(key); } } }
true
a79f35bf505eb36ab5daacce52f95c8cd8e31f20
Java
juankab532/Genionic
/Workspace/ISML-mde/tool/co.edu.javeriana.isml/src-gen/co/edu/javeriana/isml/isml/impl/BoolValueImpl.java
UTF-8
718
1.6875
2
[ "Apache-2.0" ]
permissive
/** */ package co.edu.javeriana.isml.isml.impl; import co.edu.javeriana.isml.isml.BoolValue; import co.edu.javeriana.isml.isml.IsmlPackage; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Bool Value</b></em>'. * <!-- end-user-doc --> * * @generated */ public class BoolValueImpl extends LiteralValueImpl implements BoolValue { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BoolValueImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return IsmlPackage.Literals.BOOL_VALUE; } } //BoolValueImpl
true
be65f7554b7c0b71b8a9c8b36bddb4c78169a70b
Java
samlindsaylevine/advent
/src/test/java/advent/year2015/day12/JsonDocumentTest.java
UTF-8
2,172
2.984375
3
[]
no_license
package advent.year2015.day12; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class JsonDocumentTest { @Test public void arrayToSix() { JsonDocument document = new JsonDocument("[1, 2, 3]"); assertEquals(6, document.sumAllNumbers()); } @Test public void mapToSix() { JsonDocument document = new JsonDocument("{\"a\":2,\"b\":4}"); assertEquals(6, document.sumAllNumbers()); } @Test public void nestedArrayToThree() { JsonDocument document = new JsonDocument("[[[3]]]"); assertEquals(3, document.sumAllNumbers()); } @Test public void nestedMapToThree() { JsonDocument document = new JsonDocument("{\"a\":{\"b\":4},\"c\":-1}"); assertEquals(3, document.sumAllNumbers()); } @Test public void nestedArrayToZero() { JsonDocument document = new JsonDocument("{\"a\":[-1,1]}"); assertEquals(0, document.sumAllNumbers()); } @Test public void nestedMapToZero() { JsonDocument document = new JsonDocument("[-1,{\"a\":1}]"); assertEquals(0, document.sumAllNumbers()); } @Test public void emptyArray() { JsonDocument document = new JsonDocument("[]"); assertEquals(0, document.sumAllNumbers()); } @Test public void emptyMap() { JsonDocument document = new JsonDocument("{}"); assertEquals(0, document.sumAllNumbers()); } @Test public void arrayToSixNonRed() { JsonDocument document = new JsonDocument("[1, 2, 3]"); assertEquals(6, document.sumAllNonRedNumbers()); } @Test public void middleObjectNonRed() { JsonDocument document = new JsonDocument("[1,{\"c\":\"red\",\"b\":2},3]"); assertEquals(4, document.sumAllNonRedNumbers()); } @Test public void entireStructureNonRed() { JsonDocument document = new JsonDocument("{\"d\":\"red\",\"e\":[1,2,3,4],\"f\":5}"); assertEquals(0, document.sumAllNonRedNumbers()); } @Test public void inArrayNonRed() { JsonDocument document = new JsonDocument("[1,\"red\",5]"); assertEquals(6, document.sumAllNonRedNumbers()); } @Test public void arrayInObjectNonRed() { JsonDocument document = new JsonDocument("{\"a\":[1,\"red\",5]}"); assertEquals(6, document.sumAllNonRedNumbers()); } }
true
d99f9616dbb7da0ba2a03d79563bd66034a91791
Java
TinderTeam/Fuego
/code/Fuego/src/cn/tinder/fuego/webservice/struts/bo/search/AssetsStatusSearchInitPageBo.java
UTF-8
1,412
1.984375
2
[]
no_license
package cn.tinder.fuego.webservice.struts.bo.search; import java.util.ArrayList; import java.util.List; import cn.tinder.fuego.webservice.struts.bo.assets.AssetsInfoBo; import cn.tinder.fuego.webservice.struts.bo.assets.AssetsPageBo; public class AssetsStatusSearchInitPageBo { private List<String> deptList; //Department private List<String> typeList; //Assets Type private List<String> techList; //status private AssetsPageBo pageBo = new AssetsPageBo(); public AssetsStatusSearchInitPageBo(){ pageBo.setAssetsList(new ArrayList<AssetsInfoBo>()); } public AssetsStatusSearchInitPageBo(AssetsPageBo bo){ pageBo=bo; } public List<String> getDeptList() { return deptList; } public void setDeptList(List<String> deptList) { this.deptList = deptList; } public List<String> getTypeList() { return typeList; } public void setTypeList(List<String> typeList) { this.typeList = typeList; } public List<String> getTechList() { return techList; } public AssetsPageBo getPageBo() { return pageBo; } @Override public String toString() { return "AssetsStatusSearchInitPageBo [deptList=" + deptList + ", typeList=" + typeList + ", techList=" + techList + ", pageBo=" + pageBo + "]"; } public void setPageBo(AssetsPageBo pageBo) { this.pageBo = pageBo; } public void setTechList(List<String> techList) { this.techList = techList; } }
true
42b2da5d47b1c9044e3163c17b7399ce6b231a22
Java
Tywacol/imhof_maps
/src/ch/epfl/imhof/osm/OSMEntity.java
UTF-8
2,946
2.984375
3
[ "MIT" ]
permissive
package ch.epfl.imhof.osm; import ch.epfl.imhof.Attributes; /** * @author Pierre Gabioud (247216) * @author Corto Callerisa (251769) * * Classe mère de toutes les classes représentant les entités OpenStreetMap. */ public abstract class OSMEntity { private final long id; private Attributes attributes; /** * @param id * l'identifiant unique de l'entité OSM * * @param attributes * les attributs de l'entité */ public OSMEntity(long id, Attributes attributes) { this.id = id; this.attributes = attributes; } /** * @return l'identifiant unique de l'entité */ public long id() { return id; } /** * @return retourne les attributs de l'entité */ public Attributes attributes() { return attributes; } /** * @param key * l'identifiant de l'attribut dont on teste l'appartenance à * l'entité OSM * * @return retourne VRAI si et seulement si l'entité possède l'attribut * passé en argument, FAUX sinon */ public boolean hasAttribute(String key) { return attributes.contains(key); } /** * @param key * l'identifiant de l'attribut * * @return retourne l'attribut correspondant à l'identifiant, ou null si * celui-ci n'existe pas */ public String attributeValue(String key) { return attributes.get(key); } /** * Le squelette de tout les batisseurs des classes héritant de * OSMEntity. */ public abstract static class Builder { protected final long id; protected Attributes.Builder attributes = new Attributes.Builder(); private boolean incomplete = false; /** * @param id * entier identifiant une entité OSM * * construit un batisseur pour une entite OSM identifiée par * l'entier donné */ public Builder(long id) { this.id = id; } /** * * Ajoute l'association (clef, valeur) donnée a l'ensemble d'attributs * de l'entité en cours de construction. Si un attribut de même nom * avait déjà été ajouté précédemment, sa valeur est remplacée par celle * donnée * * @param key * clef associée à une valeur, toutes deux données à * l'ensemble d'attributs de l'entité * * @param value * valeur associée à une clef, toutes deux données à * l'ensemble d'attributs de l'entité * */ public void setAttribute(String key, String value) { attributes.put(key, value); } /** * Declare que l'entité en cours de construction est incomplète. */ public void setIncomplete() { incomplete = true; } /** * @return VRAI si et seulement si l'entité en cours de * construction est incomplète */ public boolean isIncomplete() { return incomplete; } } }
true
4ba8a1bc38caae2577d2b05c77c61a3ec9d9416a
Java
jw980806/java_class
/src/myobj/game/RerollDice.java
UHC
4,171
3.375
3
[]
no_license
package myobj.game; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.Set; public class RerollDice { private Random ran; private static int DICE_FACET = 6; private static int NUM_OF_DICE = 5; private final static Set<Set<Integer>> SMALL_CASES; private final static Set<Set<Integer>> LARGE_CASES; static { LARGE_CASES = new HashSet<>(); for (int i = 1; i <= 3; ++i) { Set<Integer> large = new HashSet<>(4); Collections.addAll(large, i, i+1, i+2, i+3, i+4); LARGE_CASES.add(large); } SMALL_CASES = new HashSet<>(); for (int i = 1; i <= 3; ++i) { Set<Integer> small = new HashSet<>(4); Collections.addAll(small, i, i+1, i+2, i+3); SMALL_CASES.add(small); } } private List<Integer> dices; // 5 ֻ Ʈ private List<Integer> counts; // ڰ ߴ Ʈ private String made; public RerollDice() { ran = new Random(); made = "UNCHECKED"; // ֻ 5 ̻ þ ʱ ÷ 뷮 5 Ѵ // # ArrayList ʱ 뷮 Ǹ 뷮 1.5辿 Ų dices = new ArrayList<>(NUM_OF_DICE); counts = new ArrayList<>(DICE_FACET); Collections.addAll(dices, 0,0,0,0,0); Collections.addAll(counts, 0,0,0,0,0,0); } private void count() { for (int i = 0; i < DICE_FACET; ++i) { int dice_num = i + 1; counts.set(i, Collections.frequency(dices, dice_num)); } } private String check() { // check by count if (counts.contains(5)) { return "FIVE DICE!!"; } else if (counts.contains(4)) { return "FOUR DICE!!"; } else if (counts.contains(2) && counts.contains(3)) { return "FULL HOUSE!!!"; } // check by dices for (Set<Integer> ls : LARGE_CASES) { if (dices.containsAll(ls)) { return "LARGE STRAIGHT!!"; } } for (Set<Integer> ss : SMALL_CASES) { if (dices.containsAll(ss)) { return "SMALL STRAIGHT!!"; } } return "NO MATCHES"; } public void roll() { for (int i = 0; i < NUM_OF_DICE; ++i) { dices.set(i, ran.nextInt(DICE_FACET)+1); } count(); System.out.print(dices + " : "); System.out.println(check()); //System.out.println(" Ƚ : " + counts); // System.out.println("You Want ReRoll?"); // String answer = new Scanner(System.in).next(); // if (answer.equals("yes")) { // System.out.println("Put Number"); // String num = new Scanner(System.in).next(); // reroll(num); // } } public void reroll(String num) { // 034 posit {0, 3, 4} //System.out.println(dices + " : "); //int[] posit = new int[num.length()]; Set<Integer> posit = new HashSet<>(num.length()); for (int i = 0; i < num.length(); ++i) { posit.add((int) num.charAt(i)); //dices.remove(posit[i]); } for (int i : posit) { int change = ran.nextInt(DICE_FACET)+1; dices.set(i-1, change); System.out.printf("DICE %d HAS CHANGED : %d\n",i, change); } // System.out.println(dices + " : "); count(); System.out.println(dices + " : "); //System.out.println(check()); } public void print() { System.out.print(dices + " : "); if (made.equals("UNCHECKED")) { made = check(); } System.out.println(made); } public void reRoll(Set<Integer> rerolls) { if (rerolls.size() == 0) { System.out.println("NOTING"); return; } made = "UNCHECKED"; for (int i : rerolls) { int to_change = ran.nextInt(DICE_FACET) + 1; dices.set(i-1, to_change); System.out.printf("DICE %d HAS CHANGED : %d\n",i, to_change); } count(); print(); } public static void main(String[] args) { RerollDice dice01 = new RerollDice(); // for (int i = 0; i < 100; ++i) { // dice01.roll(); // } dice01.roll(); //dice01.reRoll(rerolls); } }
true
67ce63f5641a3a96ea845690d905da757eb97d3d
Java
SeekerGalahad/JavaDesignPattern
/src/com/design/training/builder/person/PersonBuilder.java
UTF-8
777
2.96875
3
[]
no_license
package com.design.training.builder.person; /** * @author Wagic * @Description: * @Date: 2019-01-08 14:24 by Wagic 创建 */ public abstract class PersonBuilder { protected Graphics g; protected Pen p; public PersonBuilder(Graphics g, Pen p) { this.g = g; this.p = p; } public Graphics getG() { return g; } public void setG(Graphics g) { this.g = g; } public Pen getP() { return p; } public void setP(Pen p) { this.p = p; } public abstract void buildHead(); public abstract void buildBody(); public abstract void buildArmLeft(); public abstract void buildArmRight(); public abstract void buildLegLeft(); public abstract void buildLegRight(); }
true
8dbe13b911d99452bcb0ad9e90081ff7b5f176e5
Java
Drakmah/BotonVolver
/app/src/main/java/com/echolima/botonvolver/MainActivity.java
UTF-8
1,245
2.625
3
[]
no_license
package com.echolima.botonvolver; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*Button botonBienvenida = (Button) findViewById(R.id.btnBotonBienvenida); botonBienvenida.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Código a ejecutar Intent linkActivity2 = new Intent(MainActivity.this, Main2Activity.class); startActivity(linkActivity2); } });*/ } // Una forma más sencilla para hacer botones es declarar los métodos en MainActivity (public) y luego // añadir en el xml correspondiente el atributo Onclick = "llamar_al_metodo" public void irSegundaActividad(View v){// porque se le pasa como parametro un view?? Intent linkActivity2 = new Intent(this, Main2Activity.class); startActivity(linkActivity2); } }
true
2fb842faa4136f2a850d99afe74a37fb255658fd
Java
Softtek-QA/softtek-framework-leroy
/Projetos/Automação/va.testes.funcionais/src/main/java/va/testes/funcionais/md/AUTDataLoader.java
UTF-8
890
2.765625
3
[]
no_license
package va.testes.funcionais.md; import java.io.IOException; import java.nio.file.Paths; public class AUTDataLoader { public static java.util.HashMap<String, String> carregarParametros(String fileNameFull) throws IOException{ java.util.HashMap<String,String> params = new java.util.HashMap<String,String>(); if(!java.nio.file.Files.exists(Paths.get(fileNameFull))) { java.nio.file.Files.createFile(Paths.get(fileNameFull)); } java.util.List<String> linhas = java.nio.file.Files.readAllLines(Paths.get(fileNameFull)); System.out.println("INFO: CARREGANDO ARQUIVO DE DADOS DO SISTEMA"); for(String ln: linhas) { String campo = ln.split("=")[0]; String valor = ln.split("=")[1]; params.put(campo, valor); System.out.println(ln); } System.out.println(params); return params; } }
true
236489d843cca24bf5546fea9fc5e812a76c2324
Java
hd19901110/jeecms1.4.1test
/jeecms-common/src/main/java/com/jeecms/common/wechat/bean/response/applet/GetTemplateListResponse.java
UTF-8
2,263
2.359375
2
[]
no_license
package com.jeecms.common.wechat.bean.response.applet; import java.util.List; /** * 获取代码模版库中的所有小程序代码模版 返回数据 * @Description: * @author wulongwei * @date 2018年11月2日 下午2:30:07 */ public class GetTemplateListResponse extends BaseAppletResponse{ private List<TemplateList> templateList; @Override public String toString() { return "GetTemplateListResponse [template_list=" + templateList + "]"; } public List<TemplateList> getTemplateList() { return templateList; } public void setTemplateList(List<TemplateList> templateList) { this.templateList = templateList; } public GetTemplateListResponse(List<TemplateList> templateList) { super(); this.templateList = templateList; } public static class TemplateList{ /** 说开发者上传草稿时间 */ private String createTime; /** 模版版本号,开发者自定义字段 */ private String userVersion; /** 模版描述 开发者自定义字段 */ private String userDesc; /** 模版id */ private String templateId; public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUserVersion() { return userVersion; } public void setUserVersion(String userVersion) { this.userVersion = userVersion; } public String getUserDesc() { return userDesc; } public void setUserDesc(String userDesc) { this.userDesc = userDesc; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } @Override public String toString() { return "TemplateList [create_time=" + createTime + ", user_version=" + userVersion + ", user_desc=" + userDesc + ", template_id=" + templateId + "]"; } public TemplateList(String createTime, String userVersion, String userDesc, String templateId) { super(); this.createTime = createTime; this.userVersion = userVersion; this.userDesc = userDesc; this.templateId = templateId; } public TemplateList() { super(); } } }
true
82c709a79c0af37fef2a258538cfd9620251663a
Java
Teo-KJ/MOBLIMA-Movie-Information-and-Booking-System
/src/Presenter/MenuSelection.java
UTF-8
514
2.78125
3
[]
no_license
package Presenter; import java.util.Scanner; public class MenuSelection { static Scanner sc = new Scanner(System.in); public static boolean select_choice(int first, int last, int choice) { if ((choice >= first) && (choice <= last)) { return true; } else return false; } public static String passChoiceString(String... string) { for(String s: string) System.out.println(s); Scanner sc = new Scanner(System.in); String choice = sc.nextLine(); return choice; } }
true
8eb212e4db44d7bbaa5fb2626854d53188325809
Java
yuede/crowds
/src/test/java/CrowdsTest.java
UTF-8
11,529
2.078125
2
[]
no_license
package test.java; import java.io.IOException; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import org.graphstream.algorithm.community.MobileMarker; import main.java.Crowds; public class CrowdsTest { /** * @param args */ public static void main(String[] args) { System.out.println(args.length); if (args.length < 2) { args = new String[]{ "--inputFile", // "/Users/agata/Documents/PhD/sumo_scenarios/Kirchberg/kirchberg_300.dgs", // "/Users/agata/Documents/PhD/sumo_scenarios/Manhattan/final_10-20.dgs", // "/Users/agata/Documents/PhD/sumo_scenarios/Luxembourg_6-8/sumoOutput/vanet.dgs", "/Users/agata/shared/thesis_scenarios/highway_congestion/crowds/input/vanet.dgs", // "/Users/agata/shared/thesis_scenarios/higway_nocongestion/network/input/vanet.dgs", // "/Users/agata/Documents/PhD/sumo_scenarios/twolanes_long_120kmph_600/vanet.dgs", "--communityAlgorithmName", "SandSharc_copy_linkduration" , // "MySandSharc4_hybrid", // "SandSharc_copy_hybrid", "--congestionAlgorithmName", "CongestionMeasure", "--goal", "communities", "--startStep", "0", "--endStep", "600", "--outputDir", "/Users/agata/workspace/crowds/output/eclipse/", "--speedHistoryLength", "90", "--speedType", "timemean", "--numberOfIterations", "1"}; } HashMap<String, String> programArgs = parseArgs(args); HashMap<MobileMarker, String> markers = initializeMarkers(); if (programArgs.get("filePath").indexOf("Luxembourg") != -1 || programArgs.get("filePath").indexOf("twolanes") != -1 || programArgs.get("filePath").indexOf("highway") != -1) { markers = initializeMarkersLuxembourgOrHighway(); } Dictionary<String, Object> communityAlgorithmParams = getAlgorithmParams(programArgs, markers); Dictionary<String, Object> congestionAlgorithmParams = getCongestionParams(programArgs, markers); Crowds crowds = new Crowds(); // try { // crowds.setImagesGeneration(true); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } crowds.setSettings(Integer.parseInt(programArgs.get("startStep")), Integer.parseInt(programArgs.get("endStep")), Integer.parseInt(programArgs.get("numberOfIterations")), programArgs.get("goal")); crowds.openOutputFiles(programArgs.get("outputDir")); crowds.readGraph(programArgs.get("filePath")); crowds.initializeConnectedComponents(markers.get(MobileMarker.MODULE)); String communityAlgorithmName = programArgs.get("communityAlgorithmName"); if (communityAlgorithmName.equals("SandSharc_nostab") || communityAlgorithmName.equals("SandSharc_mobility") || communityAlgorithmName.equals("SandSharc_linkduration") || communityAlgorithmName.equals("SandSharc_hybrid")) { communityAlgorithmName = "SandSharc"; } if (communityAlgorithmName.equals("SandSharc_copy_nostab") || communityAlgorithmName.equals("SandSharc_copy_mobility") || communityAlgorithmName.equals("SandSharc_copy_linkduration") || communityAlgorithmName.equals("SandSharc_copy_hybrid")) { communityAlgorithmName = "SandSharc_copy"; } if (communityAlgorithmName.equals("MySandSharc_nostab") || communityAlgorithmName.equals("MySandSharc_mobility") || communityAlgorithmName.equals("MySandSharc_linkduration") || communityAlgorithmName.equals("MySandSharc_hybrid")) { communityAlgorithmName = "MySandSharc"; } if (communityAlgorithmName.equals("MySandSharc2_nostab") || communityAlgorithmName.equals("MySandSharc2_mobility") || communityAlgorithmName.equals("MySandSharc2_linkduration") || communityAlgorithmName.equals("MySandSharc2_hybrid")) { communityAlgorithmName = "MySandSharc2"; } if (communityAlgorithmName.equals("MySandSharc3_nostab") || communityAlgorithmName.equals("MySandSharc3_mobility") || communityAlgorithmName.equals("MySandSharc3_linkduration") || communityAlgorithmName.equals("MySandSharc3_hybrid")) { communityAlgorithmName = "MySandSharc3"; System.out.println("communityAlgorithmName " + communityAlgorithmName); } if (communityAlgorithmName.equals("MySandSharc4_nostab") || communityAlgorithmName.equals("MySandSharc4_mobility") || communityAlgorithmName.equals("MySandSharc4_linkduration") || communityAlgorithmName.equals("MySandSharc4_hybrid")) { communityAlgorithmName = "MySandSharc4"; System.out.println("communityAlgorithmName " + communityAlgorithmName); } if (communityAlgorithmName.equals("MySandSharc5_nostab") || communityAlgorithmName.equals("MySandSharc5_mobility") || communityAlgorithmName.equals("MySandSharc5_linkduration") || communityAlgorithmName.equals("MySandSharc5_hybrid")) { communityAlgorithmName = "MySandSharc5"; System.out.println("communityAlgorithmName " + communityAlgorithmName); } if (communityAlgorithmName.equals("MySandSharc6_nostab") || communityAlgorithmName.equals("MySandSharc6_mobility") || communityAlgorithmName.equals("MySandSharc6_linkduration") || communityAlgorithmName.equals("MySandSharc6_hybrid")) { communityAlgorithmName = "MySandSharc6"; System.out.println("communityAlgorithmName " + communityAlgorithmName); } crowds.initializeCommunityDetectionAlgorithm(communityAlgorithmName, markers.get(MobileMarker.COMMUNITY), communityAlgorithmParams); crowds.initializeCongestionDetectionAlgorithm(programArgs.get("congestionAlgorithmName"), markers.get(MobileMarker.CONGESTION), congestionAlgorithmParams); crowds.detectCommunities(); } public static Hashtable<String, Object> getCongestionParams(HashMap<String, String> programArgs, HashMap<MobileMarker, String> markers) { Hashtable<String, Object> params = new Hashtable<String, Object>(); String algorithmName = programArgs.get("congestionAlgorithmName"); if (algorithmName.equals("CongestionCrowdz") || algorithmName.equals("CongestionMeasure")) { params.put("weightMarker", "weight"); params.put("speedMarker", markers.get(MobileMarker.SPEED)); params.put("angleMarker", markers.get(MobileMarker.ANGLE)); params.put("mobilitySimilarityMarker", markers.get(MobileMarker.MOBILITY_SIMILARITY)); params.put("laneMarker", markers.get(MobileMarker.LANE)); params.put("dynamismMarker", markers.get(MobileMarker.DYNAMISM)); params.put("linkDurationMarker", markers.get(MobileMarker.LINK_DURATION)); params.put("hybridMarker", "hybrid"); params.put("speedHistoryLength", Integer.parseInt(programArgs.get("speedHistoryLength"))); params.put("speedType", programArgs.get("speedType")); } return params; } public static Dictionary<String, Object> getAlgorithmParams(HashMap<String, String> programArgs, HashMap<MobileMarker, String> markers) { Dictionary<String, Object> params = new Hashtable<String, Object>(); String algorithmName = programArgs.get("communityAlgorithmName"); params.put("mobilitySimilarityMarker", markers.get(MobileMarker.MOBILITY_SIMILARITY)); // used in CrowdsTest to print edges params.put("linkDurationMarker", markers.get(MobileMarker.LINK_DURATION)); // used in CrowdsTest to print edges // Oryginal SandSharc if (algorithmName.indexOf("nostab") != -1) { params.put("weightMarker", ""); } // Oryginal SandSharc + mobility_metric as stability measure else if (algorithmName.indexOf("mobility") != -1 ) { params.put("weightMarker", markers.get(MobileMarker.MOBILITY_SIMILARITY)); } // Oryginal SandSharc + linkduration as stability measure else if (algorithmName.indexOf("linkduration") != -1) { params.put("weightMarker", markers.get(MobileMarker.LINK_DURATION)); } else if (algorithmName.indexOf("hybrid") != -1) { params.put("weightMarker", "hybrid"); } // if (algorithmName.equals("Leung")) { // params.put("m", Double.parseDouble(programArgs.get("mParameter"))); // params.put("delta", Double.parseDouble(programArgs.get("deltaParameter"))); // params.put("weightMarker", markers.get(MobileMarker.WEIGHT)); // } // else { System.err.println("Community detection algorithm not known " + algorithmName + " " + params); } return params; } public static HashMap<MobileMarker, String> initializeMarkers() { HashMap<MobileMarker, String> markers = new HashMap<MobileMarker, String>(); markers.put(MobileMarker.X, "x"); markers.put(MobileMarker.Y, "y"); markers.put(MobileMarker.WEIGHT, "weight"); markers.put(MobileMarker.COMMUNITY, "community"); markers.put(MobileMarker.COMMUNITY_SCORE, markers.get(MobileMarker.COMMUNITY)+".score"); markers.put(MobileMarker.CONGESTION, "congestion"); markers.put(MobileMarker.MODULE, "module"); markers.put(MobileMarker.SPEED, "speed"); markers.put(MobileMarker.LANE, "link_id"); markers.put(MobileMarker.ANGLE, "angle"); markers.put(MobileMarker.POS, "offset"); markers.put(MobileMarker.DISTANCE, "distance"); markers.put(MobileMarker.DYNAMISM, "dynamism"); markers.put(MobileMarker.TIMEMEANSPEED, "timeMeanSpeed"); markers.put(MobileMarker.LINK_DURATION, "linkDuration"); markers.put(MobileMarker.MOBILITY_SIMILARITY, "mob_sim"); return markers; } public static HashMap<MobileMarker, String> initializeMarkersLuxembourgOrHighway() { HashMap<MobileMarker, String> markers = new HashMap<MobileMarker, String>(); markers.put(MobileMarker.X, "x"); markers.put(MobileMarker.Y, "y"); markers.put(MobileMarker.WEIGHT, "weight"); markers.put(MobileMarker.COMMUNITY, "community"); markers.put(MobileMarker.COMMUNITY_SCORE, markers.get(MobileMarker.COMMUNITY)+".score"); markers.put(MobileMarker.CONGESTION, "congestion"); markers.put(MobileMarker.MODULE, "module"); markers.put(MobileMarker.SPEED, "vehicleSpeed"); markers.put(MobileMarker.LANE, "vehicleLane"); markers.put(MobileMarker.ANGLE, "vehicleAngle"); markers.put(MobileMarker.POS, "vehiclePos"); markers.put(MobileMarker.DISTANCE, "distance"); markers.put(MobileMarker.DYNAMISM, "dynamism"); markers.put(MobileMarker.TIMEMEANSPEED, "timeMeanSpeed"); markers.put(MobileMarker.LINK_DURATION, "linkDuration"); markers.put(MobileMarker.MOBILITY_SIMILARITY, "mob_sim"); return markers; } public static HashMap<String, String> parseArgs(String[] args) { HashMap<String, String> programArgs = new HashMap<String, String>(); if (args.length > 1) { for (int i = 0; i < args.length; ++i) { String argName = args[i]; String argValue = args[++i]; if (argName.equals("--communityAlgorithmName")) { programArgs.put("communityAlgorithmName", argValue.trim()); } if (argName.equals("--congestionAlgorithmName")) { programArgs.put("congestionAlgorithmName", argValue.trim()); } if (argName.equals("--goal")) { programArgs.put("goal", argValue.trim()); } if (argName.equals("--inputFile")) { programArgs.put("filePath", argValue.trim()); } if (argName.equals("--startStep")) { programArgs.put("startStep", argValue.trim()); } if (argName.equals("--endStep")) { programArgs.put("endStep", argValue.trim()); } if (argName.equals("--outputDir")) { programArgs.put("outputDir", argValue.trim()); } if (argName.equals("--numberOfIterations")) { programArgs.put("numberOfIterations", argValue.trim()); } if (argName.equals("--speedHistoryLength")) { programArgs.put("speedHistoryLength", argValue.trim()); } if (argName.equals("--speedType")) { programArgs.put("speedType", argValue.trim());; } } } return programArgs; } }
true
20cd0b8d1cd005bbb19af5ee6ff50cff34943805
Java
Eulers-Bridge/dbinterface
/src/main/java/com/eulersbridge/iEngage/core/events/users/LoginDetails.java
UTF-8
1,200
2.390625
2
[]
no_license
/** * */ package com.eulersbridge.iEngage.core.events.users; import com.eulersbridge.iEngage.core.events.Details; import com.eulersbridge.iEngage.core.events.newsArticles.NewsArticleDetails; import java.util.Iterator; /** * @author Greg Newitt * */ public class LoginDetails extends Details { private Iterator<NewsArticleDetails> articles; private UserDetails user; /** * @param articles * @param user * @param userId */ public LoginDetails(Iterator<NewsArticleDetails> articles, UserDetails user, Long userId) { super(userId); this.articles = articles; this.user = user; } public Iterator<NewsArticleDetails> getArticles() { return this.articles; } public UserDetails getUser() { return this.user; } /** * @param articles the articles to set */ public void setArticles(Iterator<NewsArticleDetails> articles) { this.articles = articles; } /** * @param user the user to set */ public void setUser(UserDetails user) { this.user = user; } /** * @return the userId */ public Long getUserId() { return getNodeId(); } /** * @param userId the userId to set */ public void setUserId(Long userId) { setNodeId(userId); } }
true
afd1237b2edeed57bf08dd663b595d4ea58522df
Java
poshjosh/cometdchat
/src/main/java/com/looseboxes/cometd/chat/PrivateMessageConsumerLocalDiscStore.java
UTF-8
3,535
2.265625
2
[]
no_license
/* * Copyright 2018 NUROX Ltd. * * Licensed under the NUROX Ltd Software License (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.looseboxes.com/legal/licenses/software.html * * 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.looseboxes.cometd.chat; import com.bc.collection.diskbacked.FileBackedCollection; import com.bc.collection.diskbacked.FileBackedListImpl; import com.looseboxes.cometd.chat.functions.GetAppDir; import com.looseboxes.cometd.chat.functions.GetAppName; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; /** * @author Chinomso Bassey Ikwuagwu on May 19, 2018 1:09:27 PM */ public class PrivateMessageConsumerLocalDiscStore extends PrivateMessageConsumerImpl{ private static final Logger LOG = Logger.getLogger(PrivateMessageConsumerLocalDiscStore.class.getName()); private static final class GetMessagesDir { public File apply(ServletContext context, String name) { final String appName = new GetAppName().apply(context); final File appDir = new GetAppDir().apply(context, appName); final File messagesDir = new File(appDir, name); if(!messagesDir.exists()) { messagesDir.mkdirs(); } return messagesDir; } } private static final class GetChunkSize { public int apply(ServletContext context, int outputIfNone) { final String sval = context.getInitParameter("fileBasedCollection_chunkSize"); final int chunkSize = sval == null || sval.isEmpty() ? outputIfNone : Integer.parseInt(sval); return chunkSize; } } public PrivateMessageConsumerLocalDiscStore(ServletContext context) { this( new GetMessagesDir().apply(context, "chat_messages").toString(), new GetChunkSize().apply(context, 100) ); } public PrivateMessageConsumerLocalDiscStore(String messagesDir, int chunkSize) { super(new HashMap(), (from, to) -> new FileBackedListImpl(messagesDir, from + "=" + to + ".bin", false, chunkSize)); } @Override public List remove(String from, String to) { final FileBackedCollection fileBasedList = (FileBackedCollection)super.remove(from, to); final List output; if(fileBasedList == null) { output = null; }else{ try { if(fileBasedList.isEmpty()) { output = Collections.EMPTY_LIST; }else{ output = new ArrayList(); fileBasedList.forEach((e) -> output.add(e)); } }finally{ try{ fileBasedList.close(); }catch(IOException e) { LOG.log(Level.WARNING, "Exception closing file based list", e); } } } return output; } }
true
06a37297c95fc3227335643c29380e8a2d5f29b0
Java
SuryaNMenon/Java
/Applets/ChoiceDemo.java
UTF-8
1,485
3.296875
3
[]
no_license
package Applets; import java.awt.*; import java.awt.event.*; public class ChoiceDemo extends Frame implements ItemListener{ Label lbl; Choice deg; TextField tf; public ChoiceDemo(){ tf = new TextField(30); tf.setEditable(false); deg = new Choice(); deg.add("Select your font"); deg.add("Bold"); deg.add("Italics"); deg.add("Bold+Italics"); deg.addItemListener(this); add(deg); add(tf); } public void itemStateChanged(ItemEvent ie){ if(deg.getSelectedIndex() == 1){ tf.setFont(new Font("Arial", Font.BOLD, 20)); tf.setText("You selected " + deg.getSelectedItem()); } else if(deg.getSelectedIndex() == 2){ tf.setFont(new Font("Arial", Font.ITALIC, 20)); tf.setText("You selected "+ deg.getSelectedItem()); } else if(deg.getSelectedIndex() == 3){ tf.setFont(new Font("Arial", Font.BOLD|Font.ITALIC, 20)); tf.setText("You selected "+deg.getSelectedItem()); } } public static void main(String[] args) { Frame F = new ChoiceDemo(); F.setTitle("Choice Demo"); F.setSize(400,400); F.setVisible(true); F.setLayout(new FlowLayout()); F.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } }
true
77184afd1ed5dbc9086991950fe68c2e9e350858
Java
thanhvg/java
/pong5/src/network2/ServerToClientMsg.java
UTF-8
923
2.5
2
[]
no_license
package network2; import java.io.Serializable; public class ServerToClientMsg implements Serializable { int ballPosX; int ballPoxY; int barLeftPos; int barRightPos; public ServerToClientMsg(int ballPosX, int ballPoxY, int barLeftPos, int barRightPos) { super(); this.ballPosX = ballPosX; this.ballPoxY = ballPoxY; this.barLeftPos = barLeftPos; this.barRightPos = barRightPos; } public int getBallPosX() { return ballPosX; } public void setBallPosX(int ballPosX) { this.ballPosX = ballPosX; } public int getBallPoxY() { return ballPoxY; } public void setBallPoxY(int ballPoxY) { this.ballPoxY = ballPoxY; } public int getBarLeftPos() { return barLeftPos; } public void setBarLeftPos(int barLeftPos) { this.barLeftPos = barLeftPos; } public int getBarRightPos() { return barRightPos; } public void setBarRightPos(int barRightPos) { this.barRightPos = barRightPos; } }
true
1f6b3b83ad9b8811349ec25d0d2ce3159eeecf09
Java
useocl/use_plugins
/ModelValidator/branches/diplom-aili/model-validator/src/org/tzi/use/kodkod/plugin/gui/model/TableModelReal.java
UTF-8
2,149
2.59375
3
[]
no_license
package org.tzi.use.kodkod.plugin.gui.model; import java.util.LinkedHashSet; import java.util.Set; import javax.swing.table.AbstractTableModel; import org.tzi.use.kodkod.plugin.gui.ConfigurationTerms; import org.tzi.use.kodkod.plugin.gui.model.data.RealSettings; import org.tzi.use.util.StringUtil; public class TableModelReal extends AbstractTableModel { private static final long serialVersionUID = 1L; private final RealSettings settings; private static final String[] COLUMN_NAMES = new String[] { ConfigurationTerms.REAL_MIN, ConfigurationTerms.REAL_MAX, ConfigurationTerms.REAL_STEP, ConfigurationTerms.REAL_VALUES }; public TableModelReal(RealSettings settings) { this.settings = settings; } @Override public int getRowCount() { return 1; } @Override public int getColumnCount() { return COLUMN_NAMES.length; } @Override public String getColumnName(int column) { return COLUMN_NAMES[column]; } @Override public boolean isCellEditable(int row, int column) { return true; } @Override public Object getValueAt(int row, int col) { switch (col) { case 0: return settings.getMinimum(); case 1: return settings.getMaximum(); case 2: return settings.getStep(); case 3: return StringUtil.fmtSeq(settings.getValues(), ","); } return null; } @Override public void setValueAt(Object aValue, int row, int column) { switch (column) { case 0: settings.setMinimum((Double) aValue); fireTableCellUpdated(row, column); break; case 1: settings.setMaximum((Double) aValue); fireTableCellUpdated(row, column); break; case 2: settings.setStep((Double) aValue); fireTableCellUpdated(row, column); break; case 3: String[] split = ((String) aValue).split(","); Set<Double> list = new LinkedHashSet<Double>(); for (int i = 0; i < split.length; i++) { list.add(Double.valueOf(split[i].trim())); } settings.setValues(list); fireTableCellUpdated(row, column); break; } } public RealSettings getSettings() { return settings; } }
true
1daa456ad98ebe06bd6ee2d12b4945dc0050d4e7
Java
NMVW/meerchat_android
/Meerchat2/app/src/main/java/mobi/meerchat/meerchat2/TC.java
UTF-8
10,062
2.328125
2
[]
no_license
package mobi.meerchat.meerchat2; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class TC extends Activity { String tc = ""; String fbid = ""; String fbemail = ""; Bundle extras; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState==null){ extras = getIntent().getExtras(); if(extras==null) { fbid=null; fbemail=null; } else { fbid=extras.getString("FBid"); fbemail = extras.getString("FBemail"); } } else { fbid = (String)savedInstanceState.getSerializable("FBid"); fbemail = (String)savedInstanceState.getSerializable("FBemail"); } Log.v("Terms&Conditions",fbid); Log.v("Terms&Conditions",fbemail); setContentView(R.layout.activity_tc); String contents = ""; TextView tcView = (TextView) findViewById(R.id.tc); //startTimerThread(contents); outputThread ot = new outputThread(); ot.start(); Log.v("Terms&Conditions","trying to set"); try { Thread.sleep(10000); } catch(Exception e) { e.printStackTrace(); } Log.v("Terms&Conditions","while done"); contents= ot.getContents(); contents = contents.substring(contents.indexOf("Welcome to ")); Log.v("Terms&Conditions",contents); while (contents.indexOf("<")>-1 || contents.indexOf(">")>-1) { if(contents.indexOf("<")==contents.indexOf("</p")) { contents = replaceString(contents,contents.substring(contents.indexOf("<"),contents.indexOf(">")+1),"\n\n"); } else { contents = replaceString(contents,contents.substring(contents.indexOf("<"),contents.indexOf(">")+1),""); } Log.v("Terms&Conditions",contents); } //remove &ldquo ", &rdquo ", nbsp ,&quot ",&#39 ', &rsquo ', contents = replaceAllString(contents,"&ldquo;","\""); contents = replaceAllString(contents,"&rdquo;","\""); contents = replaceAllString(contents,"&nbsp;"," "); contents = replaceAllString(contents,"&quot;","\""); contents = replaceAllString(contents,"&#39;","\'"); contents = replaceAllString(contents,"&rsquo;","\'"); tcView.setText(contents); Log.v("Terms&Conditions","set"); /** Thread t = new Thread(new Runnable(){ public void run() { try { //urlAddress=""; //CHANGE THIS LINE WEEK AND NUMBERS //page = new URL(urlAddress); //contents=""; //pageToRead=page; final URL page = new URL(urlAddress); String contents = ""; final TextView tcView = (TextView) findViewById(R.id.tc); URLConnection yc = page.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while((inputLine=in.readLine())!=null) { contents+=inputLine; } in.close(); Log.v("Terms&Conditions",contents); contents = contents.substring(contents.indexOf("Welcome to ")); Log.v("Terms&Conditions",contents); while (contents.indexOf("<")>-1 || contents.indexOf(">")>-1) { contents = replaceString(contents,contents.substring(contents.indexOf("<"),contents.indexOf(">")+1),""); Log.v("Terms&Conditions",contents); } tcView.setText(contents); Log.v("Terms&Conditions","done"); } catch(Exception e) { e.printStackTrace(); Log.v("Terms&Conditions","broken"); } } }); t.start(); */ /** Thread t = new Thread(new Runnable() { public void run() { try { Log.v("TCLOG","trying url"); URL tcPage = new URL("http://www.oracle.com/"); //http://meerchat.mobi/PrivacyPolicy_Terms/ Log.v("TCLOG","trying buffered"); BufferedReader in = new BufferedReader( new InputStreamReader(tcPage.openStream())); String inputLine; Log.v("TCLOG","running while"); while ((inputLine = in.readLine()) != null) { tc += inputLine; Log.v("TCLOG", tc); } in.close(); Log.v("TCLOG","done"); } catch(Exception e) { Log.v("TCLOG", "error"); e.printStackTrace(); } } }); t.start(); */ /** try { Log.v("TCLOG","trying url"); URL tcPage = new URL("http://www.oracle.com/"); Log.v("TCLOG","trying buffered"); BufferedReader in = new BufferedReader( new InputStreamReader(tcPage.openStream())); String inputLine; Log.v("TCLOG","running while"); while ((inputLine = in.readLine()) != null) tc+=inputLine; in.close(); } catch(Exception e) { Log.v("TCLOG", "error"); e.printStackTrace(); } */ //Log.v("TCLOG","setting text"); //tcView.setText(tc); } /** private void startTimerThread(final String contents) { final String contents2; Runnable runnable = new Runnable() { //private long startTime = System.currentTimeMillis(); public void run() { Handler handler = new Handler(); final String urlAddress = "http://meerchat.mobi/PrivacyPolicy_Terms/"; //String contents = ""; final TextView tcView = (TextView) findViewById(R.id.tc); try { final URL page = new URL(urlAddress); //urlAddress=""; //CHANGE THIS LINE WEEK AND NUMBERS //page = new URL(urlAddress); //contents=""; //pageToRead=page; URLConnection yc = page.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while((inputLine=in.readLine())!=null) { contents+=inputLine; } in.close(); Log.v("Terms&Conditions",contents); contents = contents.substring(contents.indexOf("Welcome to ")); Log.v("Terms&Conditions",contents); while (contents.indexOf("<")>-1 || contents.indexOf(">")>-1) { contents = replaceString(contents,contents.substring(contents.indexOf("<"),contents.indexOf(">")+1),""); Log.v("Terms&Conditions",contents); } tcView.setText(contents); //final String contents2 = contents; Log.v("Terms&Conditions","done"); contents2=contents; } catch(Exception e) { e.printStackTrace(); Log.v("Terms&Conditions","broken"); } handler.post(new Runnable(){ public void run() { tcView.setText(contents); } }); } }; new Thread(runnable).start(); } */ public static String replaceString(String bigString, String old, String newS) { while(bigString.indexOf(old)>-1) { bigString = bigString.substring(0,bigString.indexOf(old)) + newS + bigString.substring(bigString.indexOf(old)+old.length()); } return bigString; } public static String replaceAllString(String bigString, String old, String newS) { while(bigString.indexOf(old)>-1){ bigString=replaceString(bigString, old, newS); } return bigString; } public void goToNextPage(View view) { Intent RegisterIntent = new Intent(getApplicationContext(), UserCreation.class); RegisterIntent.putExtra("FBemail",fbemail); RegisterIntent.putExtra("FBid",fbid); startActivity(RegisterIntent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_tc, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
2234cedcc09a98f386b81ba31dc82ff3eceee629
Java
tommy770221/AngelHack
/src/main/java/com/angelhack/mapteam/api/model/AccessTokenResponse.java
UTF-8
1,005
2.265625
2
[]
no_license
package com.angelhack.mapteam.api.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreType; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.robohorse.robopojogenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class AccessTokenResponse{ @JsonProperty("access_token") private String accessToken; @JsonProperty("token_type") private String tokenType; public void setAccessToken(String accessToken){ this.accessToken = accessToken; } public String getAccessToken(){ return accessToken; } public void setTokenType(String tokenType){ this.tokenType = tokenType; } public String getTokenType(){ return tokenType; } @Override public String toString(){ return "AccessTokenResponse{" + "access_token = '" + accessToken + '\'' + ",token_type = '" + tokenType + '\'' + "}"; } }
true
a15e3c7e1e4fa49c887f514a19889edb0a9c35c0
Java
kuchro/jaztest
/src/main/java/com/jaztest/jazs21912nbp/JazS21912NbpApplication.java
UTF-8
329
1.507813
2
[]
no_license
package com.jaztest.jazs21912nbp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JazS21912NbpApplication { public static void main(String[] args) { SpringApplication.run(JazS21912NbpApplication.class, args); } }
true
b311a08099a022f6900e0093aa974ed3c83623f5
Java
crciuperca/HomeColocviu2
/app/src/main/java/practicaltest02/eim/systems/cs/pub/ro/practicaltest02/CommunicationThread.java
UTF-8
9,871
2.171875
2
[]
no_license
package practicaltest02.eim.systems.cs.pub.ro.practicaltest02; import android.graphics.BitmapFactory; import android.util.Log; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.HttpEntity; import cz.msebera.android.httpclient.HttpResponse; import cz.msebera.android.httpclient.NameValuePair; import cz.msebera.android.httpclient.client.ClientProtocolException; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.client.ResponseHandler; import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity; import cz.msebera.android.httpclient.client.methods.HttpGet; import cz.msebera.android.httpclient.client.methods.HttpPost; import cz.msebera.android.httpclient.impl.client.BasicResponseHandler; import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; import cz.msebera.android.httpclient.message.BasicNameValuePair; import cz.msebera.android.httpclient.protocol.HTTP; import cz.msebera.android.httpclient.util.EntityUtils; public class CommunicationThread extends Thread { private MyServerThread serverThread; private Socket socket; private EditText serverTextEditText; private String link = "https://www.wunderground.com/cgi-bin/findweather/getForecast?query="; private Spinner dropdown; private String city; private String informationType; String retStr; public CommunicationThread(Socket socket, EditText serverTextEditText, Spinner dropdown, MyServerThread serverThread) { this.socket = socket; this.serverTextEditText = serverTextEditText; this.dropdown = dropdown; this.serverThread = serverThread; } @Override public void run() { try { Log.v(Constants.TAG, "Connection opened with " + socket.getInetAddress() + ":" + socket.getLocalPort()); PrintWriter printWriter = Utilities.getWriter(socket); BufferedReader bufferedReader = Utilities.getReader(socket); city = bufferedReader.readLine(); informationType = bufferedReader.readLine(); String msg = getInfo(); // printWriter.println(retStr); //printWriter.println(getInfo()); socket.close(); Log.v(Constants.TAG, "Conenction closed"); } catch (IOException ioException) { Log.e(Constants.TAG, "An exception has occurred: " + ioException.getMessage()); if (Constants.DEBUG) { ioException.printStackTrace(); } } } public String getInfo() { this.retStr = ""; String humidity = ""; String temperature = ""; if (!(informationType).equals("POST")) { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGetXKCD = new HttpGet(link + city);//serverTextEditText.getText().toString()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String pageSourceCode = null; Document document = new Document("Page empty"); Element htmlTag = new Element("Empty"); HttpResponse httpResponse; try { pageSourceCode = httpClient.execute(httpGetXKCD, responseHandler); } catch (ClientProtocolException clientProtocolException) { Log.e(Constants.TAG, clientProtocolException.getMessage()); if (Constants.DEBUG) { clientProtocolException.printStackTrace(); } } catch (IOException ioException) { Log.e(Constants.TAG, ioException.getMessage()); if (Constants.DEBUG) { ioException.printStackTrace(); } } if (pageSourceCode != null) { document = Jsoup.parse(pageSourceCode); htmlTag = document.child(0); List<Element> elements = htmlTag.getElementsByTag("script"); for (Element el : elements) { if (el.toString().contains("heatindex")) { humidity = "Humidity: " + el.toString().split("\"humidity\"")[1].substring(1,3) + "%\n"; temperature = "Temperature: " + el.toString().split("\"temperature\"")[1].substring(1, 3) + "F\n"; retStr += humidity; retStr += temperature; //serverThread.setData(city, new WeatherForecastInformation(humidity, temperature)); break; } } PrintWriter printWriter = null; try { printWriter = Utilities.getWriter(socket); printWriter.println(humidity); printWriter.println(temperature); printWriter.flush(); } catch (IOException e) { e.printStackTrace(); } /* EXAMPLE JSON PARSE int position = scriptData.indexOf(Constants.SEARCH_KEY) + Constants.SEARCH_KEY.length(); scriptData = scriptData.substring(position); JSONObject content = new JSONObject(scriptData); JSONObject currentObservation = content.getJSONObject(Constants.CURRENT_OBSERVATION); String temperature = currentObservation.getString(Constants.TEMPERATURE); */ // retStr += "Heat index: " + htmlTag.getElementsByAttributeValue("data-variable", "heatindex").first().toString() + "\n"; // retStr += "Dew point: " + htmlTag.getElementsByAttributeValue("data-variable", "dewpoint").first().toString() + "\n"; // retStr += "Humidity: " + htmlTag.getElementsByAttributeValue("data-variable", "humidity").first().toString() + "\n"; // EXAMPLE CARTOON // cartoon title // Element divTagIdCtitle = htmlTag.getElementsByAttributeValue(Constants.ID_ATTRIBUTE, Constants.CTITLE_VALUE).first(); // xkcdCartoonInformation.setCartoonTitle(divTagIdCtitle.ownText()); // // // cartoon url // Element divTagIdComic = htmlTag.getElementsByAttributeValue(Constants.ID_ATTRIBUTE, Constants.COMIC_VALUE).first(); // String cartoonInternetAddress = divTagIdComic.getElementsByTag(Constants.IMG_TAG).attr(Constants.SRC_ATTRIBUTE); // String cartoonUrl = Constants.HTTP_PROTOCOL + cartoonInternetAddress; // xkcdCartoonInformation.setCartoonUrl(cartoonUrl); // // try { // HttpGet httpGetCartoon = new HttpGet(cartoonUrl); // HttpResponse httpResponse = httpClient.execute(httpGetCartoon); // HttpEntity httpEntity = httpResponse.getEntity(); // if (httpEntity != null) { // xkcdCartoonInformation.setCartoonBitmap(BitmapFactory.decodeStream(httpEntity.getContent())); // } // } catch (ClientProtocolException clientProtocolException) { // Log.e(Constants.TAG, clientProtocolException.getMessage()); // if (Constants.DEBUG) { // clientProtocolException.printStackTrace(); // } // } catch (IOException ioException) { // Log.e(Constants.TAG, ioException.getMessage()); // if (Constants.DEBUG) { // ioException.printStackTrace(); // } // } } return retStr; } else { // EXAMPLE POST try { HttpClient httpClientPost = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://httpbin.org/post"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("attribute1", "value1")); // ... params.add(new BasicNameValuePair("attributen", "valuen")); UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8); httpPost.setEntity(urlEncodedFormEntity); HttpResponse httpPostResponse = httpClientPost.execute(httpPost); HttpEntity httpPostEntity = httpPostResponse.getEntity(); if (httpPostEntity != null) { // do something with the response //Toast.makeText(MainActivity.context, httpPostEntity.toString(), Toast.LENGTH_LONG).show(); retStr = httpPostEntity.getContent().toString(); Log.i(Constants.TAG, EntityUtils.toString(httpPostEntity)); return retStr; } } catch (Exception exception) { Log.e(Constants.TAG, exception.getMessage()); if (Constants.DEBUG) { exception.printStackTrace(); } } } return "Empty"; } }
true
0d81ad5d2d996fcf8826cccf6a599c37e1f1af4e
Java
liaopen123/ItemTouchHelperDemo
/app/src/main/java/com/example/pony/itemtouchhelperdemo/activity/MainActivity.java
UTF-8
2,258
2.078125
2
[]
no_license
package com.example.pony.itemtouchhelperdemo.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import com.example.pony.itemtouchhelperdemo.Adapter.GalleryAdapter; import com.example.pony.itemtouchhelperdemo.R; import com.example.pony.itemtouchhelperdemo.callback.ItemDragAndSwipeCallback; import java.util.ArrayList; import java.util.Arrays; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { @BindView( R.id.recyclerview ) public RecyclerView mRecyclerView ; private ArrayList<Integer> mDatas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); //设置布局管理器 initDatas(); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); // RecyclerView.LayoutManager mLayoutManager = new StaggeredGridLayoutManager( // 2, StaggeredGridLayoutManager.VERTICAL); // mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setLayoutManager(linearLayoutManager); //设置适配器 GalleryAdapter mAdapter = new GalleryAdapter(this, mDatas); //设置触摸回调 ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback); itemTouchHelper.attachToRecyclerView(mRecyclerView); mRecyclerView.setAdapter(mAdapter); Intent intent = new Intent(this,MultiItemActivity.class); startActivity(intent); } private void initDatas() { mDatas = new ArrayList<Integer>(Arrays.asList(R.mipmap.ic_launcher, R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher)); } }
true
76a87cdfc906c12ec299b3a6946634eb3d74f863
Java
zzyongx/c-gist
/java/howto/src/main/java/commons/spring/LoggerFilter.java
UTF-8
8,144
2.09375
2
[]
no_license
package commons.spring; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.util.StreamUtils; @ManagedResource(objectName = "bean:name=loggerFilter") public class LoggerFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(LoggerFilter.class); private boolean logHttpGet; private boolean logHttpPost; private boolean logHttpPut; private boolean logHttpDelete; private boolean logError; public LoggerFilter(Environment env) { String def = "true"; logHttpGet = Boolean.parseBoolean(env.getProperty("logfilter.get", "false")); logHttpPost = Boolean.parseBoolean(env.getProperty("logfilter.post", def)); logHttpPut = Boolean.parseBoolean(env.getProperty("logfilter.put", def)); logHttpDelete = Boolean.parseBoolean(env.getProperty("logfilter.delete", def)); logError = Boolean.parseBoolean(env.getProperty("logfilter.error", def)); } @ManagedAttribute(description="The logHttpGet Attribute", defaultValue="false") public boolean getLogHttpGet() { return this.logHttpGet; } @ManagedAttribute(description="The logHttpGet Attribute") public void setLogHttpGet(boolean logHttpGet) { this.logHttpGet = logHttpGet; } @ManagedAttribute(description="The logHttpPost Attribute", defaultValue="false") public boolean getLogHttpPost() { return this.logHttpPost; } @ManagedAttribute(description="The logHttpPost Attribute") public void setLogHttpPost(boolean logHttpPost) { this.logHttpPost = logHttpPost; } @ManagedAttribute(description="The logHttpPut Attribute", defaultValue="false") public boolean getLogHttpPut() { return this.logHttpPut; } @ManagedAttribute(description="The logHttpPut Attribute") public void setLogHttpPut(boolean logHttpPut) { this.logHttpPut = logHttpPut; } @ManagedAttribute(description="The logHttpDelete Attribute", defaultValue="false") public boolean getLogHttpDelete() { return this.logHttpDelete; } @ManagedAttribute(description="The logHttpDelete Attribute") public void setLogHttpDelete(boolean logHttpDelete) { this.logHttpDelete = logHttpDelete; } @ManagedAttribute(description="The logError Attribute", defaultValue="false") public boolean getLogError() { return this.logError; } @ManagedAttribute(description="The logError Attribute") public void setLogError(boolean logError) { this.logError = logError; } public void init(FilterConfig arg) throws ServletException { // nothing to do } public void destroy() { // nothing to do } boolean ifLog(String method, HttpServletRequest req) { if (logHttpGet && method.equals("GET") || logHttpDelete && method.equals("DELETE")) { return true; } else if (logHttpPost && method.equals("POST") || logHttpPut && method.equals("PUT")) { String contentType = req.getContentType(); if (contentType != null && (contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("multipart/form-data") || contentType.startsWith("application/json") || contentType.startsWith("text/plain"))) { return true; } int len = req.getContentLength(); if (len == 0) return true; } return false; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String method = req.getMethod(); boolean log = ifLog(method, req); ServletRequest reqWrap = request; ServletResponse respWrap = response; ResettableStreamHttpServletRequest resetableReq = null; ResettableStreamHttpServletResponse resetableResp = null; String reqBody = "-"; String respBody = null; if (log) { if (method.equals("POST") || method.equals("PUT")) { resetableReq = new ResettableStreamHttpServletRequest(req); reqWrap = resetableReq; } resetableResp = new ResettableStreamHttpServletResponse(resp); respWrap = resetableResp; } if (logError) request.setAttribute("response__", resp); chain.doFilter(reqWrap, respWrap); if (log) { if (resetableReq != null) { // must call after doFilter byte[] bytes = resetableReq.getData(); if (bytes == null) { reqBody = req.getParameterMap().toString(); } else { reqBody = new String(bytes); } } byte[] bytes = resetableResp.getData(); response.getOutputStream().write(bytes); if (bytes != null) respBody = new String(bytes); } else if (logError) { reqBody = req.getParameterMap().toString(); respBody = (String) request.getAttribute("ApiResultError"); } if (log || logError && respBody != null) { String queryStr = req.getQueryString(); if (queryStr == null) queryStr = "-"; if (respBody == null) respBody = "-"; String userId = (String) request.getAttribute("RmsUid"); if (userId == null) userId = "-"; logger.warn("{} {} {} {} {} {}", method, req.getRequestURI(), queryStr, userId, reqBody, respBody); } } private static class ResettableStreamHttpServletRequest extends HttpServletRequestWrapper { private byte rawData[]; private ServletInputStreamImpl servletStream; public ResettableStreamHttpServletRequest(HttpServletRequest request) { super(request); this.servletStream = new ServletInputStreamImpl(); } public byte[] getData() { return rawData; } @Override public ServletInputStream getInputStream() throws IOException { rawData = StreamUtils.copyToByteArray(super.getInputStream()); servletStream.setData(rawData); return servletStream; } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } private static class ServletInputStreamImpl extends ServletInputStream { public ByteArrayInputStream stream; public void setData(byte[] data) { stream = new ByteArrayInputStream(data); } @Override public int read() throws IOException { return stream.read(); } @Override public boolean isReady() { return true; } @Override public boolean isFinished() { return stream.available() > 0; } @Override public void setReadListener(ReadListener readListener) { } } } private static class ResettableStreamHttpServletResponse extends HttpServletResponseWrapper { private ServletOutputStreamImpl servletStream; public ResettableStreamHttpServletResponse(HttpServletResponse response) { super(response); this.servletStream = new ServletOutputStreamImpl(); } public byte[] getData() { return this.servletStream.stream.toByteArray(); } @Override public ServletOutputStream getOutputStream() throws IOException { return servletStream; } @Override public PrintWriter getWriter() throws IOException { return new PrintWriter(servletStream.stream, true); } private static class ServletOutputStreamImpl extends ServletOutputStream { private ByteArrayOutputStream stream; public ServletOutputStreamImpl() { stream = new ByteArrayOutputStream(); } @Override public void write(int param) throws IOException { stream.write(param); } @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener writeListener) { } } } }
true
615f763447cd99693cf5446aaa5352522928d8ad
Java
realperlon/variation-service
/src/main/java/org/spice3d/variation/provider/CustomJAXBContextProvider.java
UTF-8
3,082
2.515625
3
[ "MIT" ]
permissive
package org.spice3d.variation.provider; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.JAXBContextProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spice3d.variation.model.VariationRecord; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import java.io.InputStream; import java.util.*; //By default a JAX-RS implementation will bootstrap a JAXBContext from the parameters or return type from a service method. //You can control how the JAXBContext is created through the ContextResolver mechanism. //The ContextResolver allows you to control what JAXBContext is used with a particular class. //In this example we tell the JAX-RS implementation to use a MOXy JAXBContext in which the metadata has been supplied via XML /** Expose our custom bean for representing variation records via JAXB * */ @Provider public class CustomJAXBContextProvider implements ContextResolver<JAXBContext> { private final String[] bindingFileNames = {"variationRecord.xml"}; public static final Class<?>[] cTypes = {VariationRecord.class}; static Logger logger = LoggerFactory.getLogger(CustomJAXBContextProvider.class); private JAXBContext context = null; private final Set<Class<?>> types; //private final List<Object> fileList; private final List<Object> inputStreamList; private Map<String, Object> props = new HashMap<String, Object>(1); public CustomJAXBContextProvider() { try { this.types = new HashSet<Class<?>>(Arrays.asList(cTypes)); inputStreamList = new ArrayList<Object>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for(String filename : bindingFileNames){ InputStream inputStream = classLoader.getResourceAsStream(filename); inputStreamList.add(inputStream); } props.put(JAXBContextProperties.OXM_METADATA_SOURCE, inputStreamList); this.context = JAXBContextFactory.createContext(cTypes, props); } catch(JAXBException e) { logger.error("Cant instantiate CustomJAXBContextProvider ", e.getMessage()); logger.debug("cause: ", e); throw new RuntimeException(e); } } public JAXBContext getContext(Class<?> type) { if(!types.contains(type)) { return null; // we don't support anything other than the listed types } if (context == null) { try { context = JAXBContext.newInstance(cTypes); } catch (JAXBException e) { // null will be returned which indicates that our custom provider won't/can't be used. logger.error("Context for CustomJAXBContextProvider is null. It cant be used ", e.getMessage()); logger.debug("cause: ", e); } } return context; } }
true