text
stringlengths
10
2.72M
package com.technology.share.domain; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; /** * 角色实体类 */ @TableName("t_role") @Data public class Role extends BaseEntity { /**角色名称*/ private String roleName; /**角色状态*/ private Boolean roleStatus; /**权限ID列表*/ @TableField(exist = false) private String pIds; /**是否删除(0:不删除1:删除)(添加时自动填充,且默认为不删除状态)*/ @TableLogic(value = "0",delval = "1") @TableField(fill = FieldFill.INSERT) private Boolean deleted; }
package eight.extend; //Dog Penguin Pet PetTest 表示继承 //继承表示父类跟子类的关系 //当两个类或者多个类具有相同属性和方法的时候,可以提取出来变成父类,子类可以继承 //子类跟父类是is-a的关系 //使用: // 1、继承的时候需要使用extends关键字 // 2、使用继承关系后,父类中的属性和方法都可以在子类中进行使用(非私有属性、非私有方法) // 3、Java中是单继承的 //super: 是直接对象父类的一个引用 //用途: // 1、 可以在子类中调用直接被父类覆盖的一个方法 super.父类方法名称 // 2、 当super在普通方法中使用的的话,可以任意位置编写 // 3、 当super在构造方法中使用的话,会调用父类的构造方法,一定要将super放在第一行 // 4、 在构造方法中super关键字和this关键字[ this() ]不能同时出现。 // 5、 父类中私有的属性和方法都不能被调用,包括构造方法 // 6、 子类的构造方法中都会默认的使用super关键字调用父类的构造方法 // 7、 如果super构造方法中显式指定了super的构造方法,那么无参构造方法就不会被调用 //总结: // 1、在创建子类对象的时候会优先创建父类对象。 // 2、所有的Java类都具有一个老祖宗类,称之为Object,是所有类的一个跟类。 // // //重写: // 必须要存在继承关系,当父类中的方法无法满足子类的需求的时候可以选择使用重写方式 // //注意: // 1、重写表示的是子类覆盖父类的方法,当覆盖之后,调用同样的方法的时候会优先调用子类 // 2、重写的方法名称,返回值类型,参数列表必须跟父类一致 // 3、子类重写的方法不允许比父类的方法具备更小的访问权限 // 父类 public 子类 public // 父类 protected 子类 public protected // 父类 default 子类 public protected default // 父类 private 子类 public protected default private //私有是不能被继承的 所以这一行的权限是没有的 // // 父类的静态方法子类可以被调用,但不可以被重写 public class PetTest { public static void main(String[] args){ Dog dog=new Dog(); dog.setName("大黄"); System.out.println(dog.getName()); dog.play(); //继承中的主函数 Pet pet=new Pet(); System.out.println(pet); //因为主方法中已经创建了Dog dog=new Dog();所以在此不用在次创建 System.out.println(dog); } }
package vinoos.cordova.iap.util.communication; public interface OnConnectListener { void connected(); }
package org.epclet.serializer; public class EPCletSemanticSequencer extends AbstractEPCletSemanticSequencer { }
package graphic.Cli; /** * Created by Michele on 15/06/2017. */ public interface Comando { void esegui(String[] parametri) throws ComandoNonValido; }
package com.tencent.mm.plugin.profile.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.R; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.az.a; import com.tencent.mm.model.au; import com.tencent.mm.model.bd; import com.tencent.mm.model.c; import com.tencent.mm.model.q; import com.tencent.mm.model.s; import com.tencent.mm.plugin.account.b; import com.tencent.mm.plugin.account.friend.a.ao; import com.tencent.mm.plugin.account.friend.a.g; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.wxpay.a$k; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.ui.base.n; import com.tencent.mm.ui.base.p; import com.tencent.mm.ui.widget.a.d; abstract class NormalUserFooterPreference$a implements e { boolean isDeleteCancel = false; final /* synthetic */ NormalUserFooterPreference lXw; private d lXx = null; protected abstract void bnA(); static /* synthetic */ void a(NormalUserFooterPreference$a normalUserFooterPreference$a) { s.i(NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw)); NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).Be(); if (NormalUserFooterPreference.p(normalUserFooterPreference$a.lXw)) { NormalUserFooterPreference.q(normalUserFooterPreference$a.lXw).setVisibility(8); normalUserFooterPreference$a.bnA(); } } static /* synthetic */ void b(NormalUserFooterPreference$a normalUserFooterPreference$a) { s.h(NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw)); NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).Bd(); if (NormalUserFooterPreference.p(normalUserFooterPreference$a.lXw)) { NormalUserFooterPreference.q(normalUserFooterPreference$a.lXw).setVisibility(0); normalUserFooterPreference$a.bnA(); } } static /* synthetic */ void c(NormalUserFooterPreference$a normalUserFooterPreference$a) { int i = 7; Intent intent = new Intent(); switch (NormalUserFooterPreference.l(normalUserFooterPreference$a.lXw)) { case 1: case 2: case 3: case 12: case 13: case a$k.AppCompatTheme_toolbarStyle /*58*/: case 59: case a$k.AppCompatTheme_popupMenuStyle /*60*/: intent.putExtra("k_outside_expose_proof_item_list", a.v(45, NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username)); i = 45; break; case 9: case 14: i = 35; break; case 18: i = NormalUserFooterPreference.m(normalUserFooterPreference$a.lXw) ? 2 : 1; intent.putStringArrayListExtra("k_outside_expose_proof_item_list", a.nv(NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username)); break; case 22: case 23: case 24: case 26: case 27: case 28: case 29: i = NormalUserFooterPreference.m(normalUserFooterPreference$a.lXw) ? 4 : 3; intent.putStringArrayListExtra("k_outside_expose_proof_item_list", a.nw(NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username)); break; case 25: i = NormalUserFooterPreference.m(normalUserFooterPreference$a.lXw) ? 6 : 5; if (!NormalUserFooterPreference.m(normalUserFooterPreference$a.lXw)) { intent.putExtra("k_outside_expose_proof_item_list", a.nx(!bi.oW(NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).taj) ? NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).taj : NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username)); break; } else { intent.putExtra("k_outside_expose_proof_item_list", a.v(i, NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username)); break; } case a$k.AppCompatTheme_actionModeSplitBackground /*30*/: intent.putStringArrayListExtra("k_outside_expose_proof_item_list", a.v(7, NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username)); break; default: i = 999; break; } intent.putExtra("k_username", NormalUserFooterPreference.a(normalUserFooterPreference$a.lXw).field_username); intent.putExtra("showShare", false); intent.putExtra("rawUrl", String.format("https://weixin110.qq.com/security/readtemplate?t=weixin_report/w_type&scene=%d#wechat_redirect", new Object[]{Integer.valueOf(i)})); com.tencent.mm.bg.d.b(NormalUserFooterPreference.b(normalUserFooterPreference$a.lXw), "webview", ".ui.tools.WebViewUI", intent); } public NormalUserFooterPreference$a(NormalUserFooterPreference normalUserFooterPreference) { this.lXw = normalUserFooterPreference; } protected void FC() { bnA(); bnC(); NormalUserFooterPreference.f(this.lXw).setOnClickListener(new 12(this)); NormalUserFooterPreference.g(this.lXw).setOnClickListener(new 13(this)); NormalUserFooterPreference.h(this.lXw).setOnClickListener(new 14(this)); NormalUserFooterPreference.i(this.lXw).setOnClickListener(new OnClickListener() { public final void onClick(View view) { NormalUserFooterPreference$a.c(NormalUserFooterPreference$a.this); } }); NormalUserFooterPreference.j(this.lXw).setOnClickListener(new OnClickListener() { public final void onClick(View view) { NormalUserFooterPreference$a.c(NormalUserFooterPreference$a.this); } }); NormalUserFooterPreference.k(this.lXw).setOnClickListener(new OnClickListener() { public final void onClick(View view) { NormalUserFooterPreference$a.c(NormalUserFooterPreference$a.this); } }); } protected void onDetach() { } public void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.NormalUserFooterPreference", "onSceneEnd: errType = " + i + " errCode = " + i2 + " errMsg = " + str + " " + lVar.getType()); } protected final void bnB() { NormalUserFooterPreference.b(this.lXw).addIconOptionMenu(0, R.g.mm_title_btn_menu, new 1(this)); } protected final void z(boolean z, boolean z2) { if (!z || !z2) { NormalUserFooterPreference.b(this.lXw).addIconOptionMenu(0, R.g.mm_title_btn_menu, new 11(this, z, z2)); } } protected void bnC() { if (NormalUserFooterPreference.d(this.lXw)) { NormalUserFooterPreference.b(this.lXw).showOptionMenu(false); } else if (!q.GF().equals(NormalUserFooterPreference.a(this.lXw).field_username)) { if (!com.tencent.mm.l.a.gd(NormalUserFooterPreference.a(this.lXw).field_type)) { z(false, false); } else if (!s.hH(NormalUserFooterPreference.a(this.lXw).field_username)) { bnB(); } } } final void bnD() { this.lXx = new d(NormalUserFooterPreference.b(this.lXw), 1, false); this.lXx.ofp = new 4(this); this.lXx.ofq = new n.d() { public final void onMMMenuItemSelected(MenuItem menuItem, int i) { switch (menuItem.getItemId()) { case 1: NormalUserFooterPreference$a.this.lXw.bny(); return; case 2: NormalUserFooterPreference$a.this.lXw.bnz(); return; default: return; } } }; this.lXx.bXO(); } final void JH(String str) { if (bi.oW(str)) { x.w("MicroMsg.NormalUserFooterPreference", "mod stranger remark, username is null"); return; } Intent intent = new Intent(); intent.putExtra("Contact_Scene", NormalUserFooterPreference.l(this.lXw)); intent.putExtra("Contact_mode_name_type", 0); intent.putExtra("Contact_ModStrangerRemark", true); intent.putExtra("Contact_User", NormalUserFooterPreference.a(this.lXw).field_username); intent.putExtra("Contact_Nick", NormalUserFooterPreference.a(this.lXw).field_nickname); intent.putExtra("Contact_RemarkName", NormalUserFooterPreference.a(this.lXw).field_conRemark); com.tencent.mm.plugin.profile.a.ezn.o(intent, this.lXw.mContext); } protected final void bnE() { h.mEJ.h(14553, new Object[]{Integer.valueOf(2), Integer.valueOf(2), NormalUserFooterPreference.a(this.lXw).field_username}); String str = NormalUserFooterPreference.a(this.lXw).field_username; if (s.hc(str)) { NormalUserFooterPreference.a(this.lXw).Bc(); au.HU(); c.FQ().b(new com.tencent.mm.aq.c(str)); au.HU(); c.FR().Ym(str); au.HU(); c.Ga().in(str); return; } String str2; this.isDeleteCancel = false; Context context = this.lXw.mContext; this.lXw.mContext.getString(R.l.app_tip); p a = com.tencent.mm.ui.base.h.a(context, this.lXw.mContext.getString(R.l.app_waiting), true, new 6(this)); if (this.isDeleteCancel) { str2 = null; } else { str2 = com.tencent.mm.pluginsdk.wallet.e.Uk(NormalUserFooterPreference.a(this.lXw).field_username); } if (bi.oW(str2)) { sa(str); return; } a.dismiss(); com.tencent.mm.ui.base.h.a(this.lXw.mContext, false, this.lXw.mContext.getString(R.l.wallet_delete_contact_note, new Object[]{str2}), null, this.lXw.mContext.getString(R.l.goto_conversation), this.lXw.mContext.getString(R.l.delete_contact), new 7(this), new 8(this, a, str), -1, R.e.alert_btn_color_warn); } final void sa(String str) { g gVar = null; NormalUserFooterPreference.a(this.lXw).Bc(); if (ab.XR(str)) { ((com.tencent.mm.openim.a.a) com.tencent.mm.kernel.g.l(com.tencent.mm.openim.a.a.class)).oB(str); } else { au.HU(); c.FQ().b(new com.tencent.mm.aq.c(str)); } bd.a(str, new bd.a() { public final boolean Ip() { return NormalUserFooterPreference$a.this.isDeleteCancel; } public final void Io() { if (NormalUserFooterPreference$a.this.lXw.eHw != null) { NormalUserFooterPreference$a.this.lXw.eHw.dismiss(); } } }); au.HU(); c.FR().a(str, NormalUserFooterPreference.a(this.lXw)); au.HU(); c.FW().Yp(str); com.tencent.mm.az.c.d(0, str); com.tencent.mm.az.c.d(0, NormalUserFooterPreference.a(this.lXw).field_encryptUsername); switch (NormalUserFooterPreference.l(this.lXw)) { case 10: com.tencent.mm.platformtools.x.I(this.lXw.mContext, str); break; case 12: ao pA = b.getQQListStg().pA(str); if (pA != null) { pA.eLx = 1; b.getQQListStg().a(pA.eLw, pA); break; } break; case 13: com.tencent.mm.plugin.account.friend.a.a pp = b.getAddrUploadStg().pp(str); if (!(pp == null || bi.oW(pp.eJG))) { pp.status = 1; b.getAddrUploadStg().a(pp.Xh(), pp); } com.tencent.mm.platformtools.x.I(this.lXw.mContext, str); break; case 31: com.tencent.mm.plugin.account.friend.a.h facebookFrdStg = b.getFacebookFrdStg(); Cursor b = facebookFrdStg.dCZ.b("select facebookfriend.fbid,facebookfriend.fbname,facebookfriend.fbimgkey,facebookfriend.status,facebookfriend.username,facebookfriend.nickname,facebookfriend.nicknamepyinitial,facebookfriend.nicknamequanpin,facebookfriend.sex,facebookfriend.personalcard,facebookfriend.province,facebookfriend.city,facebookfriend.signature,facebookfriend.alias,facebookfriend.type,facebookfriend.email from facebookfriend where facebookfriend.username = \"" + str + "\"", null, 2); if (b != null) { g gVar2; if (b.moveToFirst()) { gVar2 = new g(); gVar2.d(b); } else { gVar2 = null; } b.close(); gVar = gVar2; } if (gVar != null) { gVar.status = 100; b.getFacebookFrdStg().a(gVar); break; } break; case a$k.AppCompatTheme_toolbarStyle /*58*/: case 59: case a$k.AppCompatTheme_popupMenuStyle /*60*/: b.getGoogleFriendStorage().ab(str, 2); break; } if (NormalUserFooterPreference.l(this.lXw) == 9) { x.i("MicroMsg.NormalUserFooterPreference", "add scene unkown, check the contact getsource: " + NormalUserFooterPreference.a(this.lXw).getSource()); switch (NormalUserFooterPreference.a(this.lXw).getSource()) { case 10: case 13: x.i("MicroMsg.NormalUserFooterPreference", "delete the system contact info added by wechat"); com.tencent.mm.platformtools.x.I(this.lXw.mContext, str); break; } } if (NormalUserFooterPreference.o(this.lXw) == 0) { Intent intent = new Intent(); intent.addFlags(67108864); com.tencent.mm.plugin.profile.a.ezn.q(intent, this.lXw.mContext); return; } NormalUserFooterPreference.b(this.lXw).setResult(-1, NormalUserFooterPreference.b(this.lXw).getIntent().putExtra("_delete_ok_", true)); ((Activity) this.lXw.mContext).finish(); } }
package vc.lang.types; import java.util.HashMap; import vc.lang.impl.EvaluationContext; import vc.lang.impl.deck.ExecutableCard; import vc.lang.runtime.ExecException; public class Function extends Token { private byte[] name; public Function(byte[] name) { this.name = name; } @Override public void eval(EvaluationContext context) throws ExecException { ExecutableCard card = context.getDeck().cardByKey(name); if (card == null) { context.exception("undefined function invocation") .details("name: `%s'", new String(name)).toss(); } else { card.execute(context); } } @Override public boolean sameValue(Token other) { return name.equals(((Function) other).getSymbol()); } @Override public byte[] getSymbol() { return name; } public String toString() { return String.format("Function: `%s'", new String(name)); } }
package com.techlab.playertest; import com.techlab.player.Player; import java.io.Serializable; public class PlayerTest implements Serializable{ public static void main(String[] args) { Player p1 = new Player("Sonam", 24, 101); printInfo(p1); System.out.println(); Player p2 = new Player("Anjali", 102); printInfo(p2); System.out.println(); Player elder = p1.whoIsElder(p2); printInfo(elder); } public static void printInfo(Player p) { System.out.println("name:-" + p.getName()); System.out.println("age :- " + p.getAge()); System.out.println("id :- " + p.getId()); System.out.println("Elder person is :- " + p.getAge()); } }
package com.hb.rssai.presenter; import android.content.Context; import com.hb.rssai.constants.Constant; import com.hb.rssai.util.T; import com.hb.rssai.view.iView.IMineView; import java.util.HashMap; import java.util.Map; import retrofit2.adapter.rxjava.HttpException; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Administrator on 2017/8/20 0020. */ public class MinePresenter extends BasePresenter<IMineView> { private Context mContext; private IMineView iMineView; public MinePresenter(Context context, IMineView iMineView) { mContext = context; this.iMineView = iMineView; } public void getUser() { loginApi.getUserInfo(getParams()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resUser -> { iMineView.setResult(resUser); }, this::loadUserError); } //添加收藏 public void addCollection() { collectionApi.add(getAddParams()).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resShareCollection -> { iMineView.setAddResult(resShareCollection); }, this::loadError); } //添加订阅 public void addSubscription() { findApi.subscribe(getSubscribeParams()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resBase -> { iMineView.setAddSubscribeResult(resBase); }, this::loadError); } //获取消息数 public void getMessages() { messageApi.list(getMessageParams()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resMessageList -> { iMineView.setMessageListResult(resMessageList); }, this::loadError); } private void loadError(Throwable throwable) { throwable.printStackTrace(); if (throwable instanceof HttpException) { if (((HttpException) throwable).response().code() == 401) { iMineView.showNoLogin(); } else { iMineView.showNetError(); } } else { iMineView.showNetError(); } } private void loadUserError(Throwable throwable) { throwable.printStackTrace(); if (throwable instanceof HttpException) { if (((HttpException) throwable).response().code() == 401) { T.ShowToast(mContext, Constant.MSG_NO_LOGIN); } else { iMineView.showNetError(); } } else { iMineView.showNetError(); } iMineView.showLoadUserError(); } private Map<String, String> getParams() { Map<String, String> map = new HashMap<>(); String userId = iMineView.getUserId(); String jsonParams = "{\"userId\":\"" + userId + "\"}"; map.put(Constant.KEY_JSON_PARAMS, jsonParams); System.out.println(map); return map; } private Map<String, String> getSubscribeParams() { Map<String, String> map = new HashMap<>(); String subscribeId = iMineView.getSubscribeId(); String userId = iMineView.getUserId(); String jsonParams = "{\"userId\":\"" + userId + "\",\"subscribeId\":\"" + subscribeId + "\"}"; map.put(Constant.KEY_JSON_PARAMS, jsonParams); return map; } private Map<String, String> getAddParams() { Map<String, String> map = new HashMap<>(); String informationId = iMineView.getInformationId(); boolean isDel = false; String userId = iMineView.getUserId(); String jsonParams = "{\"isDel\":\"" + isDel + "\",\"informationId\":\"" + informationId + "\",\"userId\":\"" + userId + "\"}"; map.put(Constant.KEY_JSON_PARAMS, jsonParams); return map; } private Map<String, String> getMessageParams() { Map<String, String> map = new HashMap<>(); String userId = iMineView.getUserId(); String jsonParams = "{\"userId\":\"" + userId + "\",\"page\":\"" + 1 + "\",\"size\":\"" + Constant.PAGE_SIZE + "\"}"; map.put(Constant.KEY_JSON_PARAMS, jsonParams); System.out.println(map); return map; } }
package com.example.sunnysingh.home; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.ActivityNotFoundException; import android.content.Intent; import android.speech.RecognizerIntent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity { private static final int REQUEST_ENABLE_BT =1; List<String> dname = new ArrayList<String>(); List<String> mac = new ArrayList<String>(); BluetoothSocket btSocket; BluetoothDevice device; BluetoothAdapter mBluetoothAdapter; String address = ""; TextView mydevice; int BLUETOOTH_REQUEST = 1; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydevice = (TextView) findViewById(R.id.device); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) { String deviceName = device.getName(); String deviceAddress = device.getAddress(); if (deviceName.equals("HC-05") && deviceAddress.equals("98:D3:31:80:97:77")) { mydevice.setText("Master Bedroom"); address = "98:D3:31:80:97:77"; } } } } else { Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) { String deviceName = device.getName(); String deviceAddress = device.getAddress(); if (deviceName.equals("HC-05") && deviceAddress.equals("98:D3:31:80:97:77")) { mydevice.setText("Master Bedroom"); address = "98:D3:31:80:97:77"; } } } } mydevice.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { address = "98:D3:31:80:97:77"; Log.i("cool:",address); device = mBluetoothAdapter.getRemoteDevice(address); try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Toast.makeText(getBaseContext(),"Check & Reset your device ",Toast.LENGTH_LONG).show(); } mBluetoothAdapter.cancelDiscovery(); try { btSocket.connect(); Toast.makeText(getBaseContext(),"Connected to Master Bedroom",Toast.LENGTH_LONG).show(); BTSocket.setSocket(btSocket); Intent i = new Intent(MainActivity.this,CommunicationView.class); startActivity(i); } catch (IOException e1) { Toast.makeText(getBaseContext(),"Connect to correct device or Device Offline", Toast.LENGTH_LONG).show(); } } }); } public static class BTSocket{ private static BluetoothSocket socket; public static synchronized BluetoothSocket getSocket(){ return socket; } public static synchronized void setSocket(BluetoothSocket socket1){ socket = socket1; } } }
package com.haozileung.rpc.client; import com.haozileung.rpc.common.protocal.RpcRequest; import com.haozileung.rpc.common.protocal.RpcResponse; import com.haozileung.rpc.common.protocal.ResponseFuture; import java.util.concurrent.TimeUnit; public interface IClient { void connect(); RpcResponse syncSend(RpcRequest request); RpcResponse syncSend(RpcRequest request, Long time, TimeUnit unit); ResponseFuture<RpcResponse> asyncSend(RpcRequest request); void close(); boolean isClose(); }
package com.example.arastech.aronotes; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.graphics.drawable.Drawable; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.Image; import android.media.ImageReader; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.RemoteException; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.util.Size; import android.util.SparseIntArray; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.BeaconConsumer; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.BeaconParser; import org.altbeacon.beacon.Identifier; import org.altbeacon.beacon.RangeNotifier; import org.altbeacon.beacon.Region; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class MainActivity extends AppCompatActivity implements BeaconConsumer, RangeNotifier { private BeaconManager mBeaconManager; private static final String TAG = "AndroidCameraApi"; private FloatingActionButton takePictureButton; private FloatingActionButton tutoButton; private TextView tutoText; private TextureView textureView; private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } private String cameraId; protected CameraDevice cameraDevice; protected CameraCaptureSession cameraCaptureSessions; protected CaptureRequest captureRequest; protected CaptureRequest.Builder captureRequestBuilder; private Size imageDimension; private ImageReader imageReader; private File file; private static final int REQUEST_CAMERA_PERMISSION = 200; private boolean mFlashSupported; private Handler mBackgroundHandler; private HandlerThread mBackgroundThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBeaconManager = BeaconManager.getInstanceForApplication(this); // In this example, we will use Eddystone protocol, so we have to define it here mBeaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT)); // Binds this activity to the BeaconService mBeaconManager.bind(this); textureView = (TextureView) findViewById(R.id.texture); assert textureView != null; textureView.setSurfaceTextureListener(textureListener); takePictureButton = (FloatingActionButton) findViewById(R.id.floatingButtonTakePicture); tutoButton = (FloatingActionButton) findViewById(R.id.floatingButtonTuto); tutoText = (TextView) findViewById(R.id.textTuto); assert takePictureButton != null; takePictureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { takePicture(); } }); tutoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggleTutorial(); } }); } TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { //open your camera here openCamera(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Transform you image captured size according to the surface width and height } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(CameraDevice camera) { //This is called when the camera is open Log.e(TAG, "onOpened"); cameraDevice = camera; createCameraPreview(); } @Override public void onDisconnected(CameraDevice camera) { cameraDevice.close(); } @Override public void onError(CameraDevice camera, int error) { cameraDevice.close(); cameraDevice = null; } }; final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); Toast.makeText(MainActivity.this, "Saved:" + file, Toast.LENGTH_SHORT).show(); createCameraPreview(); } }; protected void startBackgroundThread() { mBackgroundThread = new HandlerThread("Camera Background"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); } protected void stopBackgroundThread() { mBackgroundThread.quitSafely(); try { mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } catch (InterruptedException e) { e.printStackTrace(); } } protected void toggleTutorial(){ if(tutoText.getText().equals("")){ tutoText.setText("Approchez vous des oeuvres d'art avec votre smartphone, si une information y est caché, une fenêtre s'ouvrira pour vous les dévoiler !"); tutoText.setBackgroundColor(Color.argb(130, 40, 70, 150)); }else{ tutoText.setText(""); tutoText.setBackgroundColor(Color.argb(0, 40, 70, 150)); } } protected void takePicture() { if(null == cameraDevice) { Log.e(TAG, "cameraDevice is null"); return; } CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId()); Size[] jpegSizes = null; if (characteristics != null) { jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG); } int width = 640; int height = 480; if (jpegSizes != null && 0 < jpegSizes.length) { width = jpegSizes[0].getWidth(); height = jpegSizes[0].getHeight(); } ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1); List<Surface> outputSurfaces = new ArrayList<Surface>(2); outputSurfaces.add(reader.getSurface()); outputSurfaces.add(new Surface(textureView.getSurfaceTexture())); final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(reader.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); // Orientation int rotation = getWindowManager().getDefaultDisplay().getRotation(); captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation)); Long tsLong = System.currentTimeMillis()/1000; String ts = tsLong.toString(); final File file = new File(Environment.getExternalStorageDirectory()+"/ARONotes_"+ts+".jpg"); ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { Image image = null; try { image = reader.acquireLatestImage(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.capacity()]; buffer.get(bytes); save(bytes); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (image != null) { image.close(); } } } private void save(byte[] bytes) throws IOException { OutputStream output = null; try { output = new FileOutputStream(file); output.write(bytes); } finally { if (null != output) { output.close(); } } } }; reader.setOnImageAvailableListener(readerListener, mBackgroundHandler); final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); Toast.makeText(MainActivity.this, "Saved:" + file, Toast.LENGTH_SHORT).show(); createCameraPreview(); } }; cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) { try { session.capture(captureBuilder.build(), captureListener, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(CameraCaptureSession session) { } }, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } protected void createCameraPreview() { try { SurfaceTexture texture = textureView.getSurfaceTexture(); assert texture != null; texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight()); Surface surface = new Surface(texture); captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); captureRequestBuilder.addTarget(surface); cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){ @Override public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { //The camera is already closed if (null == cameraDevice) { return; } // When the session is ready, we start displaying the preview. cameraCaptureSessions = cameraCaptureSession; updatePreview(); } @Override public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show(); } }, null); } catch (CameraAccessException e) { e.printStackTrace(); } } private void openCamera() { CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); Log.e(TAG, "is camera open"); try { cameraId = manager.getCameraIdList()[0]; CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); assert map != null; imageDimension = map.getOutputSizes(SurfaceTexture.class)[0]; // Add permission for camera and let user grant the permission if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION); return; } manager.openCamera(cameraId, stateCallback, null); } catch (CameraAccessException e) { e.printStackTrace(); } Log.e(TAG, "openCamera X"); } protected void updatePreview() { if(null == cameraDevice) { Log.e(TAG, "updatePreview error, return"); } captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); try { cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } private void closeCamera() { if (null != cameraDevice) { cameraDevice.close(); cameraDevice = null; } if (null != imageReader) { imageReader.close(); imageReader = null; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_CAMERA_PERMISSION) { if (grantResults[0] == PackageManager.PERMISSION_DENIED) { // close the app Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show(); finish(); } } } @Override protected void onResume() { super.onResume(); Log.e(TAG, "onResume"); startBackgroundThread(); if (textureView.isAvailable()) { openCamera(); } else { textureView.setSurfaceTextureListener(textureListener); } } @Override protected void onPause() { Log.e(TAG, "onPause"); //closeCamera(); stopBackgroundThread(); super.onPause(); } @Override public void onBeaconServiceConnect() { // Encapsulates a beacon identifier of arbitrary byte length ArrayList<Identifier> identifiers = new ArrayList<>(); // Set null to indicate that we want to match beacons with any value identifiers.add(null); // Represents a criteria of fields used to match beacon Region region = new Region("AllBeaconsRegion", identifiers); try { // Tells the BeaconService to start looking for beacons that match the passed Region object mBeaconManager.startRangingBeaconsInRegion(region); } catch (RemoteException e) { e.printStackTrace(); } // Specifies a class that should be called each time the BeaconService gets ranging data, once per second by default mBeaconManager.addRangeNotifier(this); } @Override public void didRangeBeaconsInRegion(Collection<Beacon> collection, org.altbeacon.beacon.Region region) { if (collection.size() > 0) { Toast.makeText(getApplicationContext(),"The first beacon I see is about "+collection.iterator().next().getDistance()+" meters away.",Toast.LENGTH_LONG).show(); Log.i(TAG, "The first beacon I see is about "+collection.iterator().next().getDistance()+" meters away."); } } }
package nl.nlxdodge.scrapyard.blocks; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.block.AbstractBlock; import net.minecraft.block.Block; import net.minecraft.block.Material; import net.minecraft.block.MaterialColor; import net.minecraft.client.render.RenderLayer; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import nl.nlxdodge.scrapyard.ScrapyardMod; public class ModBlocks { public static final Block SCRAP_BLOCK = new ScrapBlock(AbstractBlock.Settings.of(Material.METAL, MaterialColor.BROWN)); public static final Block BALLOON_BLOCK = new BalloonBlock(AbstractBlock.Settings.of(Material.SPONGE, MaterialColor.BROWN)); public static void registerBlocks() { Registry.register(Registry.BLOCK, new Identifier("scrapyard", "scrap_block"), SCRAP_BLOCK); Registry.register(Registry.ITEM, new Identifier("scrapyard", "scrap_block"), new BlockItem(SCRAP_BLOCK, new Item.Settings().group(ScrapyardMod.SCRAP_YARD_GROUP))); Registry.register(Registry.BLOCK, new Identifier("scrapyard", "balloon_block"), BALLOON_BLOCK); Registry.register(Registry.ITEM, new Identifier("scrapyard", "balloon_block"), new BlockItem(BALLOON_BLOCK, new Item.Settings().group(ScrapyardMod.SCRAP_YARD_GROUP))); BlockRenderLayerMap.INSTANCE.putBlock(BALLOON_BLOCK, RenderLayer.getCutout()); } }
package com.jean.sbc.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonIgnore; import com.jean.sbc.domain.enums.CustomerType; import com.jean.sbc.domain.enums.Profile; @Entity public class Customer implements Serializable { private static final long serialVersionUID = -5275965071840794191L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @Column(unique = true) private String email; private String socialInsuranceOrBusinessNumber; private Integer customerType; @JsonIgnore private String password; @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL) private List<Address> addresses = new ArrayList<Address>(); @ElementCollection @CollectionTable(name = "TELEPHONE") private Set<String> telephones = new HashSet<>(); @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "PROFILES") private Set<Integer> profiles = new HashSet<Integer>(); @JsonIgnore @OneToMany(mappedBy = "customer") private List<Order> orders = new ArrayList<Order>(); public Customer() { this.addProfile(Profile.CUSTOMER); } public Customer(Integer id, String name, String email, String socialInsuranceOrBusinessNumber, CustomerType customerType, String password) { super(); this.id = id; this.name = name; this.email = email; this.socialInsuranceOrBusinessNumber = socialInsuranceOrBusinessNumber; this.customerType = customerType == null ? null : customerType.getCod(); this.password = password; this.addProfile(Profile.CUSTOMER); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSocialInsuranceOrBusinessNumber() { return socialInsuranceOrBusinessNumber; } public void setSocialInsuranceOrBusinessNumber(String socialInsuranceOrBusinessNumber) { this.socialInsuranceOrBusinessNumber = socialInsuranceOrBusinessNumber; } public CustomerType getCustomerType() { return CustomerType.toEnum(customerType); } public void setCustomerType(CustomerType customerType) { this.customerType = customerType.getCod(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<Profile> getProfiles() { return this.profiles.stream().map(profile -> Profile.toEnum(profile)).collect(Collectors.toSet()); } public void addProfile(Profile profile) { this.profiles.add(profile.getCod()); } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } public Set<String> getTelephones() { return telephones; } public void setTelephones(Set<String> telephones) { this.telephones = telephones; } public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Customer other = (Customer) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
package com.nhatdear.sademo.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.nhatdear.sademo.R; import com.nhatdear.sademo.components.MyCustomButtonView; import com.nhatdear.sademo.components.MyCustomEditText; import com.nhatdear.sademo.events.SA_ErrorEvent; import com.nhatdear.sademo.helpers.SA_Helper; import com.nhatdear.sademo.helpers.SA_Validator; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import static com.nhatdear.sademo.helpers.SA_Helper.EMAIL_IS_NOT_CORRECT_FORMAT; public class SA_ResetPasswordFragment extends Fragment { private static final String EMAIL = "email"; MyCustomEditText et_email; MyCustomButtonView btn_reset; private String email; private OnFragmentInteractionListener mListener; public SA_ResetPasswordFragment() { // Required empty public constructor } public static SA_ResetPasswordFragment newInstance(String email) { SA_ResetPasswordFragment fragment = new SA_ResetPasswordFragment(); Bundle args = new Bundle(); args.putString(EMAIL, email); fragment.setArguments(args); return fragment; } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { email = getArguments().getString(EMAIL); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_reset_password, container, false); et_email = (MyCustomEditText)v.findViewById(R.id.et_email); et_email.setText(email); btn_reset = (MyCustomButtonView)v.findViewById(R.id.btn_reset); btn_reset.setOnClickListener(view -> onButtonPressed()); return v; } public void onButtonPressed() { if (mListener != null && validateForm()) { mListener.doResetPasswordAction(et_email.getText().toString()); } } private boolean validateForm() { boolean valid = true; String email = et_email.getText().toString(); if (TextUtils.isEmpty(email)) { et_email.setError("Required."); valid = false; } else if (!SA_Validator.validateEmail(email)) { et_email.setError(EMAIL_IS_NOT_CORRECT_FORMAT); valid = false; } else { et_email.setError(null); } return valid; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Subscribe(threadMode = ThreadMode.MAIN) public void onError(SA_ErrorEvent event) { SA_Helper.showSnackbar(getView(), event.mMessage); } public interface OnFragmentInteractionListener { void doResetPasswordAction(String s); } }
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.ad.domain.impl.report; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import seava.ad.domain.impl.report.DsReport; import seava.ad.domain.impl.report.ReportParam; import seava.j4e.domain.impl.AbstractAuditable; @Entity @Table(name = DsReportParam.TABLE_NAME) public class DsReportParam extends AbstractAuditable implements Serializable { public static final String TABLE_NAME = "AD_RPT_DS_PARAM"; private static final long serialVersionUID = -8865917134914502125L; /** Reference to the data-source field. */ @Column(name = "DSFIELD", length = 255) private String dsField; @Column(name = "STATICVALUE", length = 400) private String staticValue; @ManyToOne(fetch = FetchType.LAZY, targetEntity = DsReport.class) @JoinColumn(name = "DSREPORT_ID", referencedColumnName = "ID") private DsReport dsReport; @ManyToOne(fetch = FetchType.LAZY, targetEntity = ReportParam.class) @JoinColumn(name = "REPORTPARAM_ID", referencedColumnName = "ID") private ReportParam reportParam; public String getDsField() { return this.dsField; } public void setDsField(String dsField) { this.dsField = dsField; } public String getStaticValue() { return this.staticValue; } public void setStaticValue(String staticValue) { this.staticValue = staticValue; } public DsReport getDsReport() { return this.dsReport; } public void setDsReport(DsReport dsReport) { if (dsReport != null) { this.__validate_client_context__(dsReport.getClientId()); } this.dsReport = dsReport; } public ReportParam getReportParam() { return this.reportParam; } public void setReportParam(ReportParam reportParam) { if (reportParam != null) { this.__validate_client_context__(reportParam.getClientId()); } this.reportParam = reportParam; } @PrePersist public void prePersist() { super.prePersist(); } @PreUpdate public void preUpdate() { super.preUpdate(); } }
package bnorm.utils; /** * A utility class for common trigonometric functions. * * @author Brian Norman * @version 1.1 */ public final class Trig { /** * The {@link Double} representation of a complete circle in radians, which is 2*PI. */ public static final double CIRCLE = 2.0 * Math.PI; /** * The {@link Double} representation of half of a complete circle in radians, which is PI. */ public static final double HALF_CIRCLE = Math.PI; /** * The {@link Double} representation of quarter of a complete circle in radians, which is PI/2. */ public static final double QUARTER_CIRCLE = Math.PI / 2.0; /** * Don't let anyone instantiate this class. */ private Trig() { } /** * Returns the angle from the origin to the specified coordinates, <code>(x, y)</code>. * * @param x * the ordinate coordinate. * @param y * the abscissa coordinate. * @return the angle to the specified coordinates. */ public static double angle(double x, double y) { return StrictMath.atan2(x, y); } /** * Returns the sine of the specified angle in radians. * * @param radians * an angle in radians. * @return the sine of the argument. */ public static double sin(double radians) { return StrictMath.sin(radians); } /** * Returns the cosine of the specified angle in radians. * * @param radians * an angle in radians. * @return the cosine of the argument. */ public static double cos(double radians) { return StrictMath.cos(radians); } /** * Returns the tangent of the specified angle in radians. * * @param radians * an angle in radians. * @return the tangent of the argument. */ public static double tan(double radians) { return StrictMath.tan(radians); } /** * Returns the arc sine of the specified angle in radians. * * @param ratio * the ratio between sides. * @return the arc sine of the argument. */ public static double asin(double ratio) { return StrictMath.asin(ratio); } /** * Returns the arc cosine of the specified angle in radians. * * @param ratio * the ratio between sides. * @return the arc cosine of the argument. */ public static double acos(double ratio) { return StrictMath.acos(ratio); } /** * Returns the arc tangent of the specified angle in radians. * * @param ratio * the ratio between sides. * @return the arc tangent of the argument. */ public static double atan(double ratio) { return StrictMath.atan(ratio); } /** * Returns the angle <i>theta</i> from the conversion of rectangular coordinates (<code>x</code> * ,&nbsp;<code>y</code>) to Robocode polar coordinates (<i>r</i>,&nbsp;<i>theta</i>). * * @param x * the abscissa coordinate. * @param y * the ordinate coordinate. * @return the <i>theta</i> component of the point (<i>r</i>,&nbsp;<i>theta</i>) in Robocode * polar coordinates that corresponds to the point (<code>x</code>,&nbsp;<code>y</code>) * in Cartesian coordinates. */ public static double atan2(double x, double y) { return StrictMath.atan2(x, y); } }
package com.abdallahhodieb.nanodegree.nanodegreeportfolio; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; 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 onClickProject1(View v) { displayMessage("Project 1"); } public void onClickProject2(View v) { displayMessage("Project 2"); } public void onClickProject3(View v) { displayMessage("Project 3"); } public void onClickProject4(View v) { displayMessage("Project 4"); } public void onClickProject5(View v) { displayMessage("Project 5"); } public void displayMessage(String message) { Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT); toast.show(); } }
// Sun Certified Java Programmer // Chapter 1, P43 // Declarations and Access Control public abstract class Car extends Vehicle { public abstract void goUpHill(); // Still abstract public void doCarThings() { // special car code goes here } }
package Servlet; import Conexion.Conexion; import Dao.BeanUsuario; import Dao.DaoUsuario_DB; import java.io.IOException; import java.io.PrintWriter; import static java.lang.System.out; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author LEO */ public class Servlet_Usu extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a * servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String accion=request.getParameter("accion"); try (PrintWriter out = response.getWriter()) { if(accion.equals("login")){ Login(request,response); // return; }if(accion.equals("logout")){ Logout(request, response); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a * servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a * servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet * description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> private void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Connection cn; Conexion con = new Conexion(); cn = con.conectar(); String usuario = request.getParameter("txtUsuario"); String clave = request.getParameter("txtClave"); Integer estadousu=1; try{ BeanUsuario beanusu=DaoUsuario_DB.VerificarUsuario(usuario,clave); if(usuario.equals(beanusu.getUsuario())){ if(clave.equals(beanusu.getPassword())){ if(estadousu.equals(beanusu.getEstado())){ // request.setAttribute("v","1"); request.getSession().setAttribute("parametroCodigo",beanusu.getUsuario()); response.sendRedirect("panel.jsp"); }else{ response.sendRedirect("index.jsp?mens='Usted ha sido inhabilitado del sistema"); request.setAttribute("v","0"); } }else{ response.sendRedirect("index.jsp?mens='Credenciales Incorrectas'"); request.setAttribute("v","0");} }else{ response.sendRedirect("index.jsp?mens='Credenciales Incorrectas'"); request.setAttribute("v","0");} }catch (Exception ex){ out.println(ex); } } private void Logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); response.sendRedirect("index.jsp"); } }
//just a generalNode class that I've used for various assignments so that I don't have to //always recreate one. public class generalNode { private int freq; public generalNode(int frequency) { freq = frequency; } public int getFrequency() { return freq; } public void setFrequency(int frequency) { freq = frequency; } }
package an1; import javax.faces.context.FacesContext; import an1.persistence.Membres; public class PageInscription { private Membres nouveauMembre; private SessionBean1 sessionBean1; public PageInscription() { sessionBean1 = (SessionBean1) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("sessionBean1"); nouveauMembre = sessionBean1.getMembreEnCours(); if (nouveauMembre == null) { nouveauMembre = new Membres(); //return; } } public void setNouveauMembre(Membres nouveauMembre) { this.nouveauMembre = nouveauMembre; } public Membres getNouveauMembre() { return nouveauMembre; } public String validation_action() { sessionBean1.setMembreEnCours(nouveauMembre); return "confirmation"; } public String annulation_action() { System.out.println("annulation"); return null; } }
package com.tencent.mm.plugin.fts.ui; import android.app.ActivityOptions; import android.content.Intent; import android.os.Build.VERSION; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Pair; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.tencent.mm.kernel.g; import com.tencent.mm.model.s; import com.tencent.mm.plugin.chatroom.b.b; import com.tencent.mm.plugin.fts.a.d.a.a; import com.tencent.mm.plugin.fts.a.d.c; import com.tencent.mm.plugin.fts.a.n; import com.tencent.mm.plugin.fts.ui.n.d; import com.tencent.mm.plugin.fts.ui.n.e; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; public class FTSChattingConvUI extends FTSBaseUI implements OnClickListener { private ab guS; private String jso; private View jwr; private f jws; public void onCreate(Bundle bundle) { super.onCreate(bundle); initView(); c fTSImageLoader = ((n) g.n(n.class)).getFTSImageLoader(); if (fTSImageLoader != null) { fTSImageLoader.aPO(); } } protected final void initView() { super.initView(); this.jwr = findViewById(d.search_record_layout); this.jwr.setVisibility(0); RecyclerView recyclerView = (RecyclerView) findViewById(d.gird_title_view); ActionBarActivity actionBarActivity = this.mController.tml; recyclerView.setLayoutManager(new GridLayoutManager(aQM() ? 2 : 3)); recyclerView.a(new 1(this)); recyclerView.setAdapter(new a(this)); } protected final void aQB() { this.jso = getIntent().getStringExtra("detail_username"); this.guS = ((i) g.l(i.class)).FR().Yg(this.jso); x.i("MicroMsg.FTS.FTSChattingConvUI", "initSearchData conversation=%s", new Object[]{this.jso}); } private boolean aQM() { return this.guS != null && ab.XR(this.guS.field_username); } protected final d a(e eVar) { if (this.jws == null) { this.jws = new f(eVar, this.jso); } return this.jws; } public final void a(a aVar) { if (s.fq(this.jso)) { R(this.bWm, 10, aVar.position + 1); } else { R(this.bWm, 11, aVar.position + 1); } } protected final void aQG() { super.aQG(); this.jwr.setVisibility(0); } protected final void aQE() { super.aQE(); this.jwr.setVisibility(8); } protected final void aQF() { super.aQF(); this.jwr.setVisibility(8); } protected final void aQD() { super.aQD(); this.jwr.setVisibility(8); } private void kB(int i) { if (s.fq(this.jso)) { if (((b) g.l(b.class)).Ga().ii(this.jso).Nn() == null) { return; } if (i == 0) { h.mEJ.h(14569, new Object[]{Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(r0.Nn().size()), Integer.valueOf(1)}); return; } h.mEJ.h(14569, new Object[]{Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(r0.Nn().size()), Integer.valueOf(1)}); } else if (i == 0) { h.mEJ.h(14569, new Object[]{Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)}); } else { h.mEJ.h(14569, new Object[]{Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)}); } } protected final void CO(String str) { int i = 1; super.CO(str); boolean fq = s.fq(this.jso); h hVar = h.mEJ; Object[] objArr = new Object[9]; objArr[0] = Integer.valueOf(0); objArr[1] = Integer.valueOf(1); objArr[2] = Integer.valueOf(0); objArr[3] = Integer.valueOf(0); objArr[4] = Integer.valueOf(0); objArr[5] = Integer.valueOf(0); objArr[6] = Integer.valueOf(0); objArr[7] = Integer.valueOf(0); if (!fq) { i = 0; } objArr[8] = Integer.valueOf(i); hVar.h(14569, objArr); } protected final int getLayoutId() { return e.fts_detail_ui; } protected void onDestroy() { super.onDestroy(); this.jws.finish(); c fTSImageLoader = ((n) g.n(n.class)).getFTSImageLoader(); if (fTSImageLoader != null) { fTSImageLoader.aPM(); } } public void onClick(View view) { Bundle bundle = null; if (view instanceof TextView) { int intValue = ((Integer) view.getTag()).intValue(); if (!s.fq(this.jso)) { intValue++; } Intent intent; if (intValue == 0) { x.i("MicroMsg.FTS.FTSChattingConvUI", "onSearchMemberDetail"); intent = new Intent(); intent.putExtra("frome_scene", 1); intent.putExtra("RoomInfo_Id", this.jso); intent.putExtra("title", getResources().getString(n.g.search_by_chatroom_member)); com.tencent.mm.bg.d.b(this, "chatroom", ".ui.SelectMemberUI", intent); } else if (intValue == 1) { x.i("MicroMsg.FTS.FTSChattingConvUI", "onSearchDateDetail"); intent = new Intent(); intent.putExtra("detail_username", this.jso); com.tencent.mm.bg.d.b(this, "chatroom", ".ui.SelectDateUI", intent); kB(0); } else if (intValue == 2) { x.i("MicroMsg.FTS.FTSChattingConvUI", "onSeeImageVideoHistory"); intent = new Intent(); intent.putExtra("kintent_talker", this.jso); intent.putExtra("key_media_type", 1); com.tencent.mm.bg.d.e(this, "com.tencent.mm.ui.chatting.gallery.MediaHistoryGalleryUI", intent); kB(1); } else if (intValue == 3) { Bundle toBundle; x.i("MicroMsg.FTS.FTSChattingConvUI", "onSeeFileHistory"); Intent intent2 = new Intent(); intent2.putExtra("kintent_talker", this.jso); intent2.putExtra("key_media_type", 2); if (VERSION.SDK_INT >= 21) { toBundle = ActivityOptions.makeSceneTransitionAnimation(this, new Pair[0]).toBundle(); } else { toBundle = null; } com.tencent.mm.bg.d.c(this, "com.tencent.mm.ui.chatting.gallery.MediaHistoryListUI", intent2, toBundle); } else if (intValue == 4) { x.i("MicroMsg.FTS.FTSChattingConvUI", "onSeeUrlHistory"); intent = new Intent(); intent.putExtra("kintent_talker", this.jso); intent.putExtra("key_media_type", 3); if (VERSION.SDK_INT >= 21) { bundle = ActivityOptions.makeSceneTransitionAnimation(this, new Pair[0]).toBundle(); } com.tencent.mm.bg.d.c(this, "com.tencent.mm.ui.chatting.gallery.MediaHistoryListUI", intent, bundle); } else if (intValue == 5) { x.i("MicroMsg.FTS.FTSChattingConvUI", "onSeeUrlHistory"); intent = new Intent(); intent.putExtra("kintent_talker", this.jso); intent.putExtra("key_media_type", 4); if (VERSION.SDK_INT >= 21) { bundle = ActivityOptions.makeSceneTransitionAnimation(this, new Pair[0]).toBundle(); } com.tencent.mm.bg.d.c(this, "com.tencent.mm.ui.chatting.gallery.MediaHistoryListUI", intent, bundle); } else if (intValue == 6) { x.i("MicroMsg.FTS.FTSChattingConvUI", "onSeePayHistory"); intent = new Intent(); intent.putExtra("kintent_talker", this.jso); intent.putExtra("key_media_type", 5); if (VERSION.SDK_INT >= 21) { bundle = ActivityOptions.makeSceneTransitionAnimation(this, new Pair[0]).toBundle(); } com.tencent.mm.bg.d.c(this, "com.tencent.mm.ui.chatting.gallery.MediaHistoryListUI", intent, bundle); } } } private static void R(String str, int i, int i2) { x.v("MicroMsg.FTS.FTSChattingConvUI", "reportClick: %s", new Object[]{String.format("%s,%d,%d,%d,%d", new Object[]{str, Integer.valueOf(i), Integer.valueOf(5), Integer.valueOf(i2), Integer.valueOf(0)})}); h.mEJ.k(13234, r0); } }
package iterator; import global.RID; public class RIDScore { private RID rid; private float score; public RIDScore(RID rid, float score) { this.rid=rid; this.score=score; } public RID getRid() { return rid; } public void setRid(RID rid) { this.rid = rid; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } }
package com.leepc.chat.mapper; import com.leepc.chat.domain.Message; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import java.util.List; @Mapper @Repository public interface MessageMapper { @Select("select * from message") List<Message> findAll(); @Select("select * from message where id=#{id}") Message findById(Integer id); @Insert("insert into message(from_id,to_id,content,create_time) values(#{fromId},#{toId},#{content},#{createTime})") void insert(Message message); @Delete("delete from message where id = #{id}") void delete(Integer id); @Select("select * from message where to_id = #{userId}") List<Message> findByToUserId(Integer userId); }
package com.gkaraffa.polyhedron; public class Roll { private int tosses; private Die die; public Roll(int tosses, Die die) { this.tosses = tosses; this.die = die; } public int getTosses() { return tosses; } public Die getDie() { return die; } private static boolean nonZeroCheck(char c) { int i = (int) c; if ((i < 49) || (i > 57)) { return false; } return true; } private static boolean validateString(String rollString) { // format nDrr // 3-4 character length // 2nd character must be 'D' or 'd' // 1st character must be non zero integer // 3rd character must be non zero integer // 4th character may be empty or non zero integer // validate length int length = rollString.length(); if ((length < 3) || (length > 4)) { return false; } // validate 2nd character char dChar = rollString.charAt(1); if (!((dChar == 'D') || (dChar == 'd'))) { return false; } // validate 1st and 3rd characters if (!nonZeroCheck(rollString.charAt(0))) { return false; } if (!nonZeroCheck(rollString.charAt(2))) { return false; } if (length == 4) { if (!Character.isDigit(rollString.charAt(3))) { return false; } } return true; } public static Roll createRoll(String rollString) throws IllegalArgumentException { // validate if (!validateString(rollString)) { throw new IllegalArgumentException("Input string not properly formatted"); } // parse int tosses = Integer.parseInt(rollString.substring(0, 1)); int die; if (rollString.length() == 4) { die = Integer.parseInt(rollString.substring(2, 4)); } else { die = Integer.parseInt(rollString.substring(2, 3)); } // int less = 0; // create Roll Roll roll = new Roll(tosses, new Die(die)); // return Roll; return roll; } }
package com.lec.ex1_inputStreamOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Ex04_outputStream { public static void main(String[] args) { OutputStream os = null; try { // true추가시: 파일에 append, 없으면 덮어씀 os = new FileOutputStream("txtFile/out.txt", true); // 1. 스트림객체생성 String str = "모두 다 안녕이 필요한 시국\r\n"; byte[] bs = str.getBytes(); // stream byte 배열로 //!중요 !!! os.write(bs); // 2.파일쓰기 } catch (FileNotFoundException e) { System.out.println("파일 못 참음" + e.getMessage()); } catch (IOException e) { // IOException 하나로 묶었다 System.out.println("파일 쓰기 오류" + e.getMessage()); } finally { try { if (os != null) os.close(); } catch (Exception ignore) { } } } }
package one.harmony.cmd; import one.harmony.common.Config; import one.harmony.rpc.HmyResponse; import one.harmony.rpc.RPC; /** * Blockchain class retrieves the harmony protocol version. * * @author gupadhyaya * */ public class Blockchain { /** * GetProtocolVersion of Harmony network. * * @return protocol version * @throws Exception */ public static String getProtocolVersion() throws Exception { RPC rpc = new RPC(Config.node); HmyResponse response = rpc.getProtocolVersion().send(); if (response.hasError()) { throw new Exception("failed to fetch protocol version"); } return response.getResult(); } public static void main(String[] args) throws Exception { System.out.println(getProtocolVersion()); } }
package gov.usgs.aqcu.calc; import java.time.Instant; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import gov.usgs.aqcu.model.FieldVisitReading; //TODO needs testing public class LastValidVisitCalculator { Map<String, Instant> lastVisitMap = new HashMap<>(); public List<FieldVisitReading> fill(List<FieldVisitReading> readings) { Collections.sort(readings, new Comparator<FieldVisitReading>() { @Override public int compare(FieldVisitReading reading1, FieldVisitReading reading2) { if(reading1 == null && reading2 == null) { return 0; } if(reading1 == null && reading2 != null) { return -1; } if(reading1 != null && reading2 == null) { return 1; } return reading1.getVisitTime().compareTo(reading2.getVisitTime()); } }); for(FieldVisitReading reading : readings) { String value = reading.getValue(); String method = reading.getMonitoringMethod(); if(value != null && (value.matches("[-+]?\\d*\\.?\\d+") || "no mark".equals(value.toLowerCase().trim())) && method != null) { Instant previousDate = lastVisitMap.get(method); if(previousDate != null) { reading.setLastVisitPrior(previousDate); } lastVisitMap.put(method, reading.getVisitTime()); } } return readings; } }
package com.example.spring.properties; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.core.io.support.SpringFactoriesLoader; public class FactoryLoader { @Test public void load() { SpringFactoriesLoader.loadFactories(null, this.getClass().getClassLoader()); } }
package com.organization.curso.entidades.enums; public enum PedidoStatus { //Forma simples: mas não recomendável pois pode haver diferença no INDEX conforme inserção entre valores /* Aguardando_Pagamento, Pago, Enviado, Entregue, Cancelado; */ //Forma Ideal Aguardando_Pagamento(1), Pago(2), Enviado(3), Entregue(4), Cancelado(5); private int codigo; private PedidoStatus(int codigo) { this.codigo = codigo; } public int getCodigo() { return codigo; } public static PedidoStatus valueOf(int codigo) { for(PedidoStatus aux: PedidoStatus.values()) { if(aux.getCodigo()==codigo) { return aux; } } throw new IllegalArgumentException("Código de Status Inválido!"); } }
package com.example.snookertracker; import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Color; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class SetupPlayers extends AppCompatActivity { public static final String EXTRA_MESSAGE = "com.example.snookertracker.MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup_players); ConstraintLayout lay = findViewById(R.id.clay1); Globals g = (Globals)getApplication(); int data=g.getColid(); if(data==1) { lay.setBackgroundColor(Color.parseColor("#eec4d7")); lay.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#eec4d7"))); } else if(data==2) { lay.setBackgroundColor(Color.CYAN); lay.setBackgroundTintList(ColorStateList.valueOf(Color.CYAN)); } else if(data==3) { lay.setBackgroundColor(Color.LTGRAY); lay.setBackgroundTintList(ColorStateList.valueOf(Color.LTGRAY)); } // // TextView tv2 = findViewById(R.id.textView2); // tv2.setTextSize(data); // TextView tv3 = findViewById(R.id.textView3); // tv3.setTextSize(data); // TextView tv4 = findViewById(R.id.textView4); // tv4.setTextSize(data); // TextView tv5 = findViewById(R.id.textView5); // tv5.setTextSize(data); // TextView tv6 = findViewById(R.id.textView6); // tv6.setTextSize(data); // TextView tv7 = findViewById(R.id.textView8); // tv7.setTextSize(data); } public void updateNames(View view) { String name1 = "a"; String name2 = "b"; String name3 = "c"; String name4 = "d"; try { EditText n1 = findViewById(R.id.name_1); name1 = n1.getText().toString(); EditText n2 = findViewById(R.id.name_2); name2 = n2.getText().toString(); EditText n3 = findViewById(R.id.name_3); name3 = n3.getText().toString(); EditText n4 = findViewById(R.id.name_4); name4 = n4.getText().toString(); String message = name1 + "*" + name2 + "*" + name3 + "*" + name4; Intent intent = new Intent(this, scoreBoard.class); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); }catch (Exception e){ Context context = getApplicationContext(); CharSequence text = "Please enter names of the players!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } public void callsettings(View view) { Intent intent2 = new Intent(this, settingsActivity.class); startActivity(intent2); } }
package com.computerstudent.madpractical.Practical_16; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.computerstudent.madpractical.Practical_14.gridView; import com.computerstudent.madpractical.Practical_14.listView; import com.computerstudent.madpractical.R; public class selectQuestionPractical16 extends AppCompatActivity { Button btnTimePicker,btnDatePicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_question2); btnDatePicker=findViewById(R.id.btnDatePicker); btnTimePicker=findViewById(R.id.btnTimePicker); } public void onClick(View view) { if( btnDatePicker.getId()==view.getId()) { startActivity(new Intent(this, datePicker.class)); } else if( btnTimePicker.getId()==view.getId()) { startActivity(new Intent(this, timePiker.class)); } } }
// 9번 public class AddNum { public static void main(String[] args) { int rand = (int) (Math.random() * 100) % 100; System.out.println(rand); String str = Integer.toString(rand); int[] num = new int[str.length()]; for (int i = 0; i < num.length; i++) { num[i] = str.charAt(i) - '0'; } int result = num[0] + num[1]; System.out.println(result); } }
package test.nz.org.take.compiler.scenario13.generated; import nz.org.take.rt.*; /** * Interface generated by the take compiler. * @version Mon Feb 18 10:34:08 CET 2008 */ @SuppressWarnings("unchecked") public interface KB { /** * Method generated for query /hasCategory[in,out] * @param bean input parameter generated from slot 0 * @return an iterator for instances of HasCategory */ public ResultSet<HasCategory> hasCategory( final test.nz.org.take.compiler.scenario13.Bean bean); /** * Method generated for query ranking[in,in] * @param slot1 input parameter generated from slot 0 * @param slot2 input parameter generated from slot 1 * @return an iterator for instances of ranking */ public ResultSet<ranking> ranking_11( final test.nz.org.take.compiler.scenario13.Bean slot1, final long slot2); /** * Method that can be used to query annotations at runtime. * @param id the id of the rule (or other knowledge element) * @return a map of annotations (string-string mappings) * code generated using velocity template LocalAnnotationMethod.vm */ public java.util.Map<String, String> getAnnotations(String id); /** * Method that can be used to query global annotations at runtime. * Global annotations are attached to the knowledge base, not to * a particular element (rule,..). * @return a map of annotations (string-string mappings) * code generated using velocity template GlobalAnnotationMethod.vm */ public java.util.Map<String, String> getAnnotations(); }
package OOPS; public class Test1 { public static void main(String[] args) { Inher3 obj =new Inher3(); obj.m1(); } }
package com.yuan.graduate; import com.yuan.application.BaseActivity; import com.yuan.control.CheckControl; import com.yuan.dialog.CustomProgressDialog; import com.yuan.dialog.DialogUtil; import com.yuan.model.M员工信息表; import com.yuan.model.M请假申请; import com.yuan.unit.AsyncDataJobHandler; import com.yuan.unit.ToastHelper; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.List; /** * 请假界面 * * @author YUAN */ @SuppressLint("HandlerLeak") @SuppressWarnings("unused") public class LeaveActivity extends BaseActivity { private Context mContext = null; private TextView leavestateinfo = null, leave_type = null; private EditText leave_reason = null, time_start = null, time_end = null; private Button leave_submit = null, leave_start_bn, leave_end_bn, goleavetypelist; private CustomProgressDialog mProgressDialog = null; private CustomProgressDialog mCustomProgressDialog = null; private String reason, start, end; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case LEAVETYPEFROMSQL: List<?> list = (List<?>) msg.obj; DialogUtil.createLeaveTypeDialog(mContext, mHandler, list).show(); break; case LEAVETYPE: String type = (String) msg.obj; leave_type.setText(type); break; case ASKFORLEAVESUCCEED: succeedAskForLeave(); break; case ASKFORLEAVEFILDED: ToastHelper.getInstance().shortToast(mContext, "请假失败"); break; case ASKFORLEAVEENDTIME: time_end.setText((String) msg.obj); break; case ASKFORLEAVESTARTTIME: time_start.setText((String) msg.obj); break; default: break; } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; setContentView(R.layout.activity_askleave); initView(); } protected void succeedAskForLeave() { // TODO Auto-generated method stub ToastHelper.getInstance().shortToast(mContext, "请假成功,在查看审批界面查看是否被批准"); DialogUtil.createEnsureDialog(mContext, "信息提示", "是否转到发送短息页面,发送短信给你的BOSS,提示它尽快审批!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Uri uri = Uri.parse("smsto:"); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); String str = String.format(SENDMSG, M员工信息表.getInstance().get姓名(), reason, start, end); intent.putExtra("sms_body", str); startActivity(intent); dialog.dismiss(); finish(); } }).show(); } private void initView() { // TODO Auto-generated method stub leavestateinfo = (TextView) findViewById(R.id.leavestateinfo); leave_type = (TextView) findViewById(R.id.leave_type); leave_reason = (EditText) findViewById(R.id.leave_reason); time_start = (EditText) findViewById(R.id.time_start); time_end = (EditText) findViewById(R.id.time_end); leave_submit = (Button) findViewById(R.id.leave_submit); leave_start_bn = (Button) findViewById(R.id.leave_start_bn); leave_end_bn = (Button) findViewById(R.id.leave_end_bn); goleavetypelist = (Button) findViewById(R.id.goleavetypelist); leave_start_bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub DialogUtil.createTimeChoiceDialog(mContext, mHandler, "设置请假开始时间", ASKFORLEAVESTARTTIME).show(); } }); leave_end_bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub DialogUtil.createTimeChoiceDialog(mContext, mHandler, "设置请假结束时间", ASKFORLEAVEENDTIME).show(); } }); goleavetypelist.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub AsyncDataJobHandler.getInstance().getLeaveType(mHandler); } }); leave_type.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub AsyncDataJobHandler.getInstance().getLeaveType(mHandler); } }); leave_submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub reason = leave_reason.getText().toString().trim(); start = time_start.getText().toString().trim(); end = time_end.getText().toString().trim(); if (TextUtils.isEmpty(reason) || TextUtils.isEmpty(start) || TextUtils.isEmpty(end)) { ToastHelper.getInstance().shortToast(mContext, "输入为空"); return; } if (CheckControl.isLeaveRightTime(start) && CheckControl.isLeaveRightTime(end)) { M请假申请.getInstance().set开始(start + ":00.0"); M请假申请.getInstance().set结束(end + ":00.0"); M请假申请.getInstance().set请假理由(reason); AsyncDataJobHandler.getInstance().AskLeave(mHandler); } else { ToastHelper.getInstance().shortToast(mContext, "输入时间格式错误"); return; } } }); } }
import greenfoot.*; import java.awt.Color; import java.awt.Point; public class GrapplingHook extends VisibleActor { Platform platform; private double SPEED = 15; private double ANGLE = 60; private Color COLOR = Color.BLACK; private int direction; private double length = 0; private GreenfootImage img; private boolean isHooked = false; private Player parent; private Point target = null; private double initialVelocityX; private static GreenfootSound hitSound = new GreenfootSound("sounds/grapple.wav"); public GrapplingHook(Player thrower, int direction) { this.parent = thrower; this.direction = direction; this.target = new Point(parent.getX(), parent.getY()); this.initialVelocityX = parent.velocity.x; } public void act() { int width, height; if(!isHooked) { target.x += direction * SPEED * Math.cos(ANGLE * Math.PI / 180) + this.initialVelocityX; target.y -= SPEED * Math.sin(ANGLE * Math.PI / 180); this.platform = (Platform) parent.publicGetOneObjectAtOffset(target.x - parent.getX(), target.y - parent.getY(), Platform.class); if(platform != null) { isHooked = true; hitSound.play(); } } width = Math.abs(target.x - parent.getX()) + 1; height = Math.abs(target.y - parent.getY()) + 1; int disp_direction = (target.x < parent.getX() ? -1 : 1) * (target.y < parent.getY() ? 1 : -1); img = new GreenfootImage(width, height); img.setColor(COLOR); img.drawLine((disp_direction < 0 ? width - 1 : 0), height - 1, (disp_direction < 0 ? 0 : width - 1), 0); setLocation((parent.getX() + target.x) / 2, (parent.getY() + target.y) / 2); setImage(img); } public boolean getIsHooked() { return isHooked; } public Point getHookTarget() { return isHooked ? target : null; } }
package com.github.lnframeworkdemo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.Button; import com.github.fragmention.SupportFragment; /** * A simple {@link Fragment} subclass. */ public class ForgetLoginPwdFragment extends SupportFragment { public ForgetLoginPwdFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_forget_login_pwd, container, false); Button btn_backToRoot = getView(view, R.id.btn_backToRoot); btn_backToRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backToRoot(); } }); return view; } @Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { LoginActivity ac = (LoginActivity) activity; if (ac.hasAnimation()) { return super.onCreateAnimation(transit, enter, nextAnim); } else { Animation a = new Animation() { }; a.setDuration(0); return a; } } @Override public boolean interceptBackPress() { return true; } @Override protected void dealCustomBack() { super.dealCustomBack(); popBackStack(); } }
/** * Colgate University COSC 290 Labs * Version 0.2, 2019 * * @author Michael Hay */ public interface HashFamily<E> { /** * Hashes item using the ith hash function in the hash family * @param item the to be hashed * @param i which hash function to use * @return hash value */ int hash(E item, int i); }
package org.houstondragonacademy.archer.dao.entity; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.data.mongodb.core.mapping.Document; import java.time.LocalDate; import java.util.List; @Data @Builder @EqualsAndHashCode(callSuper = true) @Document(collection = "students") public class Student extends BaseEntity{ private String firstName; private String lastName; private String chineseName; private String gender; private LocalDate dateOfBirth; private String emergencyPhoneNum; private String doctorPhoneNum; private String gradeLevel; private String chineseLevel; private String notes; private List<String> enrolledCourse; }
package com.stucom.brickapp.model; import com.google.gson.annotations.SerializedName; public class LegoSet { @SerializedName("set_num") private String setNum; private String name; private int year; @SerializedName("theme_id") private int themeId; @SerializedName("num_parts") private int numParts; @SerializedName("set_img_url") private String setImgUrl; @SerializedName("set_url") private String setUrl; @SerializedName("last_modified_dt") private String lastModifiedDt; public LegoSet(String setNum, String name, int year, int themeId, int numParts, String setImgUrl, String setUrl, String lastModifiedDt) { this.setNum = setNum; this.name = name; this.year = year; this.themeId = themeId; this.numParts = numParts; this.setImgUrl = setImgUrl; this.setUrl = setUrl; this.lastModifiedDt = lastModifiedDt; } public String getSetNum() { return setNum; } public void setSetNum(String setNum) { this.setNum = setNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getThemeId() { return themeId; } public void setThemeId(int themeId) { this.themeId = themeId; } public int getNumParts() { return numParts; } public void setNumParts(int numParts) { this.numParts = numParts; } public String getSetImgUrl() { return setImgUrl; } public void setSetImgUrl(String setImgUrl) { this.setImgUrl = setImgUrl; } public String getSetUrl() { return setUrl; } public void setSetUrl(String setUrl) { this.setUrl = setUrl; } public String getLastModifiedDt() { return lastModifiedDt; } public void setLastModifiedDt(String lastModifiedDt) { this.lastModifiedDt = lastModifiedDt; } }
package com.infor.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "tbl_infortransaction") public class InforTransaction { public InforTransaction(){} @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int transactionid; @Column(name = "userid") private int userid; @Column(name = "parkingid") private String parkingid; @Column(name = "carid") private int carid; @Column(name = "timein") private String timein; @Column(name = "timeout") private String timeout; public int getTransactionid() { return transactionid; } public void setTransactionid(int transactionid) { this.transactionid = transactionid; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getParkingid() { return parkingid; } public void setParkingid(String parkingid) { this.parkingid = parkingid; } public int getCarid() { return carid; } public void setCarid(int carid) { this.carid = carid; } public String getTimein() { return timein; } public void setTimein(String timein) { this.timein = timein; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } }
package com.shoppingonline.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import com.shoppingonline.entity.Goods; import com.shoppingonline.entity.ShoppingCar; import com.shoppingonline.entity.UserTable; import com.shoppingonline.util.DBConnect; public class ShoppingCarDao { private static ArrayList<ShoppingCar> list; private static Connection con; private static PreparedStatement stmt; private static ResultSet rs; public static ArrayList<ShoppingCar> getMyShoppingCar(HttpServletRequest request) { String sql = "select * from shoppingCar where userID=?"; UserTable user = (UserTable) request.getSession().getAttribute("loginUser"); int userID = user.getUserID(); list = new ArrayList<ShoppingCar>(); try { con = DBConnect.getConnection(); stmt = con.prepareStatement(sql); stmt.setInt(1, userID); rs = stmt.executeQuery(); while(rs.next()){ ShoppingCar sc = new ShoppingCar(); sc.setGoodsID(rs.getInt("goodsID")); sc.setGoodsNum(rs.getInt("goodsNum")); sc.setUserID(rs.getInt("userid")); sc.setSumPrice(rs.getInt("sumprice")); list.add(sc); } } catch (Exception e) { e.printStackTrace(); } finally{ try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } public static int getTheGoodsNum(Goods g){ int goodsNum = 0; int goodsId = g.getGoodsID(); String sql = "select goodsnum from shoppingcar where goodsid=?"; try { con = DBConnect.getConnection(); stmt = con.prepareStatement(sql); stmt.setInt(1, goodsId); rs = stmt.executeQuery(); while(rs.next()){ goodsNum = goodsNum + rs.getInt("goodsNum"); } } catch (Exception e) { e.printStackTrace(); } finally{ try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return goodsNum; } public static int getSumPrice(ShoppingCar sc){ Goods g = new Goods(); int sumprice = 0; g.setGoodsID(sc.getGoodsID()); if(GoodsDao.isSpecial_offer(g)){ sumprice = sc.getGoodsNum()*GoodsDao.getspecial_price(g); }else{ sumprice = sc.getGoodsNum()*GoodsDao.getPrice(g); } return sumprice; } public static void addToShoppingCar(ShoppingCar sc){ String sql = "insert into shoppingcar(userid,goodsid,goodsnum,sumprice) values(?,?,?,?)"; try { con = DBConnect.getConnection(); stmt = con.prepareStatement(sql); stmt.setInt(1, sc.getUserID()); stmt.setInt(2, sc.getGoodsID()); stmt.setInt(3, 1); stmt.setInt(4, sc.getSumPrice()); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ try { stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void updateToShoppingCar(ShoppingCar sc){ String sql = "update shoppingcar set goodsnum=?,sumprice=? where goodsid=?"; Goods g = new Goods(); g.setGoodsID(sc.getGoodsID()); int goodsNum = GoodsDao.getGoodsNum(g); try { con = DBConnect.getConnection(); stmt = con.prepareStatement(sql); stmt.setInt(1, sc.getGoodsNum()); stmt.setInt(2, sc.getSumPrice()); stmt.setInt(3, sc.getGoodsID()); if(sc.getGoodsNum()<=goodsNum){ stmt.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); } finally{ try { stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void deleteAllShoppingCar() { String sql = "delete from shoppingcar"; try { con = DBConnect.getConnection(); stmt = con.prepareStatement(sql); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ try { stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void deleteShoppingCar(ShoppingCar sc) { String sql = "delete from shoppingcar where goodsid=?"; try { con = DBConnect.getConnection(); stmt = con.prepareStatement(sql); stmt.setInt(1, sc.getGoodsID()); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ try { stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.sync.diffsync.web; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.sync.Patch; import org.springframework.sync.json.JsonPatchPatchConverter; import java.io.IOException; import java.util.Collections; /** * {@link HttpMessageConverter} that converts "application/json-patch+json" payloads to/from {@link Patch} objects. * * @author Craig Walls */ public class JsonPatchHttpMessageConverter extends AbstractHttpMessageConverter<Patch> { private static final MediaType JSON_PATCH = new MediaType("application", "json-patch+json"); private static final ObjectMapper MAPPER = new ObjectMapper(); private final JsonPatchPatchConverter jsonPatchMaker; public JsonPatchHttpMessageConverter() { setSupportedMediaTypes(Collections.singletonList(JSON_PATCH)); this.jsonPatchMaker = new JsonPatchPatchConverter(); } @Override protected boolean supports(Class<?> clazz) { return Patch.class.isAssignableFrom(clazz); } @Override protected Patch readInternal(Class<? extends Patch> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return jsonPatchMaker.convert(MAPPER.readTree(inputMessage.getBody())); } @Override protected void writeInternal(Patch patch, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { outputMessage.getHeaders().setContentType(JSON_PATCH); MAPPER.writer().writeValue(outputMessage.getBody(), jsonPatchMaker.convert(patch)); } }
package org.rebioma.client.forms; import org.rebioma.client.ApplicationView; import org.rebioma.client.DataSwitch; import org.rebioma.client.Email; import org.rebioma.client.i18n.AppConstants; import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; public class ForgotPasswordForm extends Form { /** * The application constants. * */ private final static AppConstants constants = ApplicationView.getConstants(); /** * The email form input. * */ private final FormInput email = new EmailFormInput(constants.Email(), false); public ForgotPasswordForm(String name) { this(name, null); } public ForgotPasswordForm(String name, FormListener listener) { super(name, true, Layout.VERTICAL, listener); addInput(email); } @Override protected void onCancel() { History.newItem(""); } @Override protected void onSubmit() { Email mail = createEmail(); DataSwitch.get().resetUserPassword(email.getInputValue(), mail, new AsyncCallback() { public void onFailure(Throwable caught) { fireOnSubmitFailed(caught); } public void onSuccess(Object result) { fireOnSubmitSuccess(result); } }); } private Email createEmail() { Email email = new Email(); email.setSubject(constants.PasswordRecoverySubject()); email.setContent(constants.RecoveryNotificationMsg()); email.initCommonFields(); return email; } }
package com.snab.tachkit.globalOptions; import android.content.Context; import android.content.SharedPreferences; /** * Created by Таня on 16.02.2015. * Работа с сохраненными данными, которые не сохранены в базе данных (временные и переменные) */ public class SharedPreferencesCustom { private static String userId = "user_id", sessionKey = "session_key", searchStrUser = "search_str_user", searchStr = "search_str", database = "database", cityId = "city_id", cityName = "city_name", startPosition = "startPosition", tiresOrDisks = "tires_or_disks"; private static SharedPreferences init(Context context){ return context.getSharedPreferences("user_data", context.MODE_PRIVATE); } /** * id пользователя * @param context * @return */ public static int getUserId (Context context){ return init(context).getInt(userId, 0); } /** * сессия пользователя * @param context * @return */ public static String getSessionKey (Context context){ return init(context).getString(sessionKey, ""); } /** * строка отбора объявлений для пользователя * @param context * @return */ public static String getSearchStrUser (Context context){ return init(context).getString(searchStrUser, ""); } /** * строка поиска обычная * @param context * @return */ public static String getSearchStr (Context context){ return init(context).getString(searchStr, ""); } /** * возвращаем id города, где определился телефон * @param context * @return */ public static int getCityId (Context context){ return init(context).getInt(cityId, -1); } /** * возвращаем имя города, где определился телефон * @param context * @return */ public static String getCityName (Context context){ return init(context).getString(cityName, ""); } /** * возвращаем имя города, где определился телефон * @param context * @return */ public static int getStartPosition (Context context){ return init(context).getInt(startPosition, -1); } /** * запоминаем id пользователя * @param context * @param userId_ - сам id */ public static void setUserId (Context context, Integer userId_){ SharedPreferences.Editor ed = init(context).edit(); if(userId_ == null) { ed.remove(userId); }else{ ed.putInt(userId, userId_); } ed.commit(); } /** * запоминаем id пользователя * @param context * @param cityId_ - сам id */ public static void setCity (Context context, Integer cityId_, String cityName_){ SharedPreferences.Editor ed = init(context).edit(); if(cityId_ == null || cityName_ == null) { ed.remove(cityId); ed.remove(cityName); }else{ ed.putInt(cityId, cityId_); ed.putString(cityName, cityName_); } ed.commit(); } /** * запоминаем id пользователя * @param context * @param startPosition_ - сам id */ public static void setStartPosition (Context context, Integer startPosition_){ SharedPreferences.Editor ed = init(context).edit(); if(startPosition_ == null || startPosition_ == null) { ed.remove(startPosition); }else{ ed.putInt(startPosition, startPosition_); } ed.commit(); } /** * записываем сессию * @param context * @param sessionKey_ - сессия */ public static void setSessionKey (Context context, String sessionKey_){ SharedPreferences.Editor ed = init(context).edit(); if(sessionKey_ == null) { ed.remove(sessionKey); }else{ ed.putString(sessionKey, sessionKey_); } ed.commit(); } /** * записываем строку поиска для пользователя * @param context * @param searchStrUser_ */ public static void setSearchStrUser (Context context, String searchStrUser_){ SharedPreferences.Editor ed = init(context).edit(); if(searchStrUser_ == null) { ed.remove(searchStrUser); }else{ ed.putString(searchStrUser, searchStrUser_); } ed.commit(); } /** * записываем строку поиска для фильтра * @param context * @param searchStr_ */ public static void setSearchStr (Context context, String searchStr_){ System.out.println("SET!!!!!!!!!!!!! " + searchStr_); SharedPreferences.Editor ed = init(context).edit(); if(searchStr_ == null) { ed.remove(searchStr); }else{ ed.putString(searchStr, searchStr_); } ed.commit(); } /** * статус базы данных * @param context * @param database_ */ public static void setDatabase (Context context, Boolean database_){ SharedPreferences.Editor ed = init(context).edit(); if(database_ == null) { ed.remove(database); }else{ ed.putBoolean(database, database_); } ed.commit(); } /** * проверка наличия записи строки поиска для пользователя * @param context * @return */ public static Boolean containsSearchStrUser (Context context){ return init(context).contains(searchStrUser); } /** * проверка наличия записи строки поиска для пользователя * @param context * @return */ public static Boolean containsCityId (Context context){ return init(context).contains(cityId); } /** * проверка наличия строки поиска для фильтра * @param context * @return */ public static Boolean containsSearchStr (Context context){ return init(context).contains(searchStr); } /** * наличия статуса базы данных * @param context * @return */ public static Boolean containsDatabase (Context context){ return init(context).contains(database); } // Возвращает текущий раздел из шин-дисков (шины или диски) public static int getTiresOrDisks(Context context) { return init(context).getInt(tiresOrDisks, Global.idTires); } // Задает текущий раздел шин или дисков public static void setTiresOrDisks(Context context, int type) { SharedPreferences.Editor ed = init(context).edit(); ed.putInt(tiresOrDisks, type); ed.commit(); } }
package com.hiwes.cores.thread.thread1.Thread0214; /** * 判断线程是否是停止状态 * 使用this.interrupted(),测试当前线程是否已经中断。 * // 使用interrupt(),并未中断当前线程main。 * <p> * 使用this.isInterrupted(),测试线程是否被中断。 */ public class MyThread02 extends Thread { @Override public void run() { super.run(); for (int i = 0; i < 5000; i++) { System.out.println("i = " + (i + 1)); } } } class Run02 { public static void main(String[] args) { try { MyThread02 thread = new MyThread02(); thread.start(); Thread.sleep(2000); thread.interrupt(); System.out.println("是否停止1: " + thread.interrupted()); System.out.println("是否停止2: " + thread.interrupted()); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } } } class Run02_1 { public static void main(String[] args) { Thread.currentThread().interrupt(); System.out.println("是否停止1: " + Thread.interrupted()); System.out.println("是否停止2: " + Thread.interrupted()); System.out.println("end!"); } } /** * 输出结果: * <p> * 是否停止1: true * 是否停止2: false * end! * <p> * 原因:在官方帮助文档写的很清楚:interrupted()方法,测试当前线程是否被中断,中断的状态由该方法清楚。 * 即:两次调用该方法,第二次就会返回false。因为在第一次调用的时候已经清除了其中断状态,除非在第二次调用之前又被中断。 */ /** * 使用:isInterrupted()方法: * 并未清除线程的状态标志。 */ class Run02_2 { public static void main(String[] args) { try { MyThread03 thread = new MyThread03(); thread.start(); Thread.sleep(1000); thread.interrupt(); System.out.println("是否停止1: " + thread.isInterrupted()); System.out.println("是否停止2: " + thread.isInterrupted()); } catch (InterruptedException e) { System.out.println("main match"); e.printStackTrace(); } } } /** * 输出结果: * 是否停止1: false * 是否停止2: false */ /** * 总结: * this.interrupted()。测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能; * this.isInterrupted()。测试线程Thread对象是否已经是中断状态,但是不清除状态标志。 */
package com.zhao.leetcode; import java.util.HashMap; import java.util.Map; public class LFUCache { private class DLinkedNode{ Integer key; Integer value; Integer count; DLinkedNode prev; DLinkedNode next; public DLinkedNode(Integer key,Integer value,Integer count){ this.key=key; this.value =value; this.count = count; } } private Map<Integer,DLinkedNode> hashMap = new HashMap<Integer,DLinkedNode>(); private int size; private int capacity; private DLinkedNode head; private DLinkedNode tail; public LFUCache(int capacity) { this.capacity = capacity; this.size=0; this.head =new DLinkedNode(-1,-1,Integer.MAX_VALUE); this.tail =new DLinkedNode(-1,-1,0); this.head.prev =null; this.tail.next =null; this.head.next =tail; this.tail.prev =head; } private void removeNode(DLinkedNode node){ node.next.prev=node.prev; node.prev.next=node.next; } private void addByCount(DLinkedNode node){ int count = node.count; DLinkedNode p = this.head; DLinkedNode pre =null; while (p!=null){ if (count>=p.count){ break; } pre=p; p=p.next; } node.next =pre.next; pre.next.prev =node; pre.next =node; node.prev=pre; } public int get(int key){ if (this.size==0) return -1; DLinkedNode node = hashMap.get(key); if (node==null) return -1; node.count++; removeNode(node); addByCount(node); return node.value; } public void put(int key,int value){ if (this.capacity==0) return; DLinkedNode node = hashMap.get(key); DLinkedNode newNode = new DLinkedNode(key,value,0); if (node!=null){ newNode.count =node.count+1; node.count=0; removeNode(node); addByCount(newNode); hashMap.put(key,newNode); }else { if (this.capacity==size){ size--; tail.prev.count =0; hashMap.remove(tail.prev.key); removeNode(tail.prev); } newNode.count=1; addByCount(newNode); hashMap.put(key,newNode); size++; } } }
public class Calc{ private int r=0; public int add(int x, int y) { //add method return x+y; } public int sub(int x, int y){ return x-y; } public int mul(int x, int y){//multiplication method321312 return x*y; } public void iniR(int d){ r+=d; } public int getResult(){ return r; } }
package com.xwechat.api.mp; import java.util.List; /** * 用户画像 * Created by shangqingzhe on 17/10/19. */ public class UserPortrait { private String refDate; private VisitUvNew visitUvNew; private VisitUv visitUv; public String getRefDate() { return refDate; } public void setRefDate(String refDate) { this.refDate = refDate; } public VisitUvNew getVisitUvNew() { return visitUvNew; } public void setVisitUvNew(VisitUvNew visitUvNew) { this.visitUvNew = visitUvNew; } public VisitUv getVisitUv() { return visitUv; } public void setVisitUv(VisitUv visitUv) { this.visitUv = visitUv; } public static class VisitUvNew { private List<Property> province; private List<Property> city; private List<Property> genders; private List<Property> platforms; private List<Property> devices; private List<Property> ages; public List<Property> getProvince() { return province; } public void setProvince(List<Property> province) { this.province = province; } public List<Property> getCity() { return city; } public void setCity(List<Property> city) { this.city = city; } public List<Property> getGenders() { return genders; } public void setGenders(List<Property> genders) { this.genders = genders; } public List<Property> getPlatforms() { return platforms; } public void setPlatforms(List<Property> platforms) { this.platforms = platforms; } public List<Property> getDevices() { return devices; } public void setDevices(List<Property> devices) { this.devices = devices; } public List<Property> getAges() { return ages; } public void setAges(List<Property> ages) { this.ages = ages; } } public static class VisitUv { private List<Property> province; private List<Property> city; private List<Property> genders; private List<Property> platforms; private List<Property> devices; private List<Property> ages; public List<Property> getProvince() { return province; } public void setProvince(List<Property> province) { this.province = province; } public List<Property> getCity() { return city; } public void setCity(List<Property> city) { this.city = city; } public List<Property> getGenders() { return genders; } public void setGenders(List<Property> genders) { this.genders = genders; } public List<Property> getPlatforms() { return platforms; } public void setPlatforms(List<Property> platforms) { this.platforms = platforms; } public List<Property> getDevices() { return devices; } public void setDevices(List<Property> devices) { this.devices = devices; } public List<Property> getAges() { return ages; } public void setAges(List<Property> ages) { this.ages = ages; } } public static class Property { private Integer id; private String name; private String value; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
package com.yahoo.random; public class RepeatedCharInString { /** * @param args */ public static void main(String[] args) { // String str = "repeatedcharinstring"; String str = "norepat"; int checked =0; for(int i =0;i<str.length() -1 ; i++){ int val = str.charAt(i) - 'a'; //val has to be unique if char unique in string if ( (checked & (1<<val)) > 0){ // has to be zero if val was unique since that bit position would be empty System.out.println("repeated char: "+str.charAt(i)+" at pos:"+i); } checked |= (1<< val); //occupy the bit position of char, so character b which is 98 or val =1 would be 1<<1 or 10 or second bit from right } } /*replace blank with %20 */ public static void ReplaceFun(char[] str, int length) { int spaceCount = 0, newLength, i = 0; for (i = 0; i < length; i++) { if (str[i] == ' ') { spaceCount++; } } newLength = length + spaceCount * 2; str[newLength] = '\0'; for (i = length - 1; i >= 0; i--) { if (str[i] == ' ') { str[newLength - 1] = '0'; str[newLength - 2] = '2'; str[newLength - 3] = '%'; newLength = newLength - 3; } else { str[newLength - 1] = str[i]; newLength = newLength - 1; } } } }
package com.yunhe.activitymanagement; import com.yunhe.core.redis.RedisService; import com.yunhe.systemsetup.entity.Employ; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; /** * @author 刘栋 * @date 2019/1/9 16:52 */ @RunWith(SpringRunner.class) @SpringBootTest public class activitymanagement { @Resource RedisTemplate redisTemplate; @Resource RedisService redisService; @Test public void contextLoads() throws Exception { Employ employ = new Employ(); employ.setEmDelInvoice("123"); employ.setEmEmail("1231"); //存储一条数据 redisService.set("employ", employ); System.out.println( "************"+redisService.get("employ").toString()); } }
package ch.fhnw.edu.cpib.cst.interfaces; import ch.fhnw.edu.cpib.ast.interfaces.IExpr; public interface ITerm3 extends IProduction { public IExpr toAbsSyntax(); }
package com.tj.Account; public class BoxOrRectMain { public static void main(String[] args) { BoxOrRect box = new BoxOrRect(5, 6, 10); BoxOrRect rect = new BoxOrRect(10, 5); box.callNsetVolume(); // calculateVolume System.out.println("박스 부피: " + box.getVolume()); rect.callNsetVolume(); System.out.println("rect넓이: " + rect.getVolume()); }// main }
package br.com.treinarminas.academico.operators; public class OperadotorArithmetic { public static void main(String[] args) { int a = 10; int b = 20; int soma = a + b; System.out.println("A Soma de " + a + " + " + b + " = " + soma); int c = 10; int d = 20; int sub = a - b; System.out.println("\nA Subtração de " + c + " - " + d + " = " + sub); int e = 10; int f = 20; int mult = a * b; System.out.println("\nA Multiplicação de " + e + " - " + f + " = " + mult); int g = 10; int h = 3; int div = g / h; System.out.println("\nA Divisão de " + g + " / " + h + " = " + div); int i = 10; int j = 3; int modulo = g % h; System.out.println("\nA Divisão de " + i + " / " + j + " = " + modulo); } }
package controller; import dao.LocalizacaoDao; import dao.LocalizacaoDaoImp; import model.Localizacao; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import java.util.List; @ManagedBean @SessionScoped public class LocalizacaoController { private Localizacao localizacao; private DataModel listaLocalizacoes; public DataModel getListarLocalizacoes() { List<Localizacao> lista = new LocalizacaoDaoImp().list(); listaLocalizacoes = new ListDataModel(lista); return listaLocalizacoes; } public Localizacao getLocalizacao() { return this.localizacao; } public void prepararAdicionarLocalizacao() { localizacao = new Localizacao(); } public void prepararAlterarLocalizacao() { localizacao = (Localizacao) (listaLocalizacoes.getRowData()); } public String excluirLocalizacao() { Localizacao cuidadorTemp = (Localizacao) (listaLocalizacoes.getRowData()); LocalizacaoDao dao = new LocalizacaoDaoImp(); dao.remove(cuidadorTemp); return "index"; } public void adicionarLocalizacao() { LocalizacaoDao dao = new LocalizacaoDaoImp(); dao.save(localizacao); } public void alterarLocalizacao() { LocalizacaoDao dao = new LocalizacaoDaoImp(); dao.update(localizacao); } }
/******************************************************************************* * =============LICENSE_START========================================================= * * ================================================================================= * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 org.onap.ccsdk.dashboard.rest; import java.net.URL; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.client.RestTemplate; /** * Base class for all the Rest client implementations * * */ public class RestClientBase { protected RestTemplate restTemplate = null; /** * @param restTemplate the restTemplate to set */ public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } protected void createRestTemplate(URL url, String user, String pass, String urlScheme) { RestTemplate restTempl = null; final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort(), urlScheme); // Build a client with a credentials provider CloseableHttpClient httpClient = null; if (user != null && pass != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); } else { httpClient = HttpClientBuilder.create().build(); } // Create request factory HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(httpHost); requestFactory.setHttpClient(httpClient); // Put the factory in the template restTempl = new RestTemplate(); restTempl.setRequestFactory(requestFactory); this.restTemplate = restTempl; } /** * Builds URL ensuring appropriate separators. The base comes from properties * file so could have many problems. * * @param base * @param suffix * @param queryParams key-value pairs; i.e. must have an even number of entries. * Ignored if null. * @return */ protected String buildUrl(final String[] path, final String[] queryParams) { StringBuilder sb = new StringBuilder(path[0]); for (int p = 1; p < path.length; ++p) { if (!path[p - 1].endsWith("/") && !path[p].startsWith("/")) sb.append('/'); sb.append(path[p]); } if (queryParams != null && queryParams.length > 0) { sb.append('?'); int i = 0; while (i < queryParams.length) { if (i > 0) sb.append('&'); sb.append(queryParams[i]); sb.append('='); sb.append(queryParams[i + 1]); i += 2; } } return sb.toString(); } /** * Create Http Entity for the tenant header * * @param tenant * @return */ protected HttpEntity<String> getTenantHeader(String tenant) { HttpHeaders headers = new HttpHeaders(); headers.set("Tenant", tenant); return new HttpEntity<String>("parameters", headers); } /** * Create Http Entity for the consul token header * * @param token string * @return */ protected HttpEntity<String> getConsulTokenHeader(String token) { HttpHeaders headers = new HttpHeaders(); headers.set("X-Consul-Token", token); return new HttpEntity<String>("parameters", headers); } }
/******************************************************************************* * Copyright (C) 2010 Daniel Murphy and Peter Brewer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Daniel Murphy * Peter Brewer ******************************************************************************/ package org.tellervo.desktop.bulkdataentry.command; import org.tellervo.desktop.bulkdataentry.control.DeleteRowEvent; import com.dmurph.mvc.IllegalThreadException; import com.dmurph.mvc.IncorrectThreadException; import com.dmurph.mvc.MVC; import com.dmurph.mvc.MVCEvent; import com.dmurph.mvc.control.ICommand; import com.dmurph.mvc.model.MVCArrayList; public class DeleteRowCommand implements ICommand { @Override public void execute(MVCEvent argEvent) { try { MVC.splitOff(); // so other mvc events can execute } catch (IllegalThreadException e) { // this means that the thread that called splitOff() was not an MVC thread, and the next event's won't be blocked anyways. e.printStackTrace(); } catch (IncorrectThreadException e) { // this means that this MVC thread is not the main thread, it was already splitOff() previously e.printStackTrace(); } DeleteRowEvent event = (DeleteRowEvent) argEvent; MVCArrayList rowsToDelete = new MVCArrayList(); for(int i : event.getValue()) { rowsToDelete.add(event.model.getRows().get(i)); } event.model.getRows().removeAll(rowsToDelete); } }
package network.stuff; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import exception.stuff.EasyIn; import exception.stuff.MessageListener; public class NetworkingStuff { public static void main(String[] args) throws Exception { Socket socket = new Socket("192.168.0.109", 5250); MessageListener ml = new MessageListener(socket); DataOutputStream os = new DataOutputStream(socket.getOutputStream()); Scanner fromKBD = new Scanner(System.in); while (true) { System.out.print("Message: "); String str = fromKBD.nextLine(); os.writeUTF(str); os.flush(); } } }
package www.chaayos.com.chaimonkbluetoothapp.network; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Header; import retrofit2.http.POST; import www.chaayos.com.chaimonkbluetoothapp.data.model.OrderDetail; /** * Created by shikhar on 09-08-2016. */ public interface AnalyticsDataService { @POST("kettle-analytics/rest/v1/chai-monk/sync-orders") Call<Integer> syncOrders(@Header("auth") String jwtToken, @Body List<OrderDetail> orderDetails); }
package tcpdemo; import java.io.*; import java.net.*; import java.util.*; /** * * @author rasmu */ public class EchoServer { static String ip = "localhost"; static int port = 8080; public static void main(String[] args) throws IOException { if (args.length == 2) { ip = args[0]; port = Integer.parseInt(args[1]); } ServerSocket ss = new ServerSocket(); ss.bind(new InetSocketAddress(ip, port)); System.out.println("Server started, listening on " + port + ", bound to " + ip); Socket socket = ss.accept(); handleClient(socket); System.out.println("New client connected"); } public static void handleClient(Socket s) { try { Scanner scan = new Scanner(s.getInputStream()); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); String msg = ""; while (!msg.equals("STOP")) { msg = scan.nextLine(); pw.println(msg.toUpperCase()); } scan.close(); pw.close(); s.close(); } catch (IOException x) { System.out.println("blabla"); } } }
package com.mahirkole.walkure.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; @EqualsAndHashCode(callSuper = true) @Data @Entity @DiscriminatorValue(value = "movie") public class MovieCast extends CastItem { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "item_id") private Movie movie; }
package cn.cnmua.car.dao; import cn.cnmua.car.domian.PartsImg; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * @Author hjf * @Date 2020/1/3 **/ public interface PartsImgMapper extends BaseMapper<PartsImg> { }
class Solution { public int trap(int[] height) { if (height.length < 3) return 0; int startEnd = 0; int endEnd = 0; int maxValue = 0; int ret = 0; int value = height[0]; for (int i = 0 ; i <height.length;i++) { if (maxValue < height[i]) { maxValue = height[i]; } } for (int i = height.length - 1; i >=0; i--) { if (maxValue == height[i]) { startEnd = i; endEnd = i; break; } } for (int i = 1; i < startEnd;i++) { if (value < height[i]) { value = height[i]; } else { ret += value - height[i]; } } if (startEnd < height.length - 2) { value = height[height.length - 1]; for(int i = height.length - 2; i >= endEnd; i--) { if (value < height[i]) { value = height[i]; } else { ret += value - height[i]; } } } return ret; } }
package edu.htu.ap.lesson10; public class Test { public static void main(String[] args) { Major major=new Major(10,"IT"); Course course1=new Course(101,"Programming",1); Course course2=new Course(102,"Advanced Programming",2); Course course3=new Course(101,"Data Structure",3); StudentCourse stdCourse1=new StudentCourse(course1,90,2019,1); StudentCourse stdCourse2=new StudentCourse(course2,80,2019,2); StudentCourse stdCourse3=new StudentCourse(course3,50,2019,3); Student student=new Student(103,"Ata"); student.setMajor(major); student.addStudentCourses(stdCourse1,stdCourse2,stdCourse3); System.out.println(student.getGpa()); } }
package pl.java.scalatech.properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * @author przodownik * Module name : springKata * Creating time : 28 maj 2014 */ @Configuration @PropertySource("classpath:my.properties") public class PropConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
package jp.co.aforce.servlets; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jp.co.aforce.beans.SignUpBean; import jp.co.aforce.models.SignUpModel; public class SignUpServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // GETリクエストはあり得ないので、無条件でログイン画面に飛ばす RequestDispatcher rDispatcher = request.getRequestDispatcher("/views/signup.jsp"); rDispatcher.forward(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // 文字のエンコードを UTF-8 とする。これがないと文字化け。 request.setCharacterEncoding("UTF-8"); // ユーザによって入力された情報を取り出す SignUpBean signUpBean = new SignUpBean(); String name = request.getParameter("name"); String ageString = request.getParameter("age"); String birthyearString= request.getParameter("birth_year"); String birthmonthString = request.getParameter("birth_month"); String birthdayString = request.getParameter("birth_day"); try { //Stringをintに変換 int birthyear = Integer.parseInt(birthyearString); int birthmonth = Integer.parseInt(birthmonthString); int birthday = Integer.parseInt(birthdayString); if (name.length() <= 0) { // 書き漏れ、間違いのあるときの処理 signUpBean.setEmsg("入力されていない項目があります。"); request.setAttribute("signUpBean", signUpBean); // 書き漏れのないときの処理 } else { // モデルをインスタンス化する SignUpModel signUpModel = new SignUpModel(); //会員情報の登録 if (signUpModel.setUserDate(name,ageString,birthyear,birthmonth,birthday)) { signUpBean.setSuccess("登録に成功しました。"); request.setAttribute("signUpBean", signUpBean); }else { signUpBean.setEmsg("登録に失敗しました。"); request.setAttribute("signUpBean", signUpBean); } } }catch (Exception e) { // 書き漏れ、間違いのあるときの処理 signUpBean.setEmsg("入力されていない項目があります。"); request.setAttribute("signUpBean", signUpBean); }finally { // forwaed_jsp に設定されているJSPへディスパッチ RequestDispatcher rDispatcher = request.getRequestDispatcher("/views/signup.jsp"); rDispatcher.forward(request, response); } } }
/* * Sonar, open source software quality management tool. * Copyright (C) 2009 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.taglist; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.doubleThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.batch.DecoratorContext; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.Java; import org.sonar.api.resources.JavaFile; import org.sonar.api.resources.Language; import org.sonar.api.resources.Project; import org.sonar.api.resources.Resource; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleFinder; import org.sonar.api.rules.RulePriority; import org.sonar.api.rules.RuleQuery; import org.sonar.api.rules.Violation; import org.sonar.api.test.IsMeasure; public class ViolationsDecoratorTest { private ViolationsDecorator decorator; private RulesProfile rulesProfile = RulesProfile.create(); private Rule rule1, rule2, rule3; private RuleFinder ruleFinder; private DecoratorContext context; private JavaFile javaFile; @Before public void setUp() { rulesProfile = RulesProfile.create(); rule1 = createCheckstyleRule().setKey("key1"); rule2 = createCheckstyleRule().setKey("key2"); rule3 = createSquidRule(); Rule inactiveRule = createCheckstyleRule().setKey("key3"); rulesProfile.activateRule(rule1, RulePriority.BLOCKER).setParameter("format", "FIXME"); rulesProfile.activateRule(rule2, RulePriority.MAJOR).setParameter("format", "TODO"); rulesProfile.activateRule(rule3, RulePriority.INFO); ruleFinder = mock(RuleFinder.class); when(ruleFinder.findAll(argThat(any(RuleQuery.class)))).thenReturn(Arrays.asList(rule1, rule2, inactiveRule, rule3)); context = mock(DecoratorContext.class); javaFile = new JavaFile("org.example", "HelloWorld"); decorator = new ViolationsDecorator(rulesProfile, ruleFinder); } @Test public void dependedUpon() { assertThat(decorator.dependedUpon().size(), is(5)); } @Test public void shouldExecuteOnlyOnJavaProject() { Project project = mock(Project.class); Language anotherLanguage = mock(Language.class); when(project.getLanguage()).thenReturn(Java.INSTANCE).thenReturn(anotherLanguage); assertThat(decorator.shouldExecuteOnProject(project), is(true)); assertThat(decorator.shouldExecuteOnProject(project), is(false)); } @Test public void dontDecoratePackage() { Resource resource = mock(Resource.class); when(resource.getQualifier()).thenReturn(Resource.QUALIFIER_PACKAGE); ViolationsDecorator spy = spy(decorator); spy.decorate(resource, context); verify(spy, never()).saveFileMeasures(eq(context), argThat(any(Collection.class))); } @Test public void shouldSaveMetrics() { Violation mandatory = Violation.create(rule1, null); Violation optional = Violation.create(rule2, null); Violation info = Violation.create(rule3, null); when(context.getViolations()).thenReturn(Arrays.asList(mandatory, optional, info)); decorator.decorate(javaFile, context); verify(context, atLeastOnce()).getViolations(); verify(context).saveMeasure(eq(TaglistMetrics.TAGS), doubleThat(equalTo(3.0))); verify(context).saveMeasure(eq(TaglistMetrics.MANDATORY_TAGS), doubleThat(equalTo(1.0))); verify(context).saveMeasure(eq(TaglistMetrics.OPTIONAL_TAGS), doubleThat(equalTo(2.0))); verify(context).saveMeasure(eq(TaglistMetrics.NOSONAR_TAGS), doubleThat(equalTo(1.0))); verify(context).saveMeasure(argThat(new IsMeasure(TaglistMetrics.TAGS_DISTRIBUTION, "FIXME=1;NOSONAR=1;TODO=1"))); verifyNoMoreInteractions(context); } @Test public void shouldntSaveMetricsIfNoTags() { when(context.getViolations()).thenReturn(Collections.<Violation> emptyList()); decorator.decorate(javaFile, context); verify(context, atLeastOnce()).getViolations(); verifyNoMoreInteractions(context); } @Test public void ruleRriorities() { assertThat(ViolationsDecorator.isMandatory(RulePriority.BLOCKER), is(true)); assertThat(ViolationsDecorator.isMandatory(RulePriority.CRITICAL), is(true)); assertThat(ViolationsDecorator.isMandatory(RulePriority.MAJOR), is(false)); assertThat(ViolationsDecorator.isMandatory(RulePriority.MINOR), is(false)); assertThat(ViolationsDecorator.isMandatory(RulePriority.INFO), is(false)); } private Rule createSquidRule() { Rule rule = Rule.create(); rule.setRepositoryKey(CoreProperties.SQUID_PLUGIN); return rule; } private Rule createCheckstyleRule() { Rule rule = Rule.create(); rule.setRepositoryKey(CoreProperties.CHECKSTYLE_PLUGIN); rule.createParameter("format").setDefaultValue("TODO:"); return rule; } }
package database.jdbc.main; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.sql.Types; import database.jdbc.util.DBHandler; public class CallableStatementExample { /** * @param args */ public static void main(String[] args) { CallableStatement cstmt = null; CallableStatement cstmt2 = null; try { // 获得数据库连接 Connection conn = DBHandler.getConnection("dbtest", "yuu"); // 测试不带参数的存储过程 String sql = "{call insert_record_into_student(?, ?, ?, ?)}"; if(conn == null) { System.out.println("hello world!"); return; } cstmt = conn.prepareCall(sql); cstmt.setInt(1, 8); cstmt.setString(2, "tubaozi"); cstmt.setInt(3, 34); cstmt.setString(4, "M"); Boolean flag = cstmt.execute(); System.out.println(!flag ? "OK" : "error"); // 测试带参数的存储过程 String sql2 = "{call count_studunt_samename(?, ?)}"; cstmt2 = conn.prepareCall(sql2); cstmt2.setString(1, "tubaozi"); cstmt2.registerOutParameter(2, Types.INTEGER); //注册输出参数 cstmt2.execute(); int totalCount = cstmt2.getInt(2); //获取输出参数 System.out.println("总数:" + totalCount); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { cstmt.close(); cstmt2.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { DBHandler.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.hackerrank.github.model; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import java.sql.Timestamp; @Data @Entity @NoArgsConstructor public class Event { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(unique = true, nullable = false) private Long id; private String type; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "actor_id", referencedColumnName = "id") private Actor actor; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "repo_id", referencedColumnName = "id") private Repo repo; @CreationTimestamp @Column(name = "created_at") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") private Timestamp createdAt; }
package com.ejsfbu.app_main.DialogFragments; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Point; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.bumptech.glide.request.RequestOptions; import com.ejsfbu.app_main.Activities.AddGoalActivity; import com.ejsfbu.app_main.BitmapScaler; import com.ejsfbu.app_main.Models.User; import com.ejsfbu.app_main.R; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseUser; import com.parse.SaveCallback; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import static android.app.Activity.RESULT_OK; import static com.ejsfbu.app_main.Activities.AddGoalActivity.rotateBitmapOrientation; public class EditProfileImageDialogFragment extends DialogFragment { private final static int PICK_PHOTO_CODE = 1046; public final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1034; private File photoFile; public String photoFileName = "photo.jpg"; private Context context; private User user; private Button bEditProfilePicConfirm; private Button bEditProfilePicCancel; private ImageView ivEditProfilePicProfilePic; private ImageButton ibEditProfilePicPhotos; private ImageButton ibEditProfilePicCamera; public EditProfileImageDialogFragment() { } public static EditProfileImageDialogFragment newInstance(String title) { EditProfileImageDialogFragment frag = new EditProfileImageDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); frag.setArguments(args); return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { context = getContext(); return inflater.inflate(R.layout.fragment_edit_profile_pic, container); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); user = (User) ParseUser.getCurrentUser(); ivEditProfilePicProfilePic = view.findViewById(R.id.ivEditProfilePicProfilePic); ibEditProfilePicPhotos = view.findViewById(R.id.ibEditProfilePicPhotos); ibEditProfilePicCamera = view.findViewById(R.id.ibEditProfilePicCamera); bEditProfilePicConfirm = view.findViewById(R.id.bEditProfilePicConfirm); bEditProfilePicCancel = view.findViewById(R.id.bEditProfilePicCancel); fillData(); String title = getArguments().getString("title", "Enter Name"); getDialog().setTitle(title); getDialog().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); setOnClick(); } public interface EditProfileImageDialogListener { void onFinishEditDialog(); } public void sendBackResult() { ArrayList<Fragment> fragments = (ArrayList<Fragment>) getFragmentManager().getFragments(); String fragmentTag; int fragmentId; if (user.getIsParent()) { fragmentTag = fragments.get(1).getTag(); fragmentId = fragments.get(1).getId(); } else { fragmentTag = fragments.get(0).getTag(); fragmentId = fragments.get(0).getId(); } EditProfileImageDialogListener listener; if (fragmentTag != null) { listener = (EditProfileImageDialogListener) getFragmentManager() .findFragmentByTag(fragmentTag).getContext(); } else { listener = (EditProfileImageDialogListener) getFragmentManager() .findFragmentById(fragmentId); } listener.onFinishEditDialog(); dismiss(); } public void onResume() { Window window = getDialog().getWindow(); Point size = new Point(); Display display = window.getWindowManager().getDefaultDisplay(); display.getSize(size); window.setLayout((int) (size.x * 0.85), WindowManager.LayoutParams.WRAP_CONTENT); window.setGravity(Gravity.CENTER); super.onResume(); } private void fillData() { ParseFile image = user.getParseFile("profileImage"); if (image != null) { String imageUrl = image.getUrl(); imageUrl = imageUrl.substring(4); imageUrl = "https" + imageUrl; RequestOptions options = new RequestOptions(); options.placeholder(R.drawable.icon_user) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .error(R.drawable.icon_user) .transform(new CenterCrop()) .transform(new CircleCrop()); Glide.with(context) .load(imageUrl) .apply(options) // Extra: round image corners .into(ivEditProfilePicProfilePic); } } private void setOnClick() { bEditProfilePicCancel.setOnClickListener(view -> { dismiss(); }); bEditProfilePicConfirm.setOnClickListener(view -> { ParseFile parseFile; if (photoFile == null || ivEditProfilePicProfilePic.getDrawable() == null) { parseFile = null; dismiss(); return; } else { parseFile = new ParseFile(photoFile); } user.put("profileImage", parseFile); user.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { Toast.makeText(context, "Profile Image changed successfully.", Toast.LENGTH_SHORT).show(); sendBackResult(); } else { e.printStackTrace(); } } }); }); ibEditProfilePicPhotos.setOnClickListener(view -> { requestPerms(); Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (intent.resolveActivity(context.getPackageManager()) != null) { startActivityForResult(intent, PICK_PHOTO_CODE); } }); ibEditProfilePicCamera.setOnClickListener(view -> { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoFile = AddGoalActivity.getPhotoFileUri(photoFileName, context); Uri fileProvider = FileProvider.getUriForFile(context, "com.codepath.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider); if (intent.resolveActivity(context.getPackageManager()) != null) { startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_PHOTO_CODE) { if (resultCode == RESULT_OK && data != null) { Uri photoUri = data.getData(); photoFile = new File(AddGoalActivity.getRealPathFromURI(photoUri, context)); Bitmap selectedImage = null; try { selectedImage = MediaStore.Images.Media .getBitmap(context.getContentResolver(), photoUri); Bitmap resizedBitmap = BitmapScaler .scaleToFill(selectedImage, 200, 200); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); File resizedFile = AddGoalActivity .getPhotoFileUri(photoFileName + "_resized", context); resizedFile.createNewFile(); FileOutputStream fos = new FileOutputStream(resizedFile); fos.write(bytes.toByteArray()); fos.close(); photoFile = resizedFile; } catch (IOException e) { e.printStackTrace(); } ivEditProfilePicProfilePic.setImageBitmap(selectedImage); } } if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { Uri takenPhotoUri = Uri.fromFile(AddGoalActivity .getPhotoFileUri(photoFileName, context)); Bitmap rotatedBitmap = rotateBitmapOrientation(takenPhotoUri.getPath()); int width = rotatedBitmap.getWidth(); int height = rotatedBitmap.getHeight(); Bitmap resizedBitmap; if (width <= height) { resizedBitmap = BitmapScaler.scaleToFitWidth(rotatedBitmap, 200); } else { resizedBitmap = BitmapScaler.scaleToFitHeight(rotatedBitmap, 200); } Bitmap cropImg = Bitmap.createBitmap(resizedBitmap, 0, 0, 200, 200); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); cropImg.compress(Bitmap.CompressFormat.JPEG, 40, bytes); File resizedFile = AddGoalActivity .getPhotoFileUri(photoFileName + "_resized", context); try { resizedFile.createNewFile(); FileOutputStream fos = new FileOutputStream(resizedFile); fos.write(bytes.toByteArray()); fos.close(); photoFile = resizedFile; } catch (IOException e) { e.printStackTrace(); } //ivGoalImage.setVisibility(View.VISIBLE); ivEditProfilePicProfilePic.setImageBitmap(cropImg); Log.d("ProfileImage", photoFile.getAbsolutePath()); } else { // Result was a failure Toast.makeText(context, "Picture wasn't taken!", Toast.LENGTH_SHORT).show(); } } } public void requestPerms() { if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0); } else { } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 0) { //testPost(); } } }
package session3_assignment1; public class Variables { int a; //Instance variable int b; //Instance variable static int c; //Class variable static int d; //Class variable /* * Instance variables are the variables which are declared inside the class and outside the Main method. * Instance methods are accessed directly inside the instance methods. * In order to access Instance variables in static methods, we need to make use of objects. * The scope the instance variable is inside the class, methods, constructors, blocks. * * Class variables are the variables which are declared inside the class and outside of the main method with 'Static' keyword. * In order to access 'Class or static variables', we need to make use of the Class-name. * The scope of the static variables is inside the class. * 3-ways to access class variables. * a) Using class-name. * b) If the vraibles are in the same package, we can access directly. * c) Using object. * But, using 1st approach is the best way i.e, by using class-name. */ void instanceMethod(){ //Instance method a = 50; //Instance variable b = 60; //Instance variable Variables.c = 70; //we can use directly also i.e., c = 70 Variables.d = 80; //Printing the variables System.out.println("The value of Instance Variable 'a' = " +a); System.out.println("The value of Instance Variable 'b' = " +b); System.out.println("The value of Class Variable 'c' = " +Variables.c); System.out.println("The value of Class Variable 'd' = " +Variables.d); } //main method starts public static void main(String[] args) { Variables instance = new Variables(); //Object Creation instance.a = 10; //Instance Variable declaration instance.b = 20; //Instance Variable declaration Variables.c = 30; //Class variable declaration Variables.d = 40; //Class variable declaration //Printing the variables System.out.println("The value of Instance Variable 'a' = " +instance.a); System.out.println("The value of Instance Variable 'b' = " +instance.b); System.out.println("The value of Class Variable 'c' = " +Variables.c); System.out.println("The value of Class Variable 'd' = " +Variables.d); instance.instanceMethod(); //Calling instance method } }
package com.farm.tables; import org.json.JSONObject; import com.farm.upload.ImageUpload; import android.os.Environment; /* * Represents events table in database */ public class Events { public int eventId; public String eventOccuredDate; public String eventOccuredTime; public String imagePath; public int monitorPointId; public Events(int eventId, String eventOccuredDate, String eventOccuredTime, String imagePath, int monitorPointId){ this.eventId = eventId; this.eventOccuredDate = eventOccuredDate; this.eventOccuredTime = eventOccuredTime; this.imagePath = imagePath; this.monitorPointId = monitorPointId; } /* * Generates Json string corresponding to events data */ public JSONObject getEventsJson(){ JSONObject obj = null; try { obj = new JSONObject(); obj.put("eventid", ""+eventId); obj.put("eventoccureddate", eventOccuredDate); obj.put("eventoccuredtime", eventOccuredTime); obj.put("imagepath", imagePath); obj.put("monitorpointid", ""+monitorPointId); if(!imagePath.equals("")) { String dir = Environment.getExternalStorageDirectory().getPath() + "/"; obj.put("eventimage", ImageUpload.convertImage(dir + imagePath)); } } catch (Exception e) { e.printStackTrace(); } return obj; } }
package de.madjosz.adventofcode.y2020; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; import java.util.stream.Stream; public class Day20 { private final List<String> lines; public Day20(List<String> input) { this.lines = input; } public long a1() { Map<Integer, List<List<Integer>>> tiles = parseTileBorders(); return findCorners(tiles).mapToLong(i -> i).reduce(1L, (a, b) -> a * b); } private static IntStream findCorners(Map<Integer, List<List<Integer>>> tiles) { return tiles.entrySet().stream().filter(tile -> { List<Integer> sides = tile.getValue().get(0); return tiles.entrySet() .stream() .filter(e -> !e.getKey().equals(tile.getKey())) .filter(e -> e.getValue().stream().flatMap(Collection::stream).anyMatch(sides::contains)) .count() == 2; }).mapToInt(Entry::getKey); } private Map<Integer, List<List<Integer>>> parseTileBorders() { Map<Integer, List<List<Integer>>> tiles = new LinkedHashMap<>(); for (int i = 0; i < lines.size(); i += 12) { int tileId = Integer.parseInt(lines.get(i).substring(5, 9)); int[] top = parseLine(i + 1); int[] bottom = parseLine(i + 10); int[] sides = parseCols(i + 1); tiles.put(tileId, List.of(List.of(top[0], sides[0], bottom[1], sides[3]), List.of(top[1], sides[2], bottom[0], sides[1]))); } return tiles; } private int[] parseLine(int idx) { String line = lines.get(idx).replace('#', '1').replace('.', '0'); return new int[] { Integer.parseInt(line, 2), Integer.parseInt(new StringBuilder(line).reverse().toString(), 2) }; } private int[] parseCols(int idx) { StringBuilder c1 = new StringBuilder(); StringBuilder c2 = new StringBuilder(); for (int i = 0; i < 10; ++i) { String line = lines.get(idx + i); c1.append(line.charAt(0) == '#' ? '1' : '0'); c2.append(line.charAt(9) == '#' ? '1' : '0'); } return new int[] { parse(c1.toString()), parse(c1.reverse().toString()), parse(c2.toString()), parse(c2.reverse().toString()) }; } private static int parse(String s) { return Integer.parseInt(s, 2); } public int a2() { Map<Integer, Tile> tiles = parseTiles(); List<String> photo = new TileAligner(tiles).alignAll(); return new SeamonsterTracker(photo).getRoughSeaCount(); } private Map<Integer, Tile> parseTiles() { return IntStream.iterate(0, i -> i < lines.size(), i -> i + 12) .mapToObj(this::parseTile) .collect(toMap(Tile::getId, Function.identity())); } private static class TileAligner { private final Tile[][] aligned; private final Map<Integer, Tile> tiles; public TileAligner(Map<Integer, Tile> tiles) { this.tiles = tiles; int size = (int) Math.sqrt(tiles.size()); this.aligned = new Tile[size][size]; } public List<String> alignAll() { alignCorner(); alignRow(0); alignColumns(); return collapse(); } private List<String> collapse() { List<String> collapsed = new ArrayList<>(); for (int row = 0; row < aligned.length; row++) { Tile[] line = aligned[row]; for (int r = 0; r < line[0].image.size(); ++r) { StringBuilder str = new StringBuilder(); for (int col = 0; col < line.length; ++col) str.append(line[col].image.get(r)); collapsed.add(str.toString()); } } return collapsed; } private void alignRow(int row) { for (int col = 1; col < aligned[row].length; ++col) alignTile(row, col, 3); } private void alignTile(int row, int col, int borderidx) { Tile fixed = aligned[row + (borderidx % 2 == 0 ? borderidx - 1 : 0)][col + (borderidx % 2 == 1 ? 2 - borderidx : 0)]; Integer border = fixed.getBorders().get((borderidx + 2) % 4); Tile matchingTile = orientTile(fixed, findMatchingTile(border), borderidx); tiles.remove(matchingTile.getId()); aligned[row][col] = matchingTile; } private void alignColumns() { for (int row = 1; row < aligned.length; ++row) { alignTile(row, 0, 0); alignRow(row); } } private Tile orientTile(Tile fixedTile, Tile matchingTile, int matchposition) { int[] orientation = fixedTile.orientation(matchingTile); if (orientation[1] < 0) { matchingTile = matchingTile.flipD(); orientation = fixedTile.orientation(matchingTile); } while (orientation[1] != matchposition) { matchingTile = matchingTile.rotateR(); orientation = fixedTile.orientation(matchingTile); } return matchingTile; } private Tile findMatchingTile(Integer border) { return tiles.entrySet() .stream() .filter(e -> e.getValue().getPossibleBorders().anyMatch(border::equals)) .map(Entry::getValue) .findAny() .orElseThrow(); } private void alignCorner() { int corner = findCorner(); Tile cornerTile = tiles.remove(corner); List<Integer> sides = cornerTile.getBorders(); List<Tile> matchingCorner = tiles.entrySet() .stream() .filter(e -> e.getValue().getPossibleBorders().anyMatch(sides::contains)) .map(Entry::getValue) .collect(toList()); int[] c1 = cornerTile.orientation(matchingCorner.get(0)); int[] c2 = cornerTile.orientation(matchingCorner.get(1)); while (!Set.of(c1[0], c2[0]).containsAll(Set.of(1, 2))) { cornerTile = cornerTile.rotateR(); c1 = cornerTile.orientation(matchingCorner.get(0)); c2 = cornerTile.orientation(matchingCorner.get(1)); } aligned[0][0] = cornerTile; tiles.remove(cornerTile.getId()); } private int findCorner() { return tiles.entrySet() .stream() .filter(e -> tiles.entrySet() .stream() .filter(o -> !e.getKey().equals(o.getKey())) .filter(o -> o.getValue() .getPossibleBorders() .anyMatch(e.getValue().getBorders()::contains)) .count() == 2) .mapToInt(Entry::getKey) .findAny() .orElseThrow(); } } private class Tile { private final int id; private final List<String> image; private final List<Integer> bordersR; private final List<Integer> bordersL; private final List<String> raw; private Tile(int id, List<String> image, int[] bordersR, int[] bordersL, List<String> raw) { this.id = id; this.image = image; this.bordersR = Arrays.stream(bordersR).boxed().collect(toList()); this.bordersL = Arrays.stream(bordersL).boxed().collect(toList()); this.raw = raw; } public int getId() { return id; } public List<Integer> getBorders() { return bordersR; } public Stream<Integer> getPossibleBorders() { return Stream.concat(bordersR.stream(), bordersL.stream()); } public Tile rotateR() { Integer[] r = bordersR.toArray(new Integer[0]); Integer[] l = bordersL.toArray(new Integer[0]); return new Tile(id, Day20.rotateR(image), new int[] { r[3], r[0], r[1], r[2] }, new int[] { l[3], l[0], l[1], l[2] }, Day20.rotateR(raw)); } public Tile flipD() { Integer[] r = bordersR.toArray(new Integer[0]); Integer[] l = bordersL.toArray(new Integer[0]); return new Tile(id, Day20.flipD(image), new int[] { l[3], l[2], l[1], l[0] }, new int[] { r[3], r[2], r[1], r[0] }, Day20.flipD(raw)); } public int[] orientation(Tile other) { List<Integer> b = other.getBorders(); for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { if (bordersL.get(i).equals(b.get(j))) return new int[] { i, j }; if (bordersR.get(i).equals(b.get(j))) return new int[] { i, ~j }; } throw new IllegalArgumentException(); } } public Tile parseTile(int pos) { int tileId = Integer.parseInt(lines.get(pos).substring(5, 9)); int[] top = parseLine(pos + 1); int[] bottom = parseLine(pos + 10); int[] sides = parseCols(pos + 1); List<String> image = IntStream.range(pos + 2, pos + 10) .mapToObj(lines::get) .map(s -> s.substring(1, 9)) .collect(toList()); return new Tile(tileId, image, new int[] { top[0], sides[2], bottom[1], sides[1] }, new int[] { top[1], sides[3], bottom[0], sides[0] }, lines.subList(pos + 1, pos + 11)); } private static class SeamonsterTracker { @SuppressWarnings("unused") private static final String SEAMONSTER1 = "..................#."; private static final String SEAMONSTER2 = "#....##....##....###"; private static final String SEAMONSTER3 = ".#..#..#..#..#..#..."; private static final Pattern p2 = Pattern.compile(SEAMONSTER2); private static final Pattern p3 = Pattern.compile(SEAMONSTER3); private final List<String> photo; private int seamonster = 0; public SeamonsterTracker(List<String> photo) { this.photo = photo; } public int getRoughSeaCount() { if (seamonster == 0) countSeaMonsters(); return (int) photo.stream().flatMapToInt(String::chars).filter(c -> c == '#').count() - seamonster * 15; } private void countSeaMonsters() { List<String> rotatedPhoto = photo; for (int i = 0; i < 8 && seamonster == 0; ++i) { if (i == 4) rotatedPhoto = flipD(rotatedPhoto); else if (i % 4 != 0) rotatedPhoto = rotateR(rotatedPhoto); countSeaMonsters(rotatedPhoto); } } private void countSeaMonsters(List<String> rotatedPhoto) { for (int row = 1; row < rotatedPhoto.size() - 1; ++row) { Matcher m = p2.matcher(rotatedPhoto.get(row)); int start = 0; while (m.find(start)) { Matcher m2 = p3.matcher(rotatedPhoto.get(row + 1)); if (m2.find(m.start()) && m2.start() == m.start() && rotatedPhoto.get(row - 1).charAt(m.start() + 18) == '#') ++seamonster; start = m.start() + 1; } } } } private static List<String> flipD(List<String> img) { int size = img.size(); List<String> flipped = new ArrayList<>(size); for (int i = 0; i < size; ++i) { StringBuilder line = new StringBuilder(size); for (int j = 0; j < size; ++j) line.append(img.get(j).charAt(i)); flipped.add(line.toString()); } return flipped; } private static List<String> rotateR(List<String> img) { int size = img.size(); List<String> rotated = new ArrayList<>(size); for (int i = 0; i < size; ++i) { StringBuilder line = new StringBuilder(size); for (int j = size - 1; j >= 0; --j) line.append(img.get(j).charAt(i)); rotated.add(line.toString()); } return rotated; } }
package com.pk4u.colibri_lessons.activity; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.pk4u.colibri_lessons.R; import com.pk4u.colibri_lessons.adapter.UsersAdapter; import com.pk4u.colibri_lessons.pojo.User; import java.util.Arrays; import java.util.Collection; public class SearchUsersActivity extends AppCompatActivity { private RecyclerView usersRecyclerView; private UsersAdapter usersAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_users); initRecyclerView(); searchUsers(); } private void searchUsers() { Collection<User> users = getUsers(); usersAdapter.setItems(users); } private Collection<User> getUsers() { return Arrays.asList( new User( 929257819349700608L, "http://i.imgur.com/DvpvklR.png", "DevColibri", "@devcolibri", "Sample description", "USA", 42, 42 ), new User( 44196397L, "https://pbs.twimg.com/profile_images/782474226020200448/zDo-gAo0_400x400.jpg", "Elon Musk", "@elonmusk", "Hat Salesman", "Boring", 14, 13 ) ); } private void initRecyclerView() { usersRecyclerView = findViewById(R.id.users_recycler_view); usersRecyclerView.setLayoutManager(new LinearLayoutManager(this)); UsersAdapter.OnUserClickListener onUserClickListener = new UsersAdapter.OnUserClickListener() { @Override public void onUserClick(User user) { Intent intent = new Intent(SearchUsersActivity.this, UserInfoActivity.class); intent.putExtra(UserInfoActivity.USER_ID, user.getId()); startActivity(intent); } }; usersAdapter = new UsersAdapter(onUserClickListener); usersRecyclerView.setAdapter(usersAdapter); } }
package br.com.formacao.java.Teste.io; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import br.com.formacao.java.Modelo.Cliente; import br.com.formacao.java.Modelo.ContaCorrente; /** * Classe que representa o teste de serializa��o de uma conta. * * @author Guilherme Vilela * @version 0.1 */ public class TesteSerializacao { /** * * @param args * @throws FileNotFoundException * @throws IOException */ public static void main(String[] args) throws FileNotFoundException, IOException { Cliente cliente = new Cliente(); cliente.setNome("Nico"); cliente.setProfissao("Dev"); cliente.setCpf("234113131"); ContaCorrente cc = new ContaCorrente(222, 333); cc.setTitular(cliente); cc.deposita(220.3); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("cc.bin")); oos.writeObject(cc); oos.close(); } }
package com.lito.fupin.controller.website; import com.lito.fupin.business.category.ICategoryBusinessService; import com.lito.fupin.business.paper.IPaperBusinessService; import com.lito.fupin.meta.category.entity.Category; import com.lito.fupin.meta.paper.entity.Paper; import com.sun.org.apache.xpath.internal.operations.Mod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @Controller public class WebController { private final IWebBusinessService iWebBusinessService; Logger logger = LoggerFactory.getLogger(getClass()); public WebController(IWebBusinessService iWebBusinessService) { this.iWebBusinessService = iWebBusinessService; } @GetMapping("/") public String rootMe() { return "redirect:/homePage"; } @GetMapping("/homePage") public String homePage(Model model) { try { Map in = new HashMap(); in.put("categoryId", "5357e621-6952-4287-bbf3-1e878eaeff89"); // in.put("organizeId", "b4daa685-2a6b-4475-b194-2839541d6c59"); in.put("pageIndex", 0); in.put("pageSize", 10); // Map out = iWebBusinessService.listPaperToShow(in); // model.addAttribute("data", out); } catch (Exception ex) { } return "web/index"; } @GetMapping("/rootNewsList") public String rootNewsList(Model model) { try { Map in = new HashMap(); in.put("pageIndex", 0); in.put("pageSize", 10); Map out=iWebBusinessService.loadNewsHomePage(in); model.addAttribute("out", out); } catch (Exception ex) { logger.error(ex.getMessage()); } return "web/newsList"; } /** * 用户点击新闻子类 * * @param model * @param categoryId * @return */ @GetMapping("/newsList/{categoryId}") public String newsList(Model model, @PathVariable String categoryId) { /** * 当用户在新闻首页点击二级新闻时 * 读取所有新闻子类 * 把当前子类设置为active * 通过categoryId查询新闻列表 */ try { Map in = new HashMap(); in.put("categoryId", categoryId); in.put("pageIndex", 0); in.put("pageSize", 10); Map out = new HashMap(); out = iWebBusinessService.loadNewsHomePage(in); model.addAttribute("out", out); } catch (Exception ex) { logger.error(ex.getMessage()); } return "web/newsList"; } @GetMapping("/paperDetail/{paperId}") public String paperDetailPage(Model model, @PathVariable String paperId) { try { Map in = new HashMap(); in.put("paperId", paperId); Map out = iWebBusinessService.loadPaperDetailPage(in); model.addAttribute("paper", out.get("paper")); model.addAttribute("lastPaper", out.get("lastPaper")); model.addAttribute("nextPaper", out.get("nextPaper")); } catch (Exception ex) { logger.error(ex.getMessage()); } return "web/paperDetail"; } @RequestMapping("/gzfpHome") public String gzfpHome(Model model){ return "web/gzfp/gzfpHome"; } }
package com.gxc.city.service.impl; import java.util.List; import com.gxc.city.dao.CityDao; import com.gxc.city.domain.City; import com.gxc.city.service.CityService; import com.gxc.province.domain.Province; public class CityServiceImpl implements CityService { CityDao cityDao; public void setCityDao(CityDao cityDao) { this.cityDao = cityDao; } /** * 根据省查询全部城市 */ @Override public List<City> findAllCities(Province province) { return cityDao.findAllCities(province); } }
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz; import com.tencent.mm.plugin.game.gamewebview.ipc.GameProcessActivityTask; import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.UploadMediaFileHelp.UploadMediaFileActivity; import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.UploadMediaFileHelp.a; import com.tencent.mm.sdk.platformtools.x; class UploadMediaFileHelp$UploadMediaFileActivity$1 implements a { final /* synthetic */ GameProcessActivityTask.a jGc; final /* synthetic */ UploadMediaFileActivity jHS; UploadMediaFileHelp$UploadMediaFileActivity$1(UploadMediaFileActivity uploadMediaFileActivity, GameProcessActivityTask.a aVar) { this.jHS = uploadMediaFileActivity; this.jGc = aVar; } public final void b(boolean z, String str, String str2) { x.i("MicroMsg.UploadMediaFileActivity", "success = %b, mediaId = %s, mediaUrl = %s", new Object[]{Boolean.valueOf(z), str, str2}); if (z) { UploadMediaFileActivity.a(this.jHS, this.jGc, str, str2); } else { UploadMediaFileActivity.a(this.jHS, this.jGc); } } }
package com.nolansherman.team_manager.domains; import com.nolansherman.team_manager.domains.Domain; import javax.persistence.*; /** * A Futbol Team * @author Nolan Sherman * @since Nov-2017 * @version 1.0 */ @Entity public class Team extends Domain{ /** The Unique ID for this Team */ @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; /** The name of the Team*/ private String name; /** The Team's hometown */ private String hometown; /** The ID of the plaer who is this team's captain */ private long captainID; public Team(){} /** * Default Team constructor */ public Team(long id, String name, String hometown, long captainID) { super(); this.id = id; this.name = name; this.hometown = hometown; this.captainID = captainID; } /** * Returns value of id * @return */ public long getId() { return id; } /** * Sets new value of id * @param */ public void setId(long id) { this.id = id; } /** * Returns value of name * @return */ public String getName() { return name; } /** * Sets new value of name * @param */ public void setName(String name) { this.name = name; } /** * Returns value of hometown * @return */ public String getHometown() { return hometown; } /** * Sets new value of hometown * @param */ public void setHometown(String hometown) { this.hometown = hometown; } /** * Returns value of captainID * @return */ public long getCaptainID() { return captainID; } /** * Sets new value of captainID * @param */ public void setCaptainID(long captainID) { this.captainID = captainID; } /** * Create string representation of Team for printing * @return */ @Override public String toString() { return "Team [id=" + id + ", name=" + name + ", hometown=" + hometown + ", captainID=" + captainID + "]"; } }
package com.mashibing; /** * @program: tank * @description: * @create: 2020-04-01 16:44 **/ public enum Group { GOOD, BAD; }
package classes; public class BicycleDemo { public static void main(String[] args) { int startHeight = 50; int startCadence = 90; int startSpeed = 0; int startGear = 2; MountainBike mountainBike = new MountainBike(startHeight, startCadence, startSpeed, startGear); System.out.println(mountainBike.toString()); Bicycle bike = new MountainBike(++startHeight, startCadence, startSpeed, startGear); System.out.println(bike.toString()); } }
package com.learning.reactive; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; //@SpringBootTest class ReactiveMicroServiceApplicationTests { @Test void contextLoads() { System.out.println("Hi Testing"); } }
/* * 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 repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import users.DBHelper; import users.User; /** * * @author Elif */ public class FriendRepository { public boolean unfollow(String userEmail, String friendNickname) { UserRepository ur = new UserRepository(); int userId = ur.findUserId(userEmail); int friendId = ur.findUserIdFromNickname(friendNickname); int result = 0; try { String query = "delete from t_user_friendmapping where userid = ? and friendid = ?"; Connection connection = DBHelper.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setInt(1, userId); statement.setInt(2, friendId); result = statement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } if (result > 0) { FacesMessage msg1 = new FacesMessage("Removed from your following list."); msg1.setSeverity(FacesMessage.SEVERITY_INFO); FacesContext.getCurrentInstance().addMessage(null, msg1); return true; } return false; } public boolean isFollowing(String email, String nickname) { String query = "select * from t_user_friendmapping where t_user_friendmapping.userid = (select id from t_user where email = ?) and t_user_friendmapping.friendid = (select id from t_user where nickname = ?)"; try { Connection connection = DBHelper.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, email); statement.setString(2, nickname); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } public boolean addFriend(String userEmail, String friendNickname) { UserRepository ur = new UserRepository(); int userId = ur.findUserId(userEmail); int friendId = ur.findUserIdFromNickname(friendNickname); int result = 0; String query = "insert into t_user_friendmapping(userid, friendid) values(?,?)"; try { Connection connection = DBHelper.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setInt(1, userId); statement.setInt(2, friendId); result = statement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } if (result > 0) { FacesMessage msg1 = new FacesMessage("Added to your following list."); msg1.setSeverity(FacesMessage.SEVERITY_INFO); FacesContext.getCurrentInstance().addMessage(null, msg1); return true; } else { return false; } } public boolean deleteAccountFromFriendsTable(int userid) { String query; try { query = "update t_user_friendmapping set softdelete = 1 where userid = ?"; Connection connection = DBHelper.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setInt(1, userid); statement.executeUpdate(); query = "update t_user_friendmapping set softdelete = 1 where friendid = ?"; connection = DBHelper.getInstance().getConnection(); statement = connection.prepareStatement(query); statement.setInt(1, userid); statement.executeUpdate(); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } public ArrayList<User> getFriendsList(String userEmail) { UserRepository ur = new UserRepository(); ArrayList<User> friends = new ArrayList<>(); ArrayList<Integer> friendids = new ArrayList<>(); int userid = ur.findUserId(userEmail); String query = "Select * from t_user_friendmapping where userid=? and softdelete=0"; try { Connection connection = DBHelper.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setInt(1, userid); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { friendids.add(resultSet.getInt("friendid")); } query = "Select * from t_user where id=?"; statement = connection.prepareStatement(query); for (int id : friendids) { statement.setInt(1, id); resultSet = statement.executeQuery(); while (resultSet.next()) { friends.add(new User(resultSet.getString("firstname"), resultSet.getString("lastname"), resultSet.getString("nickname"))); } } } catch (Exception e) { e.printStackTrace(); } return friends; } public String findNicknameFromId(int id) { try { Connection con = DBHelper.getInstance().getConnection(); String query = "select * from t_user where id = ?"; PreparedStatement st = con.prepareStatement(query); st.setInt(1, id); ResultSet rs = st.executeQuery(); while (rs.next()) { return rs.getString("nickname"); } } catch (Exception ex) { ex.printStackTrace(); return null; } return null; } }
package me.djd.designmode.api; /** * Created by dujiande on 2017/3/23. */ import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.protobuf.ProtoConverterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; public class ServiceGenerator { private static final String HOST = ApiController.BASE_URL; private static Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(HOST) .addConverterFactory(ProtoConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()); public static <T> T createService(Class<T> tClass){ return builder.build().create(tClass); } /** * 创建带响应进度(下载进度)回调的service */ public static <T> T createResponseService(Class<T> tClass, ProgressResponseListener listener){ return builder .client(HttpClientHelper.addProgressResponseListener(listener)) .build() .create(tClass); } /** * 创建带请求体进度(上传进度)回调的service */ public static <T> T createReqeustService(Class<T> tClass, ProgressRequestListener listener){ return builder .client(HttpClientHelper.addProgressRequestListener(listener)) .build() .create(tClass); } }
/* * Minesweeper Project * by Group3 : Arnaud BABOL, Guillaume SIMMONEAU */ package Controler.Listeners; import View.Events.ViewEvent; /** * * @author simonneau */ public abstract class ViewListener { /** * * @param ev */ public abstract void catchViewEvent(ViewEvent ev); }
package LinkList; public class Node { private int value; private Node next; public Node (int v) { value = v; next = null; } public int getValue () { return value; } public void setNext (Node n) { next = n; } public void display() { System.out.print(value + " "); } public Node getNext() { return next; } }
package com.ugarit.java.designpatterns.bridge.impl; import java.util.Random; /** * Random integer strategy implementation to generate an integer greater than 100 * * @author durrah (mhd.durrah@gmail.com) on 5/16/15. */ public class GT100RandomIntGenerator implements RandomIntGenerator { /** * generator implementation * * @return a random integer less that 100 */ @Override public int generateInteger() { return new Random().nextInt(100) + (int) Math.abs(Math.random() * 1000); } }
package com.senac.apps.BatalhaNaval; import com.senac.apps.BatalhaNaval.controller.BatalhaNavalController; import com.senac.apps.BatalhaNaval.view.ConsoleView; public class BatalhaNaval { public static void main(String[] args) { BatalhaNavalController controller = new BatalhaNavalController(); ConsoleView view = new ConsoleView(); String command = ""; view.message("Digite 'ajuda' para comandos validos."); while (!command.equals("sair")) { command = view.read("Comando").toLowerCase(); if (command.equals("jogar")) controller.inicializaJogo(); if (command.equals("ajuda")) view.message("\nAjuda Jogar Sair"); } } }
package com.vilio.plms.pojo; /** * 类名: BorrowApply<br> * 功能:借款申请实体类<br> * 版本: 1.0<br> * 日期: 2017年7月7日<br> * 作者: wangxf<br> * 版权:vilio<br> * 说明:<br> */ public class BorrowApply { private Integer id; private String code; private String amount; private String applyTime; private String applyStatus; private String businessCode; private String contractCode; private String applyCode; private String createDate; private String modifyDate; private String paidAmount; private String paidTime; private String borrowPeriod; private String comments; private String borrowEndDate; public String getBorrowEndDate() { return borrowEndDate; } public void setBorrowEndDate(String borrowEndDate) { this.borrowEndDate = borrowEndDate; } //用户信息code private String customerCode; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getApplyTime() { return applyTime; } public void setApplyTime(String applyTime) { this.applyTime = applyTime; } public String getApplyStatus() { return applyStatus; } public void setApplyStatus(String applyStatus) { this.applyStatus = applyStatus; } public String getBusinessCode() { return businessCode; } public void setBusinessCode(String businessCode) { this.businessCode = businessCode; } public String getContractCode() { return contractCode; } public void setContractCode(String contractCode) { this.contractCode = contractCode; } public String getApplyCode() { return applyCode; } public void setApplyCode(String applyCode) { this.applyCode = applyCode; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getModifyDate() { return modifyDate; } public void setModifyDate(String modifyDate) { this.modifyDate = modifyDate; } public String getPaidAmount() { return paidAmount; } public void setPaidAmount(String paidAmount) { this.paidAmount = paidAmount; } public String getPaidTime() { return paidTime; } public void setPaidTime(String paidTime) { this.paidTime = paidTime; } public String getBorrowPeriod() { return borrowPeriod; } public void setBorrowPeriod(String borrowPeriod) { this.borrowPeriod = borrowPeriod; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getCustomerCode() { return customerCode; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public BorrowApply() { } public BorrowApply(Integer id, String code, String amount, String applyTime, String applyStatus, String businessCode, String contractCode, String applyCode, String createDate, String modifyDate, String paidAmount, String paidTime, String borrowPeriod, String comments, String customerCode, String borrowEndDate) { this.id = id; this.code = code; this.amount = amount; this.applyTime = applyTime; this.applyStatus = applyStatus; this.businessCode = businessCode; this.contractCode = contractCode; this.applyCode = applyCode; this.createDate = createDate; this.modifyDate = modifyDate; this.paidAmount = paidAmount; this.paidTime = paidTime; this.borrowPeriod = borrowPeriod; this.comments = comments; this.customerCode = customerCode; this.borrowEndDate = borrowEndDate; } }
package com.takshine.wxcrm.message.resp; import com.takshine.wxcrm.base.message.resp.BaseMessage; /** * 文本消息 * * @author liulin * @date 2014-02-26 */ public class TextMessage extends BaseMessage { // 回复的消息内容 private String Content; public String getContent() { return Content; } public void setContent(String content) { Content = content; } }
/* ... */ package bufmgr; import java.io.*; import java.util.*; import diskmgr.*; import global.*; public class BufMgr implements GlobalConst{ private Hashtable<PageId, Integer> pageFrameMap; private byte[][] bufPool; private FrameDesc[] frameDesc; private int numBufs; private Replacer replacer; /** * Create the BufMgr object. * Allocate pages (frames) for the buffer pool in main memory and * make the buffer manage aware that the replacement policy is * specified by replacerArg (i.e. Clock, LRU, MRU etc.). * * @param numbufs number of buffers in the buffer pool. * @param replacerArg name of the buffer replacement policy. */ public BufMgr(int numbufs, String replacerArg) { this.pageFrameMap = new Hashtable<>(); this.numBufs = numbufs; this.bufPool = new byte[numBufs][MINIBASE_PAGESIZE]; this.frameDesc = new FrameDesc[numbufs]; this.replacer = new LRUReplacer(this); } /** * Pin a page. * First check if this page is already in the buffer pool. * If it is, increment the pin_count and return a pointer to this * page. If the pin_count was 0 before the call, the page was a * replacement candidate, but is no longer a candidate. * If the page is not in the pool, choose a frame (from the * set of replacement candidates) to hold this page, read the * page (using the appropriate method from {\em diskmgr} package) and pin it. * Also, must write out the old page in chosen frame if it is dirty * before reading new page. (You can assume that emptyPage==false for * this assignment.) * * @param Page_Id_in_a_DB page number in the minibase. * @param page the pointer point to the page. * @param emptyPage true (empty page); false (non-empty page) * @throws Exception */ public void pinPage(PageId pin_pgid, Page page, boolean emptyPage) throws Exception { if(pageFrameMap.contains(pin_pgid)) { FrameDesc currentFrame = frameDesc[pageFrameMap.get(pin_pgid)]; // if (currentFrame.getPinCount() == 0) { // this.replacer.remove(currentFrame); //remove from replacement candidates. // } currentFrame.incrementPinCount(); } else { FrameDesc victimFrame = new FrameDesc() ; victimFrame = replacer.chooseVictim(); int i = Arrays.asList(frameDesc).indexOf(victimFrame); if (i == -1) { frameDesc[frameDesc.length+1] = victimFrame; i = frameDesc.length; } if(victimFrame.isDirty()) { flushPage(victimFrame.getPageNum()); } victimFrame.setPageNum(pin_pgid); victimFrame.incrementPinCount(); victimFrame.setDirty(false); pageFrameMap.put(pin_pgid, i); } } /** * Unpin a page specified by a pageId. * This method should be called with dirty==true if the client has * modified the page. If so, this call should set the dirty bit * for this frame. Further, if pin_count&gt;0, this method should * decrement it. If pin_count=0 before this call, throw an exception * to report error. (For testing purposes, we ask you to throw * an exception named PageUnpinnedException in case of error.) * * @param globalPageId_in_a_DB page number in the minibase. * @param dirty the dirty bit of the frame * @throws HashEntryNotFoundException * @throws PageUnpinnedException */ public void unpinPage(PageId PageId_in_a_DB, boolean dirty) throws HashEntryNotFoundException, PageUnpinnedException { if(pageFrameMap.containsKey(PageId_in_a_DB)) { int frameID = pageFrameMap.get(PageId_in_a_DB); if(frameDesc[frameID].getPinCount() == 0) { throw new PageUnpinnedException(null, ""); } frameDesc[frameID].decrementPinCount(); frameDesc[frameID].setDirty(dirty); if (frameDesc[frameID].getPinCount() == 0) { this.replacer.insert(frameDesc[frameID]); } }else { throw new HashEntryNotFoundException(null, ""); } } /** * Allocate new pages. * Call DB object to allocate a run of new pages and * find a frame in the buffer pool for the first page * and pin it. (This call allows a client of the Buffer Manager * to allocate pages on disk.) If buffer is full, i.e., you * can't find a frame for the first page, ask DB to deallocate * all these pages, and return null. * * @param firstpage the address of the first page. * @param howmany total number of allocated new pages. * * @return the first page id of the new pages. null, if error. * @throws IOException * @throws DiskMgrException * @throws FileIOException * @throws InvalidPageNumberException * @throws InvalidRunSizeException */ public PageId newPage(Page firstpage, int howmany) throws InvalidRunSizeException, InvalidPageNumberException, FileIOException, DiskMgrException, IOException { PageId pageId = new PageId(); try { SystemDefs.JavabaseDB.allocate_page(pageId, howmany); pinPage(pageId, firstpage, true); }catch(Exception e) { SystemDefs.JavabaseDB.deallocate_page(pageId); e.printStackTrace(); } return pageId; } /** * This method should be called to delete a page that is on disk. * This routine must call the method in diskmgr package to * deallocate the page. * * @param globalPageId the page number in the data base. * @throws PagePinnedException * @throws PageUnpinnedException * @throws HashEntryNotFoundException */ public void freePage(PageId globalPageId) throws PagePinnedException, HashEntryNotFoundException, PageUnpinnedException { int frameNum = pageFrameMap.get(globalPageId); if (!pageFrameMap.contains(globalPageId)) { return; } if (frameDesc[frameNum].getPinCount() > 0) { throw new PagePinnedException(null, ""); } try { if (frameDesc[frameNum].getPinCount() == 1) { this.unpinPage(globalPageId, false); } SystemDefs.JavabaseDB.deallocate_page(globalPageId); } catch (InvalidRunSizeException | InvalidPageNumberException | FileIOException | DiskMgrException | IOException e) { e.printStackTrace(); } } /** * Used to flush a particular page of the buffer pool to disk. * This method calls the write_page method of the diskmgr package. * * @param pageid the page number in the database. */ public void flushPage(PageId pageid) { if (!pageFrameMap.contains(pageid)) { return; } frameDesc[pageFrameMap.get(pageid)].setDirty(false); try { SystemDefs.JavabaseDB.write_page(pageid, new Page(bufPool[pageFrameMap.get(pageid)])); } catch (InvalidPageNumberException | FileIOException | IOException e) { e.printStackTrace(); } } /** Flushes all pages of the buffer pool to disk */ public void flushAllPages() { for(int i = 0; i < this.numBufs; i++) { if(frameDesc[i].isDirty()) { flushPage(frameDesc[i].getPageNum()); } } } /** Gets the total number of buffers. * * @return total number of buffer frames. */ public int getNumBuffers() { return this.numBufs; } /** Gets the total number of unpinned buffer frames. * * @return total number of unpinned buffer frames. */ public int getNumUnpinnedBuffers() { int j = 0; for(int i = 0; i < this.numBufs; i++) { if (frameDesc[i].getPinCount() == 0) { j++; } } return j; } }
package com.appsquadz.hostelutility; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import com.code_base_update.beans.HostelNoticeBean; import com.code_base_update.ui.BaseActivity; import com.code_base_update.ui.MyDialog; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import java.util.Calendar; import officials_module.model.SendNoticeModel; import officials_module.presenter.ISendNoticePresenter; import officials_module.view.ISendNoticeView; public class SendNoticeActivity extends BaseActivity<ISendNoticeView, ISendNoticePresenter> implements ISendNoticeView { private static final int CAMERA_REQUEST = 1211; private Uri imageUri = null; private ProgressDialog progressDialog; @Override protected ISendNoticePresenter createPresenter() { return new SendNoticeModel(); } @Override protected void initViewsAndEvents() { setupToolbar("Send Notice"); enableNavigation(); progressDialog = new MyDialog().getProgressDialog("Please wait...",this); getView(R.id.btn_send_notice).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(validateInput()){ mPresenter.sendNotice(mContext,getNotice()); } } }); getView(R.id.btn_add_image).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { firePhotoIntent(); } }); } private HostelNoticeBean getNotice() { long timeStamp = Calendar.getInstance().getTimeInMillis(); HostelNoticeBean notice = new HostelNoticeBean(); notice.setNoticeId(timeStamp+""); notice.setDate(timeStamp); notice.setImageUrl(""); notice.setByFaculty(getUserManager().getFacultyName()); notice.setByFaculty(getUserManager().getFacultyId()); notice.setNoticeBody(fetchText(R.id.et_notice_desc)); notice.setNoticeSubject(fetchText(R.id.et_notice)); return notice; } @Override protected int getLayoutId() { return R.layout.new_official_send_notice; } @Override public Uri getImage() { return imageUri; } @Override public void sendingInitiated() { progressDialog.show(); } @Override public void sendingFailed(String msg) { toastMsg("Failed: "+msg); progressDialog.dismiss(); } @Override public void sentSuccessfully() { toastMsg("Sent successfully"); clearViews(); progressDialog.dismiss(); } @Override public void onErrorOccurred() { toastMsg("Failed"); progressDialog.dismiss(); } @Override public void uploadingImage() { toastMsg("Uploading image..."); } private boolean validateInput(){ clearAllErrors(); if(TextUtils.isEmpty(fetchText(R.id.et_notice))||fetchText(R.id.et_notice).length()<20){ setError(R.id.et_notice,"Atleast 20 characters"); return false; }else if(TextUtils.isEmpty(fetchText(R.id.et_notice_desc))||fetchText(R.id.et_notice_desc).length()<50){ setError(R.id.et_notice_desc,"Atleast 50 characters"); return false; } return true; } private boolean checkPermissionForStorageRead() { return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } public boolean checkPermissionForCamera() { return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_REQUEST) // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { firePhotoIntent(); } else { Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show(); } } public void firePhotoIntent() { if (checkPermissionForCamera() && checkPermissionForStorageRead()) { CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .start(this); } else { final String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}; ActivityCompat.requestPermissions(this, permissions, CAMERA_REQUEST); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { imageUri = result.getUri(); setImageUrl(R.id.img_upload,result.getUri().toString()); } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); Log.d("CROP_IMAGE_ERROR", error.getMessage()); } } } }
package gov.samhsa.c2s.pcm.service.dto; import gov.samhsa.c2s.pcm.infrastructure.dto.RoleDto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ConsentActivityDto { private String consentReferenceId; private String actionType; private String updatedBy; private String updatedDateTime; private RoleDto role; }
/* * created 19.09.2005 by sell * * $Id: TableFonts.java 3 2005-11-02 03:04:20Z csell $ */ package com.byterefinery.rmbench.figures; import org.eclipse.swt.graphics.Font; /** * encapsulates the font choices for a table figure * * @author cse */ public class TableFonts { public Font titleFont; public Font columnFont; public Font typeFont; public static TableFonts titleFont(Font font) { TableFonts fonts = new TableFonts(); fonts.titleFont = font; return fonts; } public static TableFonts columnFont(Font font) { TableFonts fonts = new TableFonts(); fonts.columnFont = font; return fonts; } public static TableFonts typeFont(Font font) { TableFonts fonts = new TableFonts(); fonts.typeFont = font; return fonts; } private TableFonts() {} public TableFonts(Font titleFont, Font columnFont, Font typeFont) { this.titleFont = titleFont; this.columnFont = columnFont; this.typeFont = typeFont; } }
package com.rock.recyclerview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import com.rock.recyclerview.adapters.TeachAdapter; import com.rock.recyclerview.model.Model; import java.util.ArrayList; import java.util.List; /** * RecyclerView 在差量更新的时候 自带动画系统 * * * * */ public class MainActivity extends AppCompatActivity implements TeachAdapter.OnItemClickListener{ private RecyclerView mRecyclerView; private TeachAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mRecyclerView = (RecyclerView) findViewById(R.id.teach_recycler); // 设置布局管理器 GridLayoutManager layoutManager = new GridLayoutManager(this,3); // 合并单元格 spanSize 每一个item占多少个位置 layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { int spanSize = 1; switch (adapter.getItemViewType(position)) { case 100: spanSize = 3; break; } return spanSize; } }); mRecyclerView.setLayoutManager(layoutManager); // 绑定适配器 adapter = new TeachAdapter(this,getData()); mRecyclerView.setAdapter(adapter); adapter.setListener(this); // 设置动画系统 TeachItemAnimator animator = new TeachItemAnimator(); // 修改移除动画时长 animator.setRemoveDuration(3 * 1000); // 修改添加动画的时长 animator.setAddDuration(2 * 1000); mRecyclerView.setItemAnimator(animator); } private List<Model> getData() { List<Model> data = new ArrayList<>(); for (int i = 0; i < 30; i++) { Model model = new Model(); model.setName("天气冷了->" + i); if (i % 4 == 0) { model.setType(100); } data.add(model); } return data; } @Override public void onItemClick(int position) { // adapter.removeItem(position); adapter.insertItem(position); } }
package com.leetcode.wangruns; //30、best-time-to-buy-and-sell-stock-iii[数组] /** * Say you have an array for which the i^(th) element is the price of a given stock on day i * Design an algorithm to find the maximum profit. * You may complete at most two transactions. * Note: * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again) * * 假设最开始手里面只有0元 * hold1表示买了第一支赚的钱,是花钱,所以-todayPrice * release1表示将第一支卖了赚的钱,所以hold1+todayPrice * * [买入第二支,是在第一支卖出后的基础上买的] * * hold2表示买了第二支赚的钱,第二支中用了第一支卖了赚的钱去买的,所以release1-todayPrice * release2表示将第二支卖了赚的钱,所以hold2+todayPrice */ public class BestTimeToBuyAndSellStockiii030 { public int maxProfitiii(int[] prices) { int hold1=0x8fffffff,release1=0; int hold2=0x8fffffff,release2=0; for(int todayPrice:prices) { hold1=Math.max(hold1,-todayPrice);//如果今天买入第一支 release1=Math.max(release1, hold1+todayPrice);//如果今天将第一支卖出 hold2=Math.max(hold2, release1-todayPrice);//如果今天买入第二支,releas1为第一支赚的钱 release2=Math.max(release2, hold2+todayPrice);//如果今天将第二支卖出 } return release2; } }
package com.competition; import com.competition.client.*; public class Main { public static void main(String[] args) { new GetDecathlonCompetitionData(); GetDecathlonCompetitionData result = new GetDecathlonCompetitionData(); String inputFile = "src/com/competition/client/resources/Decathlon_input.txt"; GetDecathlonFinalResult finalResult = new GetDecathlonFinalResult(result.getData(inputFile)); new CreateXML(finalResult.getDecathlonFinalResult(), "src/com/competition/client/resources/DecathlonResult.xml"); } }
/* * 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 Gestion.controllers.ControlleurMetier; import Gestion.controllers.ClassMetiers.ProduitMetier; import crud.Produit; import org.json.simple.JSONObject; import org.orm.PersistentException; /** * * @author christian */ public class ProduitControlleur { @SuppressWarnings("FieldMayBeFinal") private int Action; private JSONObject retour; private Produit produit; @SuppressWarnings("FieldMayBeFinal") private JSONObject requette; public ProduitControlleur(int action,JSONObject data) { this.Action = action; this.requette = data; this.retour = new JSONObject(); this.traitement(); } private void traitement(){ switch(this.Action){ case 6:{ try { produit = Gestion.utils.ConverTypeObjet.metierTocrudProduit((ProduitMetier)requette.get("1"),false); if(produit.save()){ this.retour.put("code","0"); JSONObject json = new JSONObject(); produit.refresh(); json.put("0",Gestion.utils.ConverTypeObjet.crudTOmetierProduit(produit)); this.retour.put("message",json); }else{ this.retour.put("code","1"); this.retour.put("message","Echec de sauvegarde du produit"); } } catch (PersistentException ex) { this.retour.put("code","1"); this.retour.put("message","Echec de sauvegarde du produit"); Gestion.utils.Utils.addMessage("Produit:traitement:"+ex.toString(), true); }catch(Exception ex){ this.retour.put("code",1); this.retour.put("message","doublure"); Gestion.utils.Utils.addMessage("Produit:traitement:"+ex.toString(), true); } } break; case 7:{ try { produit = Gestion.utils.ConverTypeObjet.metierTocrudProduit((ProduitMetier)requette.get("1"),true); if(produit.save()){ this.retour.put("code","0"); JSONObject json = new JSONObject(); produit.refresh(); json.put("0",Gestion.utils.ConverTypeObjet.crudTOmetierProduit(produit)); this.retour.put("message",json); }else{ this.retour.put("code","1"); this.retour.put("message","Echec de mise à jour du produit"); } } catch (PersistentException ex) { this.retour.put("code","1"); this.retour.put("message","Echec de mise à jour du produit"); Gestion.utils.Utils.addMessage("Produit:traitement:"+ex.toString(), true); }catch(Exception ex){ this.retour.put("code",1); this.retour.put("message","doublure"); Gestion.utils.Utils.addMessage("Produit:traitement:"+ex.toString(), true); } } break; case 8:{ try { produit = Gestion.utils.ConverTypeObjet.metierTocrudProduit((ProduitMetier)requette.get("1"),true); produit.categoriesidCategories.clear(); produit.fournisseuridfournisseur.clear(); produit.save(); if(produit.deleteAndDissociate()){ this.retour.put("code","0"); this.retour.put("message",new JSONObject()); }else{ this.retour.put("code","1"); this.retour.put("message","Echec de suppression du produit"); } } catch (Exception ex) { this.retour.put("code","1"); this.retour.put("message","Echec de suppression du produit"); Gestion.utils.Utils.addMessage("Produit:traitement:"+ex.toString(), true); } } break; case 12:{ try { produit = new Produit(); String condition = requette.get("condition").toString(); String order = requette.get("order").toString(); Produit[] produits = Produit.listProduitByQuery(condition, order); JSONObject mes = new JSONObject(); int nbre = 0; for (Produit produit1 : produits) { mes.put(nbre,Gestion.utils.ConverTypeObjet.crudTOmetierProduit(produit1)); nbre++; } this.retour.put("code","0"); this.retour.put("message",mes); } catch (Exception ex) { this.retour.put("code","1"); this.retour.put("message","Echec de liste des produits"); Gestion.utils.Utils.addMessage("Produit:traitement:"+ex.toString(), true); } } } } public JSONObject getRetour() { return this.retour; } }