text
stringlengths
10
2.72M
package com.example.davidmacak.etzen; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; public class SelectLevel extends AppCompatActivity { SharedPreferences preferences; int levelRound; Button[] levelButton; LinearLayout LinearLayoutLevels; String level; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.selectlevel); preferences = getSharedPreferences("level",MODE_PRIVATE); levelRound = preferences.getInt("levelRound",1); LinearLayoutLevels = findViewById(R.id.LinearLayoutLevels); createButtons(); } public void selectLevel(View view){ int q = view.getId(); //Control if is openning level actual level. if(q>levelRound){ Toast.makeText(this,"Pomalu, nepředbíhej :)",Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(SelectLevel.this,Game.class); intent.putExtra("level",view.getId()); startActivity(intent); overridePendingTransition(R.anim.lefttoright,R.anim.righttoleft); finish(); } //Used information about done levels from sharedpreferences and use it to display open levels private void createButtons(){ LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(10,30,10,10); levelButton = new Button[10]; for(int d=1;d<10;d++){ levelButton[d] = new Button(this); if(d<=levelRound){ levelButton[d].setBackground(getDrawable(R.drawable.border_go)); //If id of button is equal to last open level, make on this button animation if(d==levelRound){ Animation animation = AnimationUtils.loadAnimation(this,R.anim.zoominlevel); levelButton[d].setAnimation(animation); } } else { levelButton[d].setBackground(getDrawable(R.drawable.border_level_na)); } levelButton[d].setLayoutParams(layoutParams); levelButton[d].setPadding(55,30,55,30); level = (getString(R.string.level)+" "+d); levelButton[d].setText(level); levelButton[d].setTextSize(20); levelButton[d].setId(d); final int finalD = d; levelButton[d].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectLevel(levelButton[finalD]); } }); LinearLayoutLevels.addView(levelButton[d]); } } }
package com.example.project.adapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.project.R; import com.example.project.models.ChatMessage; import com.example.project.models.ChatUser; import com.google.firebase.auth.FirebaseAuth; import java.util.ArrayList; public class ChatMessageRecyclerAdapter extends RecyclerView.Adapter<ChatMessageRecyclerAdapter.ViewHolder>{ private ArrayList<ChatMessage> _messages; private ArrayList<ChatUser> _users; private Context _context; public ChatMessageRecyclerAdapter(ArrayList<ChatMessage> messages, ArrayList<ChatUser> users, Context context) { this._messages = messages; this._users = users; this._context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_chat_message_list_item, parent, false); final ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { if(FirebaseAuth.getInstance().getUid().equals(_messages.get(position).getUser().getUser_id())){ holder.username.setTextColor(ContextCompat.getColor(_context, R.color.green1)); } else{ holder.username.setTextColor(ContextCompat.getColor(_context, R.color.blue2)); } holder.username.setText(_messages.get(position).getUser().getUsername()); holder.message.setText(_messages.get(position).getMessage()); } @Override public int getItemCount() { return _messages.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView message, username; public ViewHolder(View itemView) { super(itemView); message = itemView.findViewById(R.id.chat_message_message); username = itemView.findViewById(R.id.chat_message_username); } } }
/* * JBoss, Home of Professional Open Source * Copyright 2008-13, Red Hat Middleware LLC, and others contributors as indicated * by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.overlord.rtgov.ep; import static org.junit.Assert.*; import java.io.Serializable; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class EventProcessorTest { @Test public void testEventProcessorSerialization() { ObjectMapper mapper=new ObjectMapper(); TestEventProcessor ep=new TestEventProcessor(); ep.getParameters().put("testparam1", "hello"); ep.getParameters().put("testparam2", 5); try { String result=mapper.writeValueAsString(ep); TestEventProcessor epresult=mapper.readValue(result, TestEventProcessor.class); if (epresult == null) { fail("Result is null"); } if (!epresult.getParameters().get("testparam1").equals("hello")) { fail("Test param 1 is incorrect: "+epresult.getParameters().get("testparam1")); } int val=(Integer)epresult.getParameters().get("testparam2"); if (val != 5) { fail("Test param 2 is not 5: "+val); } } catch (Exception e) { fail("Failed to serialize ep: "+e); } } @Test public void testEventProcessorSerializationUnknownType() { ObjectMapper mapper=new ObjectMapper(); TestEventProcessor ep=new TestEventProcessor(); ep.getParameters().put("testparam1", "hello"); ep.getParameters().put("testparam2", new TestObject()); try { String result=mapper.writeValueAsString(ep); TestEventProcessor epresult=mapper.readValue(result, TestEventProcessor.class); if (epresult == null) { fail("Result 1 is null"); } if (!epresult.getParameters().get("testparam1").equals("hello")) { fail("Test param 1 is incorrect: "+epresult.getParameters().get("testparam1")); } Object obj=epresult.getParameters().get("testparam2"); if (obj == null) { fail("Result 2 is null"); } @SuppressWarnings("unchecked") java.util.Map<String,Object> map=(java.util.Map<String,Object>)obj; String val2=(String)map.get("val"); if (!val2.equals("TestValue")) { fail("Incorrect value: "+val2); } } catch (Exception e) { fail("Failed to serialize ep: "+e); } } public static class TestEventProcessor extends EventProcessor { @Override public Serializable process(String source, Serializable event, int retriesLeft) throws Exception { // TODO Auto-generated method stub return null; } } public static class TestObject { private String _val="TestValue"; public String getVal() { return (_val); } public void setVal(String val) { _val = val; } } }
package com.tencent.mm.plugin.brandservice.ui; import android.content.Context; import android.os.Looper; import android.util.AttributeSet; import android.view.View; import android.view.View.OnTouchListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.brandservice.b; import com.tencent.mm.plugin.brandservice.b.d; import com.tencent.mm.plugin.brandservice.b.h; import com.tencent.mm.plugin.brandservice.b.i; import com.tencent.mm.plugin.brandservice.ui.c.a; import com.tencent.mm.protocal.c.ju; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.x; import java.util.List; public class BizSearchResultItemContainer extends LinearLayout implements e { private int fdx = 0; private ListView hoG; c hoH; private TextView hoI; c hoJ; private a hoK; i hoL; private b hoM; private long[] hoN; int hoO; private boolean hoP; private int hoQ; private int hoq; static /* synthetic */ boolean a(BizSearchResultItemContainer bizSearchResultItemContainer) { return (!bizSearchResultItemContainer.hoJ.hoX || bizSearchResultItemContainer.hoJ.dYU == 0 || bizSearchResultItemContainer.hoJ.hoW) ? false : true; } public BizSearchResultItemContainer(Context context, AttributeSet attributeSet) { super(context, attributeSet); View inflate = View.inflate(getContext(), b.e.search_result_lv, this); this.hoJ = new c((byte) 0); this.hoK = new a((byte) 0); this.hoI = (TextView) inflate.findViewById(d.emptyTipsTV); this.hoG = (ListView) inflate.findViewById(d.resultLV); } public void setAdapter(c cVar) { this.hoH = cVar; if (this.hoH != null) { this.hoH.setScene(this.fdx); ListView listView = this.hoG; a aVar = this.hoK; View inflate = View.inflate(getContext(), b.e.loading_footer, null); aVar.hoT = inflate.findViewById(d.loading_progress); aVar.hoU = inflate.findViewById(d.loading_end); aVar.hoV = inflate.findViewById(d.loading_tip); aVar.hoT.setVisibility(8); aVar.hoU.setVisibility(8); aVar.hoV.setVisibility(8); listView.addFooterView(inflate, null, false); this.hoG.setAdapter(this.hoH); this.hoG.setOnScrollListener(new 1(this)); this.hoG.setOnItemClickListener(this.hoH); if (this.hoJ.hnQ == 0) { setBusinessTypes(1); return; } return; } this.hoG.setAdapter(this.hoH); } public c getAdapter() { return this.hoH; } private void c(String str, int i, long j) { ju juVar = null; this.hoJ.hoW = true; g.DF().a(1071, this); a ca = this.hoH.ca(this.hoN[this.hoN.length - 1]); List list = ca != null ? ca.hoF : null; if (list == null || list.size() == 0) { x.i("MicroMsg.BrandService.BizSearchResultItemContainer", "Get business content by type failed.(keyword : %s, offset : %s, businessType : %s)", new Object[]{str, Integer.valueOf(i), Long.valueOf(j)}); } else { juVar = (ju) list.get(list.size() - 1); } x.d("MicroMsg.BrandService.BizSearchResultItemContainer", "keyword(%s), offset(%d), businessType(%d), searchId(%s).", new Object[]{str, Integer.valueOf(i), Long.valueOf(j), juVar != null ? juVar.rlo : ""}); g.DF().a(new h(str, j, i, this.fdx, r6), 0); this.hoK.nw(1); } public final void a(int i, int i2, String str, l lVar) { int i3 = 3; x.i("MicroMsg.BrandService.BizSearchResultItemContainer", "errType (%d) , errCode (%d) , errMsg (errMsg)", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); if (this.hoM != null) { this.hoM.auV(); } if (i == 0 && i2 == 0) { this.hoP = false; if (lVar == null) { x.e("MicroMsg.BrandService.BizSearchResultItemContainer", "scene is null."); return; } int i4; int i5; int i6; if (lVar.getType() == 1070) { x.i("MicroMsg.BrandService.BizSearchResultItemContainer", "BizSearchHomePage."); g.DF().b(1070, this); i iVar = (i) lVar; List list = iVar.hnR == null ? null : iVar.hnR.sjy; this.hoH.d(this.hoJ.bHt, list); a ca = this.hoH.ca(this.hoN[this.hoN.length - 1]); i6 = (ca == null || ca.hoE) ? 0 : ca.dYU; if (i6 != 0) { i3 = 2; } if (list != null && list.size() > 0) { ju juVar = (ju) list.get(list.size() - 1); if (juVar != null) { this.hoJ.offset = juVar.rjC + this.hoO; } } i4 = i3; i5 = i6; } else if (lVar.getType() == 1071) { g.DF().b(1071, this); x.i("MicroMsg.BrandService.BizSearchResultItemContainer", "BizSearchDetailPage."); ju auP = ((h) lVar).auP(); if (auP == null || auP.jQF == null) { x.e("MicroMsg.BrandService.BizSearchResultItemContainer", "BusinessContent or itemList is null."); } i6 = auP == null ? 0 : auP.rlm; if (i6 == 0) { i4 = 3; } else { i4 = 2; } this.hoH.a(auP, true); if (auP != null) { x.d("MicroMsg.BrandService.BizSearchResultItemContainer", "searchId : %s.", new Object[]{auP.rlo}); this.hoJ.offset = auP.rjC + this.hoO; } i5 = i6; } else { x.e("MicroMsg.BrandService.BizSearchResultItemContainer", "Error type(%d).", new Object[]{Integer.valueOf(lVar.getType())}); return; } if (this.hoH.isEmpty()) { new ag(Looper.getMainLooper()).post(new 2(this)); } else { this.hoJ.hoX = true; } this.hoJ.dYU = i5; this.hoK.nw(i4); this.hoJ.hoW = false; x.v("MicroMsg.BrandService.BizSearchResultItemContainer", "The next load data offset is (%d).", new Object[]{Integer.valueOf(this.hoJ.offset)}); return; } this.hoJ.hoW = false; this.hoP = true; Toast.makeText(getContext(), getContext().getString(b.h.fmt_search_err, new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}), 0).show(); } final void reset() { this.hoH.auT(); this.hoK.nw(0); this.hoJ.hoX = false; this.hoJ.hoW = false; this.hoJ.offset = 0; this.hoJ.bHt = null; this.hoJ.dYU = 1; } public void setBusinessTypes(long... jArr) { if (jArr != null && jArr.length > 0) { this.hoN = jArr; this.hoJ.hnQ = 0; for (long j : jArr) { c cVar = this.hoJ; cVar.hnQ |= j; } this.hoH.e(jArr); } } public void setReporter(c.b bVar) { if (this.hoH != null) { this.hoH.setReporter(bVar); } } public final void aV(String str, int i) { if (this.hoH.isEmpty()) { this.hoI.setVisibility(8); } if (str != null) { String trim = str.trim(); if (!"".equals(trim)) { if ((!trim.equals(this.hoJ.bHt) || this.hoP) && !this.hoJ.hoW) { reset(); this.hoJ.hoW = true; this.hoJ.bHt = trim; this.hoO = i; if (this.hoQ != 1) { g.DF().a(1070, this); this.hoL = new i(this.hoJ.bHt, this.hoJ.hnQ, this.fdx); g.DF().a(this.hoL, 0); } else if (this.hoN.length == 0) { x.i("MicroMsg.BrandService.BizSearchResultItemContainer", "business type size is 0."); return; } else { c(trim, i, this.hoN[0]); this.hoK.nw(0); } if (this.hoM != null) { this.hoM.auU(); } } } } } public b getIOnSearchStateChangedListener() { return this.hoM; } public void setIOnSearchStateChangedListener(b bVar) { this.hoM = bVar; } public void setScene(int i) { this.fdx = i; this.hoH.setScene(this.fdx); } public void setAddContactScene(int i) { this.hoq = i; this.hoH.setAddContactScene(i); } public final void setDisplayArgs$25decb5(boolean z) { this.hoH.t(z, false); } public void setMode(int i) { this.hoQ = i; } public void setOnTouchListener(OnTouchListener onTouchListener) { super.setOnTouchListener(onTouchListener); this.hoG.setOnTouchListener(onTouchListener); } }
package com.example.day02.view; import android.content.Intent; import android.content.SharedPreferences; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.day02.R; import com.example.day02.base.BaseActivity; import com.example.day02.contract.LoginContract; import com.example.day02.persenter.ILoginPersenterIpml; public class LoginActivity extends BaseActivity<ILoginPersenterIpml> implements LoginContract.LoginView { private android.widget.EditText edName; private android.widget.EditText edPass; private SharedPreferences preferences; private boolean name; private Button btn; @Override protected void initData() { } @Override protected void initView() { edName = (EditText) findViewById(R.id.ed_name); edPass = (EditText) findViewById(R.id.ed_pass); btn = findViewById(R.id.btn); preferences = getPreferences(MODE_PRIVATE); name = preferences.getBoolean("name", false); if (name){ startActivity(new Intent(LoginActivity.this,MainActivity.class)); }else { ligon(); } } private void ligon() { btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(getName())&&TextUtils.isEmpty(getPass())){ Toast.makeText(LoginActivity.this, "账号或密码不能为空", Toast.LENGTH_SHORT).show(); }else { getPersenter().login(getName(),getPass()); } } }); } @Override protected int getLayoutID() { return R.layout.activity_login; } @Override protected ILoginPersenterIpml getPersenter() { return new ILoginPersenterIpml(this); } @Override public String getName() { return edName.getText().toString(); } @Override public String getPass() { return edPass.getText().toString(); } @Override public void getLogin(long string) { if (string>0){ Toast.makeText(this, "输入正确", Toast.LENGTH_SHORT).show(); SharedPreferences.Editor edit = preferences.edit(); edit.putBoolean("name",true); edit.commit(); btn.setText("登录成功"); startActivity(new Intent(LoginActivity.this,MainActivity.class)); }else { Toast.makeText(this, "输入错误", Toast.LENGTH_SHORT).show(); SharedPreferences.Editor edit = preferences.edit(); edit.putBoolean("name",false); edit.commit(); btn.setText("登录失败"); } } }
package com.majhub.thevibe; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.squareup.picasso.Picasso; public class ImageViewerActivity extends AppCompatActivity { private ImageView imageView; private String imageUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_viewer); imageView = findViewById(R.id.image_viewer); imageUrl = getIntent().getStringExtra("Url"); Picasso.get().load(imageUrl).into(imageView); } @Override public void onBackPressed() { super.onBackPressed(); Intent chatActivityIntent = new Intent(ImageViewerActivity.this,ChatActivity.class); startActivity(chatActivityIntent); } }
package slepec.hra.rozhrani; /** * Verejne metody pro ovladani rozhrani programu * * @author Pavel Jurca, xjurp20@vse.cz * @version 2 */ public interface IRozhrani extends slepec.util.Subject, slepec.util.Observer { void setVystup(String vystup); String getVstup(); //vrati textovy retezec ze vstupu String getVstup(String vyzva); }
package com.jei.spring.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SecurityWebApplicationInitalizer extends AbstractSecurityWebApplicationInitializer { /** * Automatically register the springSecurityFilterChain Filter for every URL in your application * 필터체인을 자동으로 다 등록해줌!! */ }
package com.train.ioc; public class TestWithFactory { public static void main(String[] args) { //Weapon w = new Axe(); Weapon w = WeaponFactory.getWeapon(); Knight k = new Knight("Leon",w); k.fight(); } }
package com.perhab.napalm; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import oshi.SystemInfo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; /** * Created by bigbear3001 on 01.07.17. */ @Slf4j public class MarkdownFileOutPrinter implements Printer { private static final long STARTTIME_NOT_SET = -1L; private final File file; public MarkdownFileOutPrinter(String filename) { file = new File(filename); } @Override public void print(Collection<Result> results) { try { if(file.exists()) { file.delete(); } file.createNewFile(); @Cleanup FileOutputStream fos = new FileOutputStream(file); @Cleanup OutputStreamWriter writer = new OutputStreamWriter(fos); writer.append("Performance Report\n"); writer.append("==================\n"); writer.append("Created at " + new SimpleDateFormat("dd.MM.yyyy").format(new Date()) + "\n"); writer.append("on " + getSystemInformation() + "\n\n"); writer.append("|**Name**|**1**|**100**|**10000**|**1000000**|\n"); writer.append("|:-------|----:|------:|--------:|----------:|\n"); Class<?> lastImplementedInterface = null; for (Result result : results) { Class<?> implementedInterface = result.getStatement().getGroup().getImplementedInterface(); if (implementedInterface != lastImplementedInterface) { writer.append("|**" + implementedInterface.getCanonicalName() + "**|||||\n"); lastImplementedInterface = implementedInterface; } writer.append("|"); writer.append(result.getStatement().toString()); long startTime = STARTTIME_NOT_SET; for (long time : result.getTimes()) { if (startTime == STARTTIME_NOT_SET) { startTime = time; } else { writer.append('|'); writer.append((time - startTime) + ""); writer.append("ms"); } } writer.append("|\n"); writer.flush(); } } catch (java.io.IOException e) { log.error("Cannot write to file: {}", file.getAbsolutePath(), e); } } private String getSystemInformation() { SystemInfo systemInfo = new SystemInfo(); return systemInfo.getHardware().getProcessor().toString(); } }
package com.murkino.domain.cat.state; public final class StatesFactory { public State createByName(String name) throws Exception { Class<?> clazz = Class.forName("com.murkino.domain.state." + name); return (State) clazz.newInstance(); } }
package com.komdosh.yandextestapp.data.dto; import java.util.List; import java.util.Map; /** * @author komdosh * created on 19.03.17 */ public class LangsDto { private List<String> dirs; private Map<String, String> langs; public List<String> getDirs() { return dirs; } public void setDirs(List<String> dirs) { this.dirs = dirs; } public Map<String, String> getLangs() { return langs; } public void setLangs(Map<String, String> langs) { this.langs = langs; } @Override public String toString() { return "LangsDto{" + "dirs=" + dirs + ", langs=" + langs + '}'; } }
package conllectionSafety; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class HashMapDemo { public static void main(String[] args) { Map<String,String> map = new HashMap<>(); Map<String,String> map2 = new ConcurrentHashMap<>(); for(int i=0; i<10;i++){ new Thread(() -> { map2.put(UUID.randomUUID().toString().substring(0,4),UUID.randomUUID().toString().substring(0,4)); System.out.println(map2); },String.valueOf(i)).start(); } } private static void HashMapTest() { Map<String,String> map = new HashMap<>(); map.put("111","3"); map.put("222","6"); map.put("333","9"); System.out.println(map); System.out.println(map.containsKey("111")); System.out.println(map.get("222")); System.out.println(map.size()); System.out.println(map); } }
package de.jmda.gen.java.impl; import de.jmda.gen.LineIndenter; import de.jmda.gen.java.DeclaredMethodGenerator; import de.jmda.gen.java.ParameterGenerator; public class MainMethodGenerator extends DefaultStaticMethodGenerator { public MainMethodGenerator(String methodBody) { super(); DeclaredMethodGenerator dmg = getDeclaredMethodGenerator(); dmg.demandModifiersGenerator().setPublic(true); dmg.getTypeNameGenerator().setTypeName(Void.TYPE.getName()); dmg.getMethodNameGenerator().setMethodName("main"); ParameterGenerator pg = new DefaultParameterGenerator("String[]", "args"); dmg.add(pg); dmg.setMethodBody(methodBody); dmg.setLineIndenter(new LineIndenter("\t", 1)); } }
import java.util.Scanner; public class Main { public static void main(String[] args){ int red, green, blue, min; Scanner sc = new Scanner(System.in); int N = sc.nextInt(); //ÁýÀǰ³¼ö(1~1000) int[][] cost = new int[3][N]; cost[0][0] = sc.nextInt(); cost[1][0]= sc.nextInt(); cost[2][0] = sc.nextInt(); for(int i = 1; i < N; i++){ red = sc.nextInt(); green = sc.nextInt(); blue = sc.nextInt(); cost[0][i] = red + Math.min(cost[1][i-1], cost[2][i-1]); cost[1][i] = green + Math.min(cost[0][i-1], cost[2][i-1]); cost[2][i] = blue + Math.min(cost[0][i-1], cost[1][i-1]); } min = Math.min(Math.min(cost[0][N-1], cost[1][N-1]), cost[2][N-1]); System.out.println(min); } }
package com.tsm.template.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public interface BaseDTO { }
package clinica; import java.util.List; public class Servico { private void cirugira() {} private void administrar() {} private void platao() {} private void consulta() {} }
package de.jmda.app.cgol.fx.mod.sidebar.addfigure; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; public class AddFigureController { @FXML private TitledPane tPn; @FXML private ComboBox< ? > cmbBxSelectFigure; @FXML private TextField tfAddFigureAtX; @FXML private TextField tfAddFigureAtY; @FXML private Button btnAddFigure; @FXML private void initialize() { tPn.setExpanded(true); } }
package com.bozhong.lhdataaccess.client.domain.dto; /** * @author gongwq * @create 2017-10-17 16:01 */ public class PrimaryKeyIdReqDTO extends BaseReqDTO{ private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public void validation() { } @Override public String controllerValidation() { if(id == null || id == 0){ return "id不能为空"; } return null; } }
package com.hovsep.visitor.ui.activity; import android.content.Intent; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import com.hovsep.visitor.R; import com.hovsep.visitor.adapter.HowToUsePagerAdapter; import com.hovsep.visitor.ui.listener.OnDotPageChangeListener; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; public class HowToUseActivity extends AppCompatActivity { public static final int LAST_PAGE = 3; private ViewPager viewPager; @BindView(R.id.next_page_button) ImageView nextPageButton; @BindView(R.id.skip_button) TextView skipButton; @BindView(R.id.done_button) TextView doneButton; @BindViews({R.id.circle_page1, R.id.circle_page2, R.id.circle_page3, R.id.circle_page4}) List<ImageView> dots; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_how_to_use); ButterKnife.bind(this); initViewPager(); } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.how_to_use_pager); HowToUsePagerAdapter pagerAdapter = new HowToUsePagerAdapter(getSupportFragmentManager()); viewPager.addOnPageChangeListener(new OnDotPageChangeListener(dots, nextPageButton, skipButton, doneButton)); viewPager.setAdapter(pagerAdapter); } @OnClick(R.id.next_page_button) public void nextPage() { int position = viewPager.getCurrentItem(); viewPager.setCurrentItem(position + 1); } @OnClick(R.id.skip_button) public void skipPages() { viewPager.setCurrentItem(LAST_PAGE); } @OnClick(R.id.done_button) public void done() { Intent i = new Intent(HowToUseActivity.this, MainMenuActivity.class); startActivity(i); } }
/** * Developer: Kadvin Date: 14-5-28 下午2:52 */ package spring.test.ann_service_import; import net.happyonroad.spring.service.ServiceExporter; import net.happyonroad.spring.service.ServiceImporter; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import spring.test.ann_service_export.AnnotationService; import spring.test.ann_service_import.beans.AnnotationUser; import spring.test.ann_service_import.more.MoreProvider; /** * 基于Annotation的应用配置,引用服务 */ @Configuration @ComponentScan("spring.test.ann_service_import") public class AppConfig implements InitializingBean{ @Autowired private ServiceImporter importer; @Autowired private ServiceExporter exporter; @Bean public AnnotationService moreAnnotationService(){ return new MoreProvider(); } @Bean public AnnotationUser annotationUser() { return new AnnotationUser(); } @Bean public AnnotationService annotationProvider() { return importer.imports(AnnotationService.class); } @Bean public AnnotationService scannedProvider(){ return importer.imports(AnnotationService.class, "scanned"); } @Override public void afterPropertiesSet() throws Exception { exporter.exports(AnnotationService.class, moreAnnotationService(), "more"); } }
import java.io.*; import java.util.*; public class Friendship { private ArrayList<String> readData(String filename) throws FileNotFoundException, IOException { ArrayList <String> information = new ArrayList(); FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); String line; //read information begin while ((line = br.readLine()) != null) { information.add(line); } return information; } private void writeData(String filename) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); ArrayList <String> data = this.readData("Friendship2.txt"); StringTokenizer st = new StringTokenizer(data.get(0), ","); bw.write( "*Vertices " + (data.size()-1) + "\n" ); int idx = 1; while (st.hasMoreTokens()) { bw.write( idx + " " + st.nextToken() + "\n" ); idx++; } bw.write( "*Edges \n" ); ArrayList<String> arr = new ArrayList<String>(); for( int i = 1; i < data.size() ; i++ ) { StringTokenizer st2 = new StringTokenizer( data.get(i), ","); int j = 0; while ( st2.hasMoreTokens() ) { if( st2.nextToken().equals("1" ) ) { if( arr.contains(j + " " + i)) { //do nothing } else { arr.add(i + " " + j); bw.write( i + " " + j + "\n") ; } } j++; } } //write information end bw.close(); } public static void main(String[] args) throws IOException { Friendship f = new Friendship(); f.writeData("VerticesEdges.txt"); } }
package com.uptc.prg.maze.view.panels; import com.uptc.prg.maze.view.UIStrings; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class ScalePanel extends JPanel { private JSlider mScaleFactor; private JLabel mTitle; private ImagePanel mImagePanel; public ScalePanel(ImagePanel imagePanel) { this.mImagePanel = imagePanel; this.initializeUI(); this.initialize(); } private void initializeUI() { this.mScaleFactor = new JSlider(SwingConstants.HORIZONTAL, 1, 10, 1); this.mScaleFactor.setMinorTickSpacing(1); this.mScaleFactor.setPaintLabels(true); this.mScaleFactor.setPaintTicks(true); this.mScaleFactor.addChangeListener(e -> this.setImagePanelScale()); this.mTitle = new JLabel(UIStrings.getString("SCALE_FACTOR")); this.mTitle.setAlignmentX(Component.CENTER_ALIGNMENT); } private void initialize() { this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.setBorder(new EmptyBorder(20, 20, 20, 20)); this.add(this.mTitle); this.add(this.mScaleFactor); } private void setImagePanelScale() { this.mImagePanel.setScale(this.mScaleFactor.getValue()); } }
/**************************************************** * $Project: DinoAge $ * $Date:: Jan 30, 2008 12:34:20 AM $ * $Revision: $ * $Author:: khoanguyen $ * $Comment:: $ **************************************************/ package org.ddth.dinoage.core; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class WorkspaceManager { private static final String WORKSPACE_SEPARATOR = "\n"; private String[] workspaces; private String selection; public WorkspaceManager(String recentWorkspaces) { StringTokenizer tokenizer = new StringTokenizer(recentWorkspaces, WORKSPACE_SEPARATOR); List<String> workspaces = new ArrayList<String>(); while (tokenizer.hasMoreElements()) { String directory = tokenizer.nextToken(); File workspaceFolder = new File(directory); workspaces.add(workspaceFolder.getAbsolutePath()); } selection = workspaces.size() > 0 ? workspaces.get(0) : null; setWorkspaces(workspaces.toArray(new String[workspaces.size()])); } public String getRecentWorkspaces() { StringBuilder recentWorkspaces = new StringBuilder(); if (selection != null) { recentWorkspaces.append(selection + WORKSPACE_SEPARATOR); } String[] workspaces = getWorkspaces(); for (String workspace : workspaces) { if (!workspace.equals(selection)) { recentWorkspaces.append(workspace + WORKSPACE_SEPARATOR); } } return recentWorkspaces.toString(); } public String getSelection() { return selection; } public String[] getWorkspaces() { return workspaces; } public void setWorkspaces(String[] workspaces) { this.workspaces = workspaces; } public void setWorkspace(String workspacePath) { selection = workspacePath; } }
package com.daheka.nl.social.shadowfish.restserver.repository; import com.daheka.nl.social.shadowfish.dao.AppUser; import com.daheka.nl.social.shadowfish.dao.Profile; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * Created by daheka on 2/10/17. */ @Repository public interface ProfileRepository extends CrudRepository<Profile, Long> { Profile findByAppUser(AppUser appUser); }
package com.kodilla.patterns.singleton; import org.junit.Assert; import org.junit.Test; public class LoggerTestSuite { @Test public void testAddOneEvent() { //Given //When Logger.getInstance().log("test event"); String messageFromLog = Logger.getInstance().getLastLog(); //Then Assert.assertEquals("test event", messageFromLog); } @Test public void testAddTwoEvents() { //Given //When Logger.getInstance().log("test event"); Logger.getInstance().log("another test event"); String messageFromLog = Logger.getInstance().getLastLog(); //Then Assert.assertEquals("another test event", messageFromLog); } }
package com.steven.base.util; import java.util.Observable; /** * @user steven * @createDate 2019/2/28 13:12 * @description 自定义 */ public class PositionObservable extends Observable { public static PositionObservable sInstance; public static PositionObservable getInstance() { if (sInstance == null) { sInstance = new PositionObservable(); } return sInstance; } /** * 通知观察者FloatingDragger */ public void update() { setChanged(); notifyObservers(); } }
package com.czm.cloudocr.util; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.util.Date; /** * Created by Phelps on 2018/3/26. */ public class SystemUtils { public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } public static Bitmap compressImage(Bitmap image, File file) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();//重置baos即清空baos //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流 image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 options -= 10;//每次都减少10 } try { FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 return bitmap; } public static String dateFormat(String date){ DateFormat mediumDateFormat = DateFormat.getDateTimeInstance (DateFormat.MEDIUM,DateFormat.MEDIUM); return mediumDateFormat.format(new Date(Long.parseLong(date))); } public static ProgressDialog waitingDialog(Context context, String message){ ProgressDialog progressDialog = new ProgressDialog(context); progressDialog.setIndeterminate(false);//循环滚动 progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage(message); progressDialog.setCancelable(false);//false不能取消显示,true可以取消显示 return progressDialog; } public static String md5(String string) { if (TextUtils.isEmpty(string)) { return ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(string.getBytes()); String result = ""; for (byte b : bytes) { String temp = Integer.toHexString(b & 0xff); if (temp.length() == 1) { temp = "0" + temp; } result += temp; } return result; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }
package com.perhab.napalm.statement; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import com.perhab.napalm.Result; import com.perhab.napalm.StatementGroup; import lombok.extern.slf4j.Slf4j; @Slf4j @AllArgsConstructor public class BaseStatement implements Statement { private Object implementationObject; @Getter private Method method; @Getter(lazy = true) private final StatementGroup group = StatementGroup.getStatementGroup(this); @Getter(lazy = true) private final String sourceCode = ExecutionExplorer.getSourceCode(method, implementationObject); @Getter private Object[] arguments; private int[] iterations; private int threads; public static List<BaseStatement> getBaseStatements(Class<?> implementation) { ArrayList<BaseStatement> statements = new ArrayList<>(); for (Method executionMethod : ExecutionExplorer.findExecutionMethods(implementation)) { try { statements.add(new BaseStatement( implementation.getConstructor(new Class[0]).newInstance(), executionMethod, ExecutionExplorer.getArguments(executionMethod, implementation), ExecutionExplorer.getIterations(executionMethod), ExecutionExplorer.getThreads(executionMethod) )); } catch (SecurityException | NoSuchMethodException e) { throw new StatementNotInitalizableException("Cannot find or access no args constructor of " + implementation, e); } catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new StatementNotInitalizableException("Cannot instanciate object with no args constructor (" + implementation + ")", e); } } return statements; } /* (non-Javadoc) * @see com.perhab.napalm.statement.StatementInterface#execute() */ public Result execute() { ExecutionThread[] executionThreads = new ExecutionThread[threads]; for (int i = 0; i < threads; i++) { executionThreads[i] = new ExecutionThread(); } for (int i = 0; i < threads; i++) { executionThreads[i].start(); } for (int i = 0; i < threads; i++) { try { executionThreads[i].join(); } catch (InterruptedException e) { log.error("Got interrupted", e); } } return executionThreads[0].result; } @Override public final String toString() { return implementationObject.getClass().getName(); } public int getExpectedTimes() { return iterations.length + 1; } private class ExecutionThread extends Thread { Result result; @Override public void run() { result = new Result(BaseStatement.this); try { result.setResult(method.invoke(implementationObject, arguments)); int j = 1; for (int i = 0; i < iterations.length; i++) { for (; j < iterations[i]; j++) { method.invoke(implementationObject, arguments); } result.time(); } result.stop(); } catch (InvocationTargetException e) { throw new InvocationError("Cannot invode method " + method + " on implementation " + implementationObject + " with args " + arguments, e); } catch (IllegalArgumentException e) { throw new InvocationError("Cannot invode method " + method + " on implementation " + implementationObject + " with args " + arguments, e); } catch (IllegalAccessException e) { throw new InvocationError("Cannot invode method " + method + " on implementation " + implementationObject + " with args " + arguments, e); } } } }
package com.zinnaworks.nxpgtool.util; public class HttpRequestHelper { public static String buildParams(String[][] pairs) { if (pairs.length == 0) throw new IllegalArgumentException(); StringBuilder params = new StringBuilder(); for (int i = 0; i < pairs.length; i++) { String[] pair = pairs[i]; params.append(pair[0] + "=" + pair[1] + "&"); } return params.substring(0, params.lastIndexOf("&")); } }
package assgn.JianKai; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; public class aff{ String Aid; String name; String password; String password2; String IC; String tel; String email; String resname; String resadd; String rescat; String postal; String theerror=""; double distance; public aff(){} public aff(String Aid,String name,String password,String IC,String tel,String email,String resname,String resadd,String postal,String rescat) { this.Aid = Aid; this.name = name; this.password = password; this.IC = IC; this.tel = tel; this.email = email; this.resname = resname; this.resadd = resadd; this.postal = postal; this.rescat = rescat; this.distance = -1; } public aff(String Aid,String name,String password,String password2,String IC,String tel,String email,String resname,String resadd,String postal,String rescat) { this.Aid = Aid; this.name = name; this.password = password; this.password2 = password2; this.IC = IC; this.tel = tel; this.email = email; this.resname = resname; this.resadd = resadd; this.postal = postal; this.rescat = rescat; this.distance = -1; } public String getAid() { return Aid; } public void setAid(String Aid) { this.Aid = Aid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPassword2() { return password2; } public void setPassword2(String password2) { this.password2 = password2; } public String getIC() { return IC; } public void setIC(String IC) { this.IC = IC; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getResname() { return resname; } public void setResname(String resname) { this.resname = resname; } public String getResadd() { return resadd; } public void setResadd(String resadd) { this.resadd = resadd; } public String getRescat() { return rescat; } public void setRescat(String rescat) { this.rescat = rescat; } public String getPostal() { return postal; } public void setPostal(String postal) { this.postal = postal; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public boolean checkName() { boolean result = true; char c[] = name.toCharArray(); int namelength = c.length; for(int i=0;i<namelength;i++) { if (Character.isDigit(c[i])) { theerror += "Do not enter digit in your name \n"; return false; } } if (name.isEmpty()) { theerror += "Please enter your name \n"; return false; } return result; } public boolean checkPassword() { boolean result = true; if (password.isEmpty()) { theerror += "Please enter password\n"; return false; } if (!password.equals(password2)) { theerror += "Password entered not same\n"; return false; } return result; } public boolean checkIC() { boolean result = true; char d[] = IC.toCharArray(); int iclength = d.length; if (iclength != 12) { theerror += "IC length error \n"; return false; } for (int o = 0; o < iclength; o++) { if (!Character.isDigit(d[o])) { theerror += "Please enter digit only for IC number\n"; return false; } } if (IC.isEmpty()) { theerror += "Please enter your IC \n"; return false; } return result; } public boolean checkTel() { boolean result = true; if (tel.isEmpty()) { theerror += "Please enter your telephone number \n"; return false; } char e[] = tel.toCharArray(); int tellength = e.length; for (int p = 0; p < tellength; p++) { if (!Character.isDigit(e[p])) { theerror += "Please enter digit for telephone number only \n"; return false; } } if (tellength != 10) { theerror += "Error telephone length\n"; return false; } return result; } public boolean checkEmail(){ boolean result = true; if (!(Pattern.matches("^[a-zA-Z0-9]+[@]{1}+[a-zA-Z0-9]+[.]{1}+[a-zA-Z0-9]+$", email))) { theerror += "Please enter valid email \n"; return false; } if (email.isEmpty()) { theerror += "Please enter email \n"; return false; } return result; } public boolean checkRes() { boolean result = true; if (resname.isEmpty()) { theerror += "Please enter resturant name\n"; return false; } return result; } public boolean checkResAdd() { boolean result = true; if (resadd.isEmpty()) { theerror += "Please enter resturant address\n"; return false; } return result; } public boolean checkPostal() { boolean result = true; char c [] = postal.toCharArray(); if(c.length < 5){ theerror +="Please enter your postal with atleast 5 digits"; return false; } for(char x:c){ if(!Character.isDigit(x)) { theerror +="Please enter your postal with only digits"; return false; } } if (postal.isEmpty()) { theerror += "Please enter resturant postal\n"; return false; } return result; } public String toString(){ return theerror; } }
package com.tencent.mm.ui.base; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.text.method.DigitsKeyListener; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import com.tencent.mm.bp.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.w.a.h; import com.tencent.mm.w.a.m; import java.util.ArrayList; import java.util.Iterator; public class MMAutoSwitchEditTextView extends LinearLayout { private int idT = 100; private int kCi; private Context mContext; private int mScreenWidth; private int mwe; private int ttN; private String ttO; private ArrayList<MMAutoSwitchEditText> ttP = new ArrayList(); private c ttQ = new c(this, (byte) 0); private a ttR; private b ttS; public void setOnInputFinished(a aVar) { this.ttR = aVar; } public void setOnTextChanged(b bVar) { this.ttS = bVar; } public String getText() { String str = ""; Iterator it = this.ttP.iterator(); while (it.hasNext()) { String str2; MMAutoSwitchEditText mMAutoSwitchEditText = (MMAutoSwitchEditText) it.next(); if (bi.oW(mMAutoSwitchEditText.getText().toString().trim())) { str2 = str; } else { str2 = str + mMAutoSwitchEditText.getText().toString().trim(); } str = str2; } return str; } public MMAutoSwitchEditTextView(Context context, AttributeSet attributeSet) { super(context, attributeSet); this.mContext = context; TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, m.AutoSwitchLayout); this.ttN = obtainStyledAttributes.getInteger(m.AutoSwitchLayout_edit_text_count, 3); this.kCi = obtainStyledAttributes.getInteger(m.AutoSwitchLayout_max_input_count, 4); this.mwe = obtainStyledAttributes.getInteger(m.AutoSwitchLayout_edit_text_inputType, 2); int resourceId = obtainStyledAttributes.getResourceId(m.AutoSwitchLayout_edit_text_digits, 0); if (resourceId != 0) { this.ttO = context.getString(resourceId); } obtainStyledAttributes.recycle(); if (context instanceof Activity) { this.mScreenWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth(); this.idT = ((this.mScreenWidth - 80) - ((this.ttN - 1) * 20)) / this.ttN; } setPadding(a.fromDPToPix(context, 20), 0, a.fromDPToPix(context, 20), 0); crr(); } private void crr() { for (int i = 0; i < this.ttN; i++) { MMAutoSwitchEditText mMAutoSwitchEditText = (MMAutoSwitchEditText) View.inflate(this.mContext, h.auto_switch_edittext, null); mMAutoSwitchEditText.setInputType(this.mwe); if (this.ttO != null && this.ttO.length() > 0) { mMAutoSwitchEditText.setKeyListener(DigitsKeyListener.getInstance(this.ttO)); } mMAutoSwitchEditText.ttI.mIndex = i; mMAutoSwitchEditText.ttI.ttM = this.kCi; mMAutoSwitchEditText.ttI.ttJ = this.ttQ; mMAutoSwitchEditText.ttI.ttK = this.ttQ; mMAutoSwitchEditText.ttI.ttL = this.ttQ; LayoutParams layoutParams = new LinearLayout.LayoutParams(this.idT, -2); if (i > 0) { layoutParams.leftMargin = 20; } else { layoutParams.leftMargin = 0; } layoutParams.weight = 1.0f; mMAutoSwitchEditText.setLayoutParams(layoutParams); this.ttP.add(mMAutoSwitchEditText); addView(mMAutoSwitchEditText); } } }
package com.tencent.mm.plugin.appbrand.jsapi; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable.Creator; import com.tencent.mm.bg.d; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.appbrand.compat.a.a; import com.tencent.mm.plugin.appbrand.config.AppBrandSysConfig; import com.tencent.mm.plugin.appbrand.ipc.MainProcessTask; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.plugin.sport.b.b; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; class JsApiOpenWeRunSetting$OpenWeRunSetting extends MainProcessTask { public static final Creator<JsApiOpenWeRunSetting$OpenWeRunSetting> CREATOR = new 3(); private boolean ccZ = false; private e fFF; private l fFa; private int fFd; private boolean fGw = false; private boolean fGx; public JsApiOpenWeRunSetting$OpenWeRunSetting(e eVar, l lVar, int i, boolean z) { x.i("MicroMsg.JsApiOpenWeRunSetting", "OpenWeRunSetting"); this.fFF = eVar; this.fFa = lVar; this.fFd = i; this.fGx = z; } public JsApiOpenWeRunSetting$OpenWeRunSetting(Parcel parcel) { g(parcel); } public final void aai() { this.fGw = ((b) g.l(b.class)).ei(ad.getContext()); if (!this.fGx || this.fGw) { ahP(); } else { ((a) g.l(a.class)).a(new 1(this)); } } private void ahP() { if (!this.fGx || this.fGw) { this.ccZ = ((b) g.l(b.class)).bFv(); if (this.fGx && this.ccZ) { ((b) g.l(b.class)).bFu(); } } a(); } public final void aaj() { if (this.fGx && !this.fGw) { this.fFa.E(this.fFd, this.fFF.f("fail device not support", null)); ahB(); } else if (this.ccZ) { this.fFa.E(this.fFd, this.fFF.f("ok", null)); ahB(); } else { MMActivity c = e.c(this.fFa); if (c == null) { this.fFa.E(this.fFd, this.fFF.f("fail", null)); ahB(); return; } AppBrandSysConfig appBrandSysConfig = this.fFa.fdO.fcu; if (appBrandSysConfig == null || bi.oW(appBrandSysConfig.bKC)) { this.fFa.E(this.fFd, this.fFF.f("fail", null)); ahB(); return; } Intent intent = new Intent(); intent.putExtra("OpenWeRunSettingName", appBrandSysConfig.bKC); c.geJ = new MMActivity.a() { public final void b(int i, int i2, Intent intent) { if (i != (JsApiOpenWeRunSetting$OpenWeRunSetting.this.hashCode() & 65535)) { JsApiOpenWeRunSetting$OpenWeRunSetting.this.ahB(); } else if (i2 == -1) { JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFa.E(JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFd, JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFF.f("ok", null)); JsApiOpenWeRunSetting$OpenWeRunSetting.this.ahB(); } else if (i2 == 0) { JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFa.E(JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFd, JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFF.f("cancel", null)); JsApiOpenWeRunSetting$OpenWeRunSetting.this.ahB(); } else { JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFa.E(JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFd, JsApiOpenWeRunSetting$OpenWeRunSetting.this.fFF.f("fail", null)); JsApiOpenWeRunSetting$OpenWeRunSetting.this.ahB(); } } }; d.a(c, "appbrand", ".ui.AppBrandOpenWeRunSettingUI", intent, hashCode() & 65535, false); ahB(); } } public final void g(Parcel parcel) { boolean z; boolean z2 = true; if (parcel.readByte() != (byte) 0) { z = true; } else { z = false; } this.fGw = z; if (parcel.readByte() != (byte) 0) { z = true; } else { z = false; } this.ccZ = z; if (parcel.readByte() == (byte) 0) { z2 = false; } this.fGx = z2; } public void writeToParcel(Parcel parcel, int i) { byte b; byte b2 = (byte) 1; if (this.fGw) { b = (byte) 1; } else { b = (byte) 0; } parcel.writeByte(b); if (this.ccZ) { b = (byte) 1; } else { b = (byte) 0; } parcel.writeByte(b); if (!this.fGx) { b2 = (byte) 0; } parcel.writeByte(b2); } }
//import java.util.Arrays; // //public class Main { // public static void main(String[] args) { // //Scanner sc = new Scanner(System.in); // // String str = sc.next(); // String str = "2(2(a))"; // // char[] s = str.toCharArray(); // StringBuilder sb = new StringBuilder(); // int i = 0; // while (i < s.length){ // if (i < s.length && s[i] <= '9' && s[i] >= '0'){ //碰到数字,先记录数字 // int numStart = i; //含头不含尾 // i++; // while (i < s.length && s[i] <= '9' && s[i] >= '0'){ // i++; // } // int numEnd = i; // int num = Integer.valueOf(str.substring(numStart,numEnd)); // //找到数字后的括号中的内容 // int count = 0;//嵌套数 // numStart = i; // if (i < s.length && s[i] == '(' || s[i] == '[' || s[i] == '{'){ // count ++; // i++; // } // while (count > 0){ // if (i < s.length && s[i] == '(' || s[i] == '[' || s[i] == '{'){ // count ++; // }else if(i < s.length && s[i] == ')' || s[i] == ']' || s[i] == '}'){ // count--; // } // i++; // } // numEnd = i;//前闭后开 // sb.append(digui(num,numStart + 1,numEnd - 2,s)); // }else if ((s[i] <= 'z' && s[i] >= 'a') || (s[i] <= 'Z' && s[i] >= 'A')){ // sb.append(s[i]); // i++; // } // i++; // } // char[] ans = sb.toString().toCharArray(); // Arrays.sort(ans); // System.out.print(String.valueOf(ans)); // } // // public static String digui(int n,int start,int end,char[] s){ // String str = s.toString(); // StringBuilder sb = new StringBuilder(); // int i = start; // while (i <= end){ // if (i < s.length && s[i] <= '9' && s[i] >= '0'){ //碰到数字,先记录数字 // int numStart = i; //含头不含尾 // i++; // while (i < s.length && s[i
package com.voksel.electric.pc.domain.entity; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="sys_menu") public class Menu implements Serializable { private static final long serialVersionUID = 5860342063567874062L; @Id @Column(name="menu_id") private String menuId; @Column(name="name") private String menuName; @OneToOne() @JoinColumn(name = "form_id") private Form form; @Column(name="parent_id") @JoinColumn(name="parent_id",referencedColumnName="menu_id") private Menu parent; @Column(name="sequence") private Integer sequence; @Column(name="param") private String parameter; public String getMenuId() { return menuId; } public void setMenuId(String menuId) { this.menuId = menuId; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public Form getForm() { return form; } public void setForm(Form form) { this.form = form; } public Menu getParent() { return parent; } public void setParent(Menu parent) { this.parent = parent; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public String getParameter() { return parameter; } public void setParameter(String parameter) { this.parameter = parameter; } }
package Modifier; public class location extends employee { public static void main(String[] args) { location obj = new location(); obj.methodDefault(); obj.methodPublic(); obj.methodProtected(); } }
package com.example.magdam.handshake; /** * Created by Magdalena on 2016-06-27. */ public class User { int id; String name; String surname; String displayName; String googleId; User(int id, String name, String surname, String displayName) { this.id=id; this.name=name; this.surname=surname; this.displayName=displayName; } public void setGoogleId(String id){ this.googleId=id; } @Override public String toString() { return this.name; } }
/* * 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 chess.pkg2; import java.awt.Color; /** * * @author kha */ public class NavFrame extends javax.swing.JFrame { protected char[] pieceCoordinate = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'}; private long minTimeBlack = 1000000; private long maxTimeBlack = 0; private long sumTimeBlack = 0; private int noMoveBlack = 0; private long avrTimeBlack; private long minTimeWhite = 1000000; private long maxTimeWhite = 0; private long sumTimeWhite = 0; private int noMoveWhite = 0; private long avrTimeWhite; public void showInfor2(String piece, int src, int des, int alliance, long time) { String s = String.format("%-20s%-10s%-6s%-6s\n", exchange(piece, alliance), convert(src), convert(des), time * 1.0 / 1000); // jTextArea1.append("\n" +exchange(piece,alliance) +"\t"+ src+"\t" + des); if (alliance == 1) { if (time <= minTimeBlack) { minTimeBlack = time; } if (time >= maxTimeBlack) { maxTimeBlack = time; } sumTimeBlack += time; noMoveBlack += 1; avrTimeBlack = sumTimeBlack / noMoveBlack; bmit.setText(""); String d = "" + minTimeBlack * 1.0 / 1000; bmit.setText(d); bmat.setText(""); d = "" + maxTimeBlack * 1.0 / 1000; bmat.setText(d); bat.setText(""); d = "" + avrTimeBlack * 1.0 / 1000; bat.setText(d); } if (alliance == 0) { if (time <= minTimeWhite) { minTimeWhite = time; } if (time >= maxTimeWhite) { maxTimeWhite = time; } sumTimeWhite += time; noMoveWhite += 1; avrTimeWhite = sumTimeWhite / noMoveWhite; wmit.setText(""); String d = "" + minTimeWhite * 1.0 / 1000; wmit.setText(d); wmat.setText(""); d = "" + maxTimeWhite * 1.0 / 1000; wmat.setText(d); wat.setText(""); d = "" + avrTimeWhite * 1.0 / 1000; wat.setText(d); } jTextArea1.insert(s, 52); } String convert(int number) { String s = ""; return s + pieceCoordinate[number % 8] + (8 - number / 8); } private String exchange(String name, int alliance) { String pieceName = ""; if (alliance == 0) { switch (name) { case "K": pieceName = "WHITE KING "; break; case "R": pieceName = "WHITE ROOK "; break; case "P": pieceName = "WHITE PAWN "; break; case "N": pieceName = "WHITE KNIGHT"; break; case "Q": pieceName = "WHITE QUEEN "; break; case "B": pieceName = "WHITE BISHOP"; break; } } if (alliance == 1) { switch (name) { case "K": pieceName = "BLACK KING "; break; case "R": pieceName = "BLACK ROOK "; break; case "P": pieceName = "BLACK PAWN "; break; case "N": pieceName = "BLACK KNIGHT"; break; case "Q": pieceName = "BLACK QUEEN "; break; case "B": pieceName = "BLACK BISHOP"; break; } } return pieceName; } // public static ImagePanel ip = new ImagePanel(); // public static void rePaint(){ // // } /** * Creates new form NavFrame * */ public NavFrame() { initComponents(); this.setLocation(850, 100); this.setVisible(true); this.setResizable(false); String s = String.format("%-28s%-10s%-7s%-5s\n", "Piece", "From", "To", "Time"); jTextArea1.setText(s); StringBuffer s1 = new StringBuffer(); this.setLayout(null); this.jTextArea1.setVisible(true); if (Table.mode == 1) { jLabel3.setText("Human VS Computer"); wl.setText("Human"); switch (Table.blacklevel) { case 2: bl.setText("2"); break; case 3: bl.setText("3"); break; case 4: bl.setText("4"); break; case 5: bl.setText("5"); break; case 6: bl.setText("6"); break; } } if (Table.mode == 0) { jLabel3.setText("Computer VS Computer"); switch (Table.blacklevel) { case 2: bl.setText("2"); break; case 3: bl.setText("3"); break; case 4: bl.setText("4"); break; case 5: bl.setText("5"); break; case 6: bl.setText("6"); break; } switch (Table.whitelevel) { case 2: wl.setText("2"); break; case 3: wl.setText("3"); break; case 4: wl.setText("4"); break; case 5: wl.setText("5"); break; case 6: wl.setText("6"); break; } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); bmit = new javax.swing.JLabel(); wmat = new javax.swing.JLabel(); bmat = new javax.swing.JLabel(); bat = new javax.swing.JLabel(); wmit = new javax.swing.JLabel(); wat = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); bl = new javax.swing.JLabel(); wl = new javax.swing.JLabel(); jLabel1.setText("jLabel1"); jLabel8.setText("jLabel8"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(290, 500)); jButton1.setText("Undo"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("New Game"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Redo"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jTextArea1.setEditable(false); jTextArea1.setColumns(15); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jLabel2.setText("MODE : "); jLabel3.setText("jLabel3"); jLabel4.setText("MinTime"); jLabel5.setText("MaxTime"); jLabel6.setText("AvrTime"); jLabel7.setText("Black :"); jLabel9.setText("White : "); bmit.setText("0"); wmat.setText("0"); bmat.setText("0"); bat.setText("0"); wmit.setText("0"); wat.setText("0"); jLabel10.setText("Level"); bl.setText("jLabel11"); wl.setText("jLabel12"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addGap(24, 24, 24)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(bl, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(wl))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(wmit, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bmit, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bmat, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(wmat, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bat, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(wat, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6) .addGap(22, 22, 22)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jLabel10)) .addGap(2, 2, 2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(bmit) .addComponent(bmat) .addComponent(bat) .addComponent(bl)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(wl)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(wat) .addComponent(wmat) .addComponent(wmit))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new MainFrame().setVisible(true); this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed MainFrame.table.undoTable(); MainFrame.table.validate(); MainFrame.table.repaint(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed MainFrame.table.redoTable(); MainFrame.table.validate(); MainFrame.table.repaint(); }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NavFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NavFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NavFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NavFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NavFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bat; private javax.swing.JLabel bl; private javax.swing.JLabel bmat; private javax.swing.JLabel bmit; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JLabel wat; private javax.swing.JLabel wl; private javax.swing.JLabel wmat; private javax.swing.JLabel wmit; // End of variables declaration//GEN-END:variables private void setLocale(int i, int i0) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
public class Dealership { private double price; private String brand; private String type; private String licensePlate; public Dealership(double p, String b, String t, String l) { price = p; brand = b; type = t; licensePlate = l; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } }
package com.van.security.service; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Iterator; @Service public class MyAccessDecisionManager implements AccessDecisionManager { private static Logger log = LogManager.getLogger(MyAccessDecisionManager.class); //decide 方法是判定是否拥有权限的决策方法, //authentication 是MyUserDetailsService中循环添加到 GrantedAuthority 对象中的权限信息集合. //object 包含客户端发起的请求的requset信息,可转换为 HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); //configAttributes 为MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法返回的结果,此方法是为了判定用户请求的url 是否在资源表中,如果在资源表中,则返回给 decide 方法,用来判定用户是否有此权限 @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (configAttributes == null ||configAttributes.size() == 0){ //说明该资源没有分配给角色, 这里不允许访问 throw new AccessDeniedException("暂无权限访问该资源!"); } ConfigAttribute c; String needRole; //遍历当前访问的资源需要的角色 for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext();){ c = iter.next(); needRole = c.getAttribute(); //遍历当前用户所拥有的角色 for(GrantedAuthority authority : authentication.getAuthorities()){ //管理员则直接放行 if("ROLE_ADMIN".equals(authority.getAuthority())){ return; } //匹配到则放行 if(needRole.trim().equals(authority.getAuthority())){ return; } } } throw new AccessDeniedException("您无权限访问此资源!"); } @Override public boolean supports(ConfigAttribute configAttribute) { return true; } @Override public boolean supports(Class<?> aClass) { return true; } }
package com.lc.exstreetseller.activity; import android.os.Bundle; import android.os.Handler; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.EditText; import com.lc.exstreetseller.R; import com.lc.exstreetseller.adapter.GoodsManageAdapter; import com.lc.exstreetseller.base.BaseActivity; import com.lc.exstreetseller.bean.GoodsManageBean; import com.xjl.elibrary.view.irecyclerview.IRecyclerView; import com.xjl.elibrary.view.irecyclerview.OnLoadMoreListener; import com.xjl.elibrary.view.irecyclerview.OnRefreshListener; import com.xjl.elibrary.view.irecyclerview.widget.LoadMoreFooterView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; public class GoodsSearchActivity extends BaseActivity { @BindView(R.id.et_goods_search_content) EditText contentEt; @BindView(R.id.rv_goods_search) IRecyclerView rv; private List<GoodsManageBean> list; private GoodsManageAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goods_search); initView(); } private void initView() { setETitle("商品搜索"); list = new ArrayList<>(); adapter = new GoodsManageAdapter(this, list); rv.setAdapter(adapter); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setRefreshEnabled(true); rv.setLoadMoreEnabled(true); rv.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { rv.setRefreshing(false); } }, 1000); } }); rv.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore(View view) { new Handler().postDelayed(new Runnable() { @Override public void run() { rv.setLoadMoreStatus(LoadMoreFooterView.Status.GONE); } }, 1000); } }); } @OnClick(R.id.tv_goods_search_search) public void click(View v) { loadData(); } private void loadData() { for (int i = 0; i < 10; i++) { list.add(new GoodsManageBean("item:" + i)); } adapter.notifyDataSetChanged(); } }
/* * 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 PL.UpdateBorrowingCardInfo; import BLL.UpdateBorrowingCardInfoController; import DAL.CardInfo; import DAL.User; import PL.AlertMessage; import PL.Login.LoginForm; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; /** * FXML Controller class * * @author tunguyen */ public class CardDetailUpdateListener { UpdateBorrowingCardInfoController controller = new UpdateBorrowingCardInfoController(); ArrayList<CardInfo> card_list; private CardInfo cardInfo; private Date expiredDate; private User user; @FXML private Label welcomeLabel; @FXML private Label cardNumberField; @FXML private TextField userNameField; @FXML private TextField nameField; @FXML private TextField borrowerIdField; @FXML private DatePicker dateField; public void setUser(User user) { this.user = user; } public void setWelcomeLabel(String name) { welcomeLabel.setText("Welcome, " + name); } public void setCardNumber(int cardId) { cardNumberField.setText(Integer.toString(cardId)); } public void setUserName(String userName) { userNameField.setText(userName); userNameField.setEditable(false); } public void setName(String name) { nameField.setText(name); nameField.setEditable(false); } public void setBorrowerId(int borrowerId) { if (borrowerId != 0) { borrowerIdField.setText(Integer.toString(borrowerId)); } else { borrowerIdField.setText("N/A"); } borrowerIdField.setEditable(false); } public void setExpiryDate(LocalDate expiryDate) { if (expiryDate != null) { dateField.setValue(expiryDate); } else { dateField.setDisable(true); } } /** * What to do when click Logout * @param event */ @FXML public void handleLogoutButton(ActionEvent event) { Node source = (Node) event.getSource(); Stage primaryStage = (Stage) source.getScene().getWindow(); LoginForm form = new LoginForm(); form.start(primaryStage, "You have been logged out"); } /** * What to do when change Date in DatePicker * @param event */ @FXML public void handleDateField(ActionEvent event) { LocalDate localDate = dateField.getValue(); Instant instant = Instant.from(localDate.atStartOfDay(ZoneId.systemDefault())); expiredDate = Date.from(instant); } /** * What to do when click Update * @param event */ @FXML public void handleUpdateButton(ActionEvent event) { Node source = (Node) event.getSource(); CardInfo oneCard = controller.getSelectedCardInfo(Integer.parseInt(cardNumberField.getText())); if (oneCard != null) { if (controller.updateSelectedCardInfo(oneCard, expiredDate)) { AlertMessage alert = new AlertMessage(); alert.setMessage("Update successful"); alert.setHeader(null); alert.execute(Alert.AlertType.INFORMATION); } else { AlertMessage alert = new AlertMessage(); alert.setMessage("Error update"); alert.setHeader(null); alert.execute(Alert.AlertType.ERROR); } } } /** * What to do when click Cancel * @param event */ @FXML public void handleCancelButton(ActionEvent event) { Node source = (Node) event.getSource(); Stage stage = (Stage) source.getScene().getWindow(); UpdateBorrowingCardInfoForm form = new UpdateBorrowingCardInfoForm(); form.start(stage, user); } }
package com.teamdev.calculator; import com.teamdev.fsm.AbstractFiniteStateMachine; import com.teamdev.calculator.parser.ExpressionParserFactory; public class MathExpressionCalculator extends AbstractFiniteStateMachine< MathExpressionReader, EvaluationStack, CalculationState, EvaluationCommand, ExpressionParser, CalculationMatrix, CalculationError, Double> implements Calculator { final private ExpressionParserFactory parserFactory = new ExpressionParserFactory(); final private CalculationMatrix matrix = new CalculationMatrix(); @Override public double calculate(String expression) throws CalculationError { return run(new MathExpressionReader(expression), new EvaluationStack()); } @Override protected Double prepareResult(EvaluationStack context) { return context.getStackNode().getOperandStack().pop(); } @Override protected void deadlock(MathExpressionReader context) throws CalculationError { throw new CalculationError("", -1); } @Override protected ExpressionParser getStateAcceptor(CalculationState state) { return parserFactory.getParser(state); } @Override protected CalculationMatrix getTransitionMatrix() { return matrix; } public static void main(String[] args) throws Exception { final MathExpressionCalculator calculator = new MathExpressionCalculator(); final double result = calculator.calculate("1 + 2 * 3 ^ 4"); System.out.println("result = " + result); } }
package com.seemoreinteractive.virtualshot.utils; public enum LegalPosition { TOP_CENTER("TOP_CENTER"), TOP_LEFT("TOP_LEFT"), TOP_RIGHT("TOP_RIGHT"), BOTTOM_CENTER("BOTTOM_CENTER"), BOTTOM_LEFT("BOTTOM_LEFT"), BOTTOM_RIGHT("BOTTOM_RIGHT"); private final String value; LegalPosition(String value) { this.value = value; } public static LegalPosition fromValue(String value) { if (value != null) { for (LegalPosition legalPosition : values()) { if (legalPosition.value.equals(value)) { return legalPosition; } } } return null; } @Override public String toString(){ return this.value; } }
package itri.io.emulator.common; import java.io.File; import java.util.List; import javax.naming.InvalidNameException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Configuration { private List<Element> properties; @SuppressWarnings("unchecked") public Configuration(String path) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); Element root = document.getRootElement(); properties = root.elements("property"); } public String get(String name) throws InvalidNameException { Element element = searchPropertyName(name); return element.element("value").getText(); } public String[] getStrings(String name) throws InvalidNameException { Element element = searchPropertyName(name); String[] values = element.element("value").getText().split(","); return values; } public int getInt(String name, int defaultValue) throws InvalidNameException { Element element = searchPropertyName(name); String strValue = element.element("value").getText(); return (strValue == null || strValue.length() == 0) ? defaultValue : Integer.valueOf(strValue); } private Element searchPropertyName(String name) throws InvalidNameException { for (Element element : properties) { if (element.element("name").getText().equals(name)) { return element; } } throw new InvalidNameException("Can't find the property with name: " + name + ". Please check your spell in configuration file."); } }
package com.swrdfish.unshop.admin; import com.swrdfish.unshop.database.Model; public class BasicAdminResource implements AdminResource { private final Class<? extends Model> modelClass; private final AdminConfig[] config; BasicAdminResource(Class<? extends Model> modelClass, AdminConfig ...config) { this.modelClass = modelClass; this.config = config; } public AdminConfig[] getConfig() { return config; } public Class<? extends Model> getModelClass() { return modelClass; } }
import java.util.*; //Time complexity is O(E+V) public class UnDirectedGraph{ int v ; List<List<Integer>> graph ; public UnDirectedGraph(int v){ this.v = v; graph = new ArrayList(v); for(int i =0; i<v; i++){ List<Integer> adj = new LinkedList(); graph.add(adj); } } public void addEdge(int u, int v){ //Undirected graps so add edges for both directions graph.get(u).add(v); graph.get(v).add(u); } public boolean isCycleExistUtils(int i,boolean [] visited,int parent){ visited[i] = true; for(int adj:graph.get(i)){ if(!visited[adj] ){ if(isCycleExistUtils(adj,visited,i)){ return true; } }else if(adj != parent){ return true; } } return false; } public boolean isCycleExist(){ boolean [] visited = new boolean[v]; for(int j = 0; j < v; j++){ visited[j] = false; } int parent = -1; for(int i = 0; i< v; i++ ){ if(!visited[i]){ if(isCycleExistUtils(i,visited,parent)){ return true; } } } return false; } public static void main(String args[]){ UnDirectedGraph udg = new UnDirectedGraph(4); udg.addEdge(0,1); udg.addEdge(1,2); udg.addEdge(0,2); udg.addEdge(2,3); if(udg.isCycleExist()){ System.out.println("Cycle exists"); }else{ System.out.println("Cycle doesn't exist"); } } }
package recursionAndBacktracking; public class DeleteKthNode { static class Node { int data; Node next; protected Node(int data) { this.data = data; next = null; } } public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); Node temp = deleteAt(head, 3); while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } static Node deleteAt(Node node, int k) { if (k < 1) { return node; } if (node == null) { return null; } if (k == 1) { Node temp = node.next; return temp; } node.next = deleteAt(node.next, k - 1); return node; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class FileProcessor { public String inFile=null; private FileInputStream fileInput=null; private BufferedReader bufferedReader=null; private File file = null; public FileProcessor(String inFile){ this.inFile = inFile; } public void openfile(){ try { File file = new File(inFile); if(file.exists()){ fileInput = new FileInputStream(file); bufferedReader = new BufferedReader(new InputStreamReader(fileInput));} else{ //System.out.println(file + " file does not exist"); } }catch(Exception e){ e.printStackTrace(); } finally{ } } public String readLine(){ String line = null; try{ if(bufferedReader!=null) line = bufferedReader.readLine(); }catch(Exception e){ e.printStackTrace(); return line; } finally{ } return line; } public void close(){ try { bufferedReader.close(); }catch (IOException e) { e.printStackTrace(); } finally{ } } }
package org.tibetjungle.misc.trywithresource; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class TryWithResource { public static void main(String[] args) { try( FileOutputStream fos = new FileOutputStream( "test.txt");){ fos.write( "test".getBytes() ); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package com.game.main; import java.awt.*; import java.awt.image.BufferedImage; public class OrbBullet extends GameObject{ private BufferedImage orbBullet; private double diameter; private Handler handler; public static double hitX, hitY, hitR, hitC, currentX, currentY; // the coordinates in pixels and row and col public static BufferedImage hitImage, currentImage; public static GameObject hitOrb, currentOrbBullet; public OrbBullet(double x, double y, double diameter, BufferedImage orbBullet, ID id, Handler handler) { super(x, y, id); super.image = orbBullet; this.diameter = diameter; this.orbBullet = orbBullet; this.handler = handler; } @Override public void tick() { x += velX; y += velY; if(x > Game.WIDTH - diameter || x < 0){ velX *= -1; } if(y > Game.HEIGHT){ handler.object.remove(this); handler.loadOrbBullet(); } if(y < 0){ velY *= - 1; } if(collision()){ handler.processCollision(); } } @Override public void render(Graphics g) { g.drawImage(orbBullet, (int)x, (int)y, (int)this.diameter, (int)this.diameter, null); } private Boolean collision(){ for(int i = 0; i < handler.grid.size(); i++){ for(int j = 0; j < handler.row.size(); j++) { Orb temp = handler.grid.get(i).get(j); // don't check for collisions with the "empty" place holder if(temp.getImage() != Assets.empty) { // collision detection and information retrieval if (getBounds().intersects(temp.getBounds())) { hitX = temp.getX(); hitY = temp.getY(); hitR = handler.getR(hitY); hitC = handler.getC(hitX); currentX = this.getX(); currentY = this.getY(); currentImage = this.getImage(); hitImage = temp.getImage(); currentOrbBullet = this; hitOrb = temp; handler.object.remove(this); handler.loadOrbBullet(); return true; } } } } return false; } @Override public Rectangle getBounds() { return new Rectangle((int)this.x, (int)this.y, (int)this.diameter, (int)this.diameter); } }
package com.ncaa.java.basketball; import java.util.ArrayList; import java.util.List; public class Round { private List<Game> games; private List<Team> winners; public Round() { } public Round(List<Team> teams) { games = new ArrayList<Game>(); winners = new ArrayList<Team>(); for (int x=0; x < (teams.size()/2); x++) { Game game = new Game(teams.get(x),teams.get(teams.size()-x-1)); games.add(game); winners.add(game.getWinner()); } } public List<Game> getGames() { return games; } public void setGames(List<Game> games) { this.games = games; } public List<Team> getWinners() { return winners; } public void setWinners(List<Team> winners) { this.winners = winners; } @Override public String toString() { return "Round{" + "games=" + games.size() + "}"; } }
/* * Copyright 2008 Kjetil Valstadsve * * 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 vanadis.osgi; enum CompareOperator { EQUAL("=") { @Override protected boolean match(int result) { return result == 0; }}, APPROX("~=") { @Override protected boolean match(int result) { return result == 0; }}, GREATER(">=") { @Override protected boolean match(int result) { return result > 0; }}, LESS("<=") { @Override protected boolean match(int result) { return result < 0; }}; private final String repr; CompareOperator(String repr) { this.repr = repr; } public String repr() { return repr; } public boolean compares(Object c1, Object c2) { if (c1.getClass().equals(c2.getClass()) && c1 instanceof Comparable<?>) { return compare(c1, c2); } else { throw new IllegalStateException(this + " could not compare " + c1 + " to " + c2); } } @SuppressWarnings({ "RawUseOfParameterizedType", "unchecked" }) private boolean compare(Object c1, Object c2) { Class<? extends Comparable> type = c1.getClass().asSubclass(Comparable.class); return match(type.cast(c1).compareTo(type.cast(c2))); } protected abstract boolean match(int result); }
package identity; import abstraction.Cargo; import abstraction.Vehicle; import inheritance.Bicycle; import inheritance.BicycleType; public class Main { public static void main(String[] args) { Bicycle b1 = new Bicycle(0, -1, 1, Cargo.PASSENGERS, "Bt'win", BicycleType.MOUNTAIN_BIKE); Bicycle b2 = new Bicycle(0, -1, 1, Cargo.PASSENGERS, "Bt'win", BicycleType.MOUNTAIN_BIKE); Vehicle veh1 = b1; System.out.println(b1 == b2); // false System.out.println(veh1 == b1); // true System.out.println(veh1 == b2); // false } }
package com.example.myoga.ui.wisdom; import android.app.Application; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import com.example.myoga.VideoRecyclerViewAdapter; import com.example.myoga.models.VideosDataSource; import java.util.ArrayList; public class WatchViewModel extends AndroidViewModel { MutableLiveData<ArrayList<VideosDataSource.Video>> videos; public WatchViewModel(Application application) { super(application); videos = new MutableLiveData<>(); VideosDataSource.loadVideos(VideoRecyclerViewAdapter.RV_TYPE.WATCH, videos, application.getApplicationContext()); } public MutableLiveData<ArrayList<VideosDataSource.Video>> getVideos() { return videos; } }
package io.metadata.filestorage.model.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.time.LocalDateTime; @ApiModel(description = "Object encapsulating the info of every item on the file list") public class FileDTO implements Serializable { public FileDTO() { } public FileDTO(String name, Integer latestVersion, LocalDateTime lastModificationDate) { this.name = name; this.latestVersion = latestVersion; this.lastModificationDate = lastModificationDate; } @ApiModelProperty(value = "Name of the file", example = "test.json") private String name; @ApiModelProperty(value = "Latest version number recorded on system", example = "2") private Integer latestVersion; @ApiModelProperty(value = "Latest time a new version was added on the system", example = "2019-02-02T00:00:00") private LocalDateTime lastModificationDate; @ApiModelProperty(value = "Download link", example = "http://localhost:8080/files/download/test.json?version=2") private String downloadLink; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLatestVersion() { return latestVersion; } public void setLatestVersion(Integer latestVersion) { this.latestVersion = latestVersion; } public String getDownloadLink() { return downloadLink; } public void setDownloadLink(String downloadLink) { this.downloadLink = downloadLink; } public LocalDateTime getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(LocalDateTime lastModificationDate) { this.lastModificationDate = lastModificationDate; } }
package com.lec.ex1_inputStreamOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; //1. stream객체 생성(inputStream,outputStream) 2.읽고쓰기(반복) 3.stream닫기 public class Ex05_fileCopyStep2 { public static void main(String[] args) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream("txtFile\\mamamoo.jpg"); // \만하면 해석하기 시작.기능의미 따라서 \\ 입력 os = new FileOutputStream("txtFile/mamamoo_copy.jpg"); // d:/big/ 출력 int cnt = 0; //뒤 "번 반목문 실행 후 파일 복사 성공"를 위해 변수 선언 byte[] bs = new byte[1024]; //1KB씩 이 배열에 읽어 들이는 목적 !!byte선언 while (true) { ++cnt; //반복문 실행 int readByteCount = is.read(bs); // !!이부분 중요 byte수를 읽어라 if (readByteCount == -1) break; os.write(bs,0,readByteCount); //!!이부분 중요 bs배열에 0번 index부터readByteCount만큼만 파일에 쓰기 } System.out.println(cnt+"번 반목문 실행 후 파일 복사 성공"); } catch (FileNotFoundException e) { System.out.println("파일 이나 폴더 못 찾음" + e.getMessage()); } catch (IOException e) { System.out.println("일고 쓸 때 예외남" + e.getMessage()); } finally { try { if(is!=null) is.close(); if(os!=null) os.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } }// main }// class
package serverframe_thread; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.EOFException; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import server_util.CommDateandTime; import server_util.CommFileClass; import server_util.Pack_util; import server_util.Table_util; import serverframe_servermanage.ServerManagePanel; import util.DataPackage; import util.Global_OnLine; import util.LogFile; import util.UserBean; import util.UserDAO; /**服务器不端接收到客户端信息的线程 * @author lisu * */ public class Server_WaitIo_Thread extends Thread { /** * 对象输入流 */ private ObjectInputStream objectInputStream = null; /** * 对象输出流 */ private ObjectOutputStream objectOutputStream = null; /** * * 要连接的套接字 * */ private Socket socket; /** * 用来开启服务器不端接收到客户端信息的线程的变量 */ private boolean isStop = false; /** * 用户信息 */ private UserBean userBean = null; /** * 选项卡属性_服务管理面板 */ private ServerManagePanel serverManagePanel; /** * 数据包协议 */ private DataPackage dataPackage; public Server_WaitIo_Thread(Socket socket, ServerManagePanel serverManagePanel) { this.socket = socket; this.serverManagePanel = serverManagePanel; try { objectInputStream = new ObjectInputStream(socket.getInputStream()); objectOutputStream = new ObjectOutputStream(socket .getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } public void run() { while (isStop == false) { try { dataPackage = (DataPackage) this.objectInputStream .readObject(); int dataType = dataPackage.getDataType(); // 登录包 if (dataType == DataPackage.Login_Pack) { Map dataMap = dataPackage.getDataMap(); String username = String.valueOf(dataMap.get("username")); String password = String.valueOf(dataMap.get("password")); // 开始解析用户数据,并发送消息反馈包。 int result = UserDAO.isUser(username, password); dataPackage = new DataPackage(); for (int i = 0; i < Global_OnLine.onLineUserList.size(); i++) { Server_WaitIo_Thread serverWaitIoThread = Global_OnLine.onLineUserList .get(i); UserBean userBean = serverWaitIoThread.userBean; if (userBean.getUserId().equals(username)) { result = 2; } } if (result == -1) { dataPackage.setDataType(DataPackage.Error_User); } else if (result == 0) { dataPackage.setDataType(DataPackage.Error_Pwd); isStop=true; } else if (result == 1) { dataPackage.setDataType(DataPackage.Succ_User); } else if (result == 2) { dataPackage.setDataType(DataPackage.UserOnLine); } userBean = UserDAO.getUserBean(username); Map dataMap_1 = dataPackage.getDataMap(); dataMap_1.put("UserBean", userBean); this.objectOutputStream.writeObject(dataPackage); this.objectOutputStream.flush(); // 在线用户 if (result == 1) { Global_OnLine.onLineUserList.add(this); // Global_OnLine.hashMap.put(this.getId(), this); userBean = UserDAO.getUserBean(username); serverManagePanel.getTaPromptInfo().append( CommDateandTime.getDateAndTime() + ": " + "用户" + userBean.getUserName() + "(" + userBean.getUserId() + ")" + "上线了" + "\n"); // 通讯信息提示 LogFile.logInfo("用户" + userBean.getUserName() + "(" + userBean.getUserId() + ")" + "上线了" + "\n"); // 将用户数据发送到客户端 DataPackage dataPackage = new DataPackage(); Map map = new HashMap(); Vector vector = new Vector(); vector.add("所有人"); for (int i = 0; i < Global_OnLine.onLineUserList.size(); i++) { Server_WaitIo_Thread serverWaitIoThread = Global_OnLine.onLineUserList .get(i); UserBean userBean = serverWaitIoThread.userBean; vector.add(userBean.getUserName()+"_"+userBean.getUserId()); } map.put("onLineUserList",vector ); dataPackage.setDataType(DataPackage.OnLineUser); dataPackage.setDataMap(map); // 循环发给所有的Socket(用户) Pack_util.sendAll_pack(dataPackage); // 更新服务端的在线用户列表的表格 Table_util.renew_OnlineTable(serverManagePanel); } } else if (dataType == DataPackage.OffLine_Pack) { // 1: Global_OnLine.onLineUserList.remove(this); serverManagePanel.getTaPromptInfo() .append( CommDateandTime.getDateAndTime() + ": " + "用户" + userBean.getUserName() + "(" + userBean.getUserId() + ")" + "下线了" + "\n"); // 通讯信息提示 LogFile.logInfo("用户" + userBean.getUserName() + "(" + userBean.getUserId() + ")" + "下线了" + "\n"); //System.out.println(Global_OnLine.onLineUserList.size()); // 将用户数据发送到客户端 dataPackage = new DataPackage(); Map map = new HashMap(); Vector vector = new Vector(); vector.add("所有人"); for (int i = 0; i < Global_OnLine.onLineUserList.size(); i++) { Server_WaitIo_Thread serverWaitIoThread = Global_OnLine.onLineUserList .get(i); UserBean userBean = serverWaitIoThread.userBean; vector.add(userBean.getUserName()+"_"+userBean.getUserId()); } map.put("onLineUserList", vector); dataPackage.setDataType(DataPackage.OnLineUser); dataPackage.setDataMap(map); // 循环发给所有的Socket Pack_util.sendAll_pack(dataPackage); // 更新服务端的在线用户列表的表格 Table_util.renew_OnlineTable(serverManagePanel); if (objectOutputStream != null) { objectOutputStream.close(); } if (objectInputStream != null) { objectInputStream.close(); } if (socket != null) { socket.close(); } // 关线程 this.isStop = true; // 群聊包 } else if (dataType == DataPackage.Public_Chat) { Map dataMap = dataPackage.getDataMap(); String message = String.valueOf(dataMap.get("message")); String thisusername = String.valueOf(dataMap .get("thisusername")); // String message_1=dataPackage.getUserBean().getUserId(); Pack_util.send_All(CommDateandTime.getDateAndTime() + "\n" + thisusername + "对所有人说: " + message,userBean); // 私聊包 } else if (dataType == DataPackage.intPrivate_Chat) { Map dataMap = dataPackage.getDataMap(); String message = String.valueOf(dataMap.get("message")); String message_1 = dataPackage.getUserBean().getUserId(); String tostrID = String.valueOf(dataMap.get("tostrID")); String userId = String.valueOf(dataMap.get("userId")); String tousername = String.valueOf(dataMap .get("tousername")); String thisusername = String.valueOf(dataMap .get("thisusername")); Pack_util.send_One(CommDateandTime.getDateAndTime() + "\n" + thisusername + "对你说: " + message, tostrID, userId,userBean); // 修改密码包 } else if (dataType == DataPackage.Alter_Password) { UserBean userBean = dataPackage.getUserBean(); Map dataMap = dataPackage.getDataMap(); String userId = userBean.getUserId(); String oldPassword = String.valueOf(dataMap .get("oldPassword")); String newPassword = String.valueOf(dataMap .get("newPassword")); String affirmPassword = String.valueOf(dataMap .get("affirmPassword")); int result = UserDAO.ispassword(userId, oldPassword); if (result == 0) { dataPackage .setDataType(DataPackage.intInit_Password_Error); } else if (result == 1) { dataPackage .setDataType(DataPackage.intAlter_Password_Success); } this.objectOutputStream.writeObject(dataPackage); this.objectOutputStream.flush(); if (result == 1) { // 更新服务器管理的Table把原来的密码改成新的 Table_util.renew_OnlineTable_newpassword( serverManagePanel, userId, newPassword); // 在文件里修改密码,传入要修改认的ID,和新密码 Table_util.modifypassword(newPassword, userId); } // 更新用户管理的Table Table_util .renew_Table( serverManagePanel.getServerFrame().getUserManagePanel().getTable(), serverManagePanel.getServerFrame().getUserManagePanel().getColumnVector()); } } catch (SocketException e) { Global_OnLine.onLineUserList.remove(this); serverManagePanel.getTaPromptInfo().append( CommDateandTime.getDateAndTime() + ": " + "用户" + userBean.getUserName() + "(" + userBean.getUserId() + ")" + "下线了" + "\n"); // 通讯信息提示 //System.out.println(Global_OnLine.onLineUserList.size()); // 将用户数据发送到客户端 DataPackage dataPackage_1 = new DataPackage(); Map map = new HashMap(); Vector vector = new Vector(); vector.add("所有人"); for (int i = 0; i < Global_OnLine.onLineUserList.size(); i++) { Server_WaitIo_Thread serverWaitIoThread = Global_OnLine.onLineUserList .get(i); UserBean userBean = serverWaitIoThread.userBean; vector.add(userBean.getUserName()+"_"+userBean.getUserId()); } map.put("onLineUserList", vector); dataPackage_1.setDataType(DataPackage.OnLineUser); dataPackage_1.setDataMap(map); // 循环发给所有的Socket Pack_util.sendAll_pack(dataPackage_1); // 更新服务端的在线用户列表的表格 Table_util.renew_OnlineTable(serverManagePanel); try { if (objectOutputStream != null) objectOutputStream.close(); if (objectInputStream != null) objectInputStream.close(); if (socket != null) socket.close(); } catch (IOException e1) { e1.printStackTrace(); } // 关线程 this.isStop = true; } catch (IOException e1) { e1.printStackTrace(); }catch (Exception e) { //e.printStackTrace(); } } } public ObjectInputStream getObjectInputStream() { return objectInputStream; } public void setObjectInputStream(ObjectInputStream objectInputStream) { this.objectInputStream = objectInputStream; } public ObjectOutputStream getObjectOutputStream() { return objectOutputStream; } public void setObjectOutputStream(ObjectOutputStream objectOutputStream) { this.objectOutputStream = objectOutputStream; } public UserBean getUserBean() { return userBean; } public void setUserBean(UserBean userBean) { this.userBean = userBean; } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public boolean isStop() { return isStop; } public void setStop(boolean isStop) { this.isStop = isStop; } public ServerManagePanel getServerManagePanel() { return serverManagePanel; } public void setServerManagePanel(ServerManagePanel serverManagePanel) { this.serverManagePanel = serverManagePanel; } public DataPackage getDataPackage() { return dataPackage; } public void setDataPackage(DataPackage dataPackage) { this.dataPackage = dataPackage; } }
package com.codingblocks.sqlitepractice; import androidx.appcompat.app.AppCompatActivity; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.codingblocks.sqlitepractice.db.TodoTable; import com.codingblocks.sqlitepractice.db.dbHelper; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button btn; EditText et; ListView lv; ArrayList<model> todos = new ArrayList<>(); ArrayAdapter<model> ad; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ad = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, todos); btn = findViewById(R.id.btn); et = findViewById(R.id.et); lv= findViewById(R.id.lv); lv.setAdapter(ad); db = new dbHelper(MainActivity.this).getWritableDatabase(); this.refreshTodoList();//call this function when db is initialized // btn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // String newTodo = et.getText().toString(); // // todos.add(newTodo); // ad.notifyDataSetChanged(); // } // }); setOnClick(btn); } public void setOnClick(View v) { v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { model newTodo = new model(et.getText().toString(), false); TodoTable.insertTodo(db, newTodo); refreshTodoList(); et.setText(""); } }); } private void refreshTodoList() { ArrayList<model> todoList = TodoTable.getAllTodos(db); todos.clear(); todos.addAll(todoList); ad.notifyDataSetChanged(); Log.d("TODOS", todoList.toString()); } }
/** * This classs represents the entity of the playing cube. The number of sides could be defined through the constuctor **/ package com.company; public class Wurfel { private int seiten; public Wurfel(int seiten){ if ((seiten>=6)&&(seiten<=20)) { this.seiten = seiten; } else { throw new IllegalArgumentException("Wurfel darf nur von 6 bis 20 Seiten haben"); } } int wuerfle(){ //Simulates the throw of the cube and returns the number of the side int number = (int)(Math.random()*seiten); if (number==0){ number++; } return number; } }
package edu.lyon1.twitter; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface TweetRepository extends CrudRepository<Tweet,Integer> { List<Tweet> findAllByAuteurOrderByDateDesc(String auteur); List<Tweet> findAllByOrderByDateDesc(); }
package com.tencent.mm.protocal; import com.tencent.mm.protocal.c.g; public class c$aw extends g { public c$aw() { super("downloadImage", "downloadImage", 106, true); } }
package com.example.mynews; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> { Context context; ArrayList<NewsArticle> articles; public NewsAdapter(Context context, ArrayList<NewsArticle> articles) { this.context = context; this.articles = articles; } @NonNull @Override public NewsAdapter.NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.news_item, parent, false); return new NewsViewHolder(view); } @Override public void onBindViewHolder(@NonNull NewsAdapter.NewsViewHolder holder, int position) { holder.tvName.setText(articles.get(position).getTitle()); holder.tvPublised.setText(articles.get(position).getPublishedAt()); holder.tvSourceName.setText(articles.get(position).getSource().getName()); Picasso.get().load(articles.get(position).getUrlToImage()).into(holder.ivNews); } @Override public int getItemCount() { return articles.size(); } public class NewsViewHolder extends RecyclerView.ViewHolder{ TextView tvName; TextView tvPublised; TextView tvSourceName; ImageView ivNews; public NewsViewHolder(@NonNull View itemView) { super(itemView); tvName = itemView.findViewById(R.id.tvName); tvPublised = itemView.findViewById(R.id.tvPublised); tvSourceName = itemView.findViewById(R.id.tvSource); ivNews = itemView.findViewById(R.id.ivNews); } } }
package sergioescalona.myfirsttoolbar.Adapters; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import sergioescalona.myfirsttoolbar.fragments.FirstFragment; import sergioescalona.myfirsttoolbar.fragments.SecondFragment; import sergioescalona.myfirsttoolbar.fragments.ThirdFragment; /** * Created by Sergio on 18/05/2017. */ public class PagerAdapter extends FragmentStatePagerAdapter { private int numberOfTabs; public PagerAdapter(FragmentManager fm, int tabs) { super(fm); this.numberOfTabs=tabs; } @Override public Fragment getItem(int position) { //getItem entra en acción cada vez que cambiamos de Fragment a través de una // posicion dada. switch (position){ //nos permite cambiar entre los tres fragments. case 0: return new FirstFragment(); case 1: return new SecondFragment(); case 2: return new ThirdFragment(); default: return null; } } @Override public int getCount() { //Nos indica el número de tabs que tenemos. return numberOfTabs; } }
package com.rc.portal.vo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rc.app.framework.webapp.model.BaseModel; public class TOrderShipmentExample extends BaseModel{ protected String orderByClause; protected List oredCriteria; public TOrderShipmentExample() { oredCriteria = new ArrayList(); } protected TOrderShipmentExample(TOrderShipmentExample example) { this.orderByClause = example.orderByClause; this.oredCriteria = example.oredCriteria; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); } public static class Criteria { protected List criteriaWithoutValue; protected List criteriaWithSingleValue; protected List criteriaWithListValue; protected List criteriaWithBetweenValue; protected Criteria() { super(); criteriaWithoutValue = new ArrayList(); criteriaWithSingleValue = new ArrayList(); criteriaWithListValue = new ArrayList(); criteriaWithBetweenValue = new ArrayList(); } public boolean isValid() { return criteriaWithoutValue.size() > 0 || criteriaWithSingleValue.size() > 0 || criteriaWithListValue.size() > 0 || criteriaWithBetweenValue.size() > 0; } public List getCriteriaWithoutValue() { return criteriaWithoutValue; } public List getCriteriaWithSingleValue() { return criteriaWithSingleValue; } public List getCriteriaWithListValue() { return criteriaWithListValue; } public List getCriteriaWithBetweenValue() { return criteriaWithBetweenValue; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteriaWithoutValue.add(condition); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } Map map = new HashMap(); map.put("condition", condition); map.put("value", value); criteriaWithSingleValue.add(map); } protected void addCriterion(String condition, List values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } Map map = new HashMap(); map.put("condition", condition); map.put("values", values); criteriaWithListValue.add(map); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } List list = new ArrayList(); list.add(value1); list.add(value2); Map map = new HashMap(); map.put("condition", condition); map.put("values", list); criteriaWithBetweenValue.add(map); } public Criteria andIdIsNull() { addCriterion("id is null"); return this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return this; } public Criteria andIdIn(List values) { addCriterion("id in", values, "id"); return this; } public Criteria andIdNotIn(List values) { addCriterion("id not in", values, "id"); return this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return this; } public Criteria andLogisticsNoIsNull() { addCriterion("logistics_no is null"); return this; } public Criteria andLogisticsNoIsNotNull() { addCriterion("logistics_no is not null"); return this; } public Criteria andLogisticsNoEqualTo(String value) { addCriterion("logistics_no =", value, "logisticsNo"); return this; } public Criteria andLogisticsNoNotEqualTo(String value) { addCriterion("logistics_no <>", value, "logisticsNo"); return this; } public Criteria andLogisticsNoGreaterThan(String value) { addCriterion("logistics_no >", value, "logisticsNo"); return this; } public Criteria andLogisticsNoGreaterThanOrEqualTo(String value) { addCriterion("logistics_no >=", value, "logisticsNo"); return this; } public Criteria andLogisticsNoLessThan(String value) { addCriterion("logistics_no <", value, "logisticsNo"); return this; } public Criteria andLogisticsNoLessThanOrEqualTo(String value) { addCriterion("logistics_no <=", value, "logisticsNo"); return this; } public Criteria andLogisticsNoLike(String value) { addCriterion("logistics_no like", value, "logisticsNo"); return this; } public Criteria andLogisticsNoNotLike(String value) { addCriterion("logistics_no not like", value, "logisticsNo"); return this; } public Criteria andLogisticsNoIn(List values) { addCriterion("logistics_no in", values, "logisticsNo"); return this; } public Criteria andLogisticsNoNotIn(List values) { addCriterion("logistics_no not in", values, "logisticsNo"); return this; } public Criteria andLogisticsNoBetween(String value1, String value2) { addCriterion("logistics_no between", value1, value2, "logisticsNo"); return this; } public Criteria andLogisticsNoNotBetween(String value1, String value2) { addCriterion("logistics_no not between", value1, value2, "logisticsNo"); return this; } public Criteria andLogisticsNameIsNull() { addCriterion("logistics_name is null"); return this; } public Criteria andLogisticsNameIsNotNull() { addCriterion("logistics_name is not null"); return this; } public Criteria andLogisticsNameEqualTo(String value) { addCriterion("logistics_name =", value, "logisticsName"); return this; } public Criteria andLogisticsNameNotEqualTo(String value) { addCriterion("logistics_name <>", value, "logisticsName"); return this; } public Criteria andLogisticsNameGreaterThan(String value) { addCriterion("logistics_name >", value, "logisticsName"); return this; } public Criteria andLogisticsNameGreaterThanOrEqualTo(String value) { addCriterion("logistics_name >=", value, "logisticsName"); return this; } public Criteria andLogisticsNameLessThan(String value) { addCriterion("logistics_name <", value, "logisticsName"); return this; } public Criteria andLogisticsNameLessThanOrEqualTo(String value) { addCriterion("logistics_name <=", value, "logisticsName"); return this; } public Criteria andLogisticsNameLike(String value) { addCriterion("logistics_name like", value, "logisticsName"); return this; } public Criteria andLogisticsNameNotLike(String value) { addCriterion("logistics_name not like", value, "logisticsName"); return this; } public Criteria andLogisticsNameIn(List values) { addCriterion("logistics_name in", values, "logisticsName"); return this; } public Criteria andLogisticsNameNotIn(List values) { addCriterion("logistics_name not in", values, "logisticsName"); return this; } public Criteria andLogisticsNameBetween(String value1, String value2) { addCriterion("logistics_name between", value1, value2, "logisticsName"); return this; } public Criteria andLogisticsNameNotBetween(String value1, String value2) { addCriterion("logistics_name not between", value1, value2, "logisticsName"); return this; } public Criteria andLogisticsPositionIsNull() { addCriterion("logistics_position is null"); return this; } public Criteria andLogisticsPositionIsNotNull() { addCriterion("logistics_position is not null"); return this; } public Criteria andLogisticsPositionEqualTo(String value) { addCriterion("logistics_position =", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionNotEqualTo(String value) { addCriterion("logistics_position <>", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionGreaterThan(String value) { addCriterion("logistics_position >", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionGreaterThanOrEqualTo(String value) { addCriterion("logistics_position >=", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionLessThan(String value) { addCriterion("logistics_position <", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionLessThanOrEqualTo(String value) { addCriterion("logistics_position <=", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionLike(String value) { addCriterion("logistics_position like", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionNotLike(String value) { addCriterion("logistics_position not like", value, "logisticsPosition"); return this; } public Criteria andLogisticsPositionIn(List values) { addCriterion("logistics_position in", values, "logisticsPosition"); return this; } public Criteria andLogisticsPositionNotIn(List values) { addCriterion("logistics_position not in", values, "logisticsPosition"); return this; } public Criteria andLogisticsPositionBetween(String value1, String value2) { addCriterion("logistics_position between", value1, value2, "logisticsPosition"); return this; } public Criteria andLogisticsPositionNotBetween(String value1, String value2) { addCriterion("logistics_position not between", value1, value2, "logisticsPosition"); return this; } public Criteria andShipmentDtIsNull() { addCriterion("shipment_dt is null"); return this; } public Criteria andShipmentDtIsNotNull() { addCriterion("shipment_dt is not null"); return this; } public Criteria andShipmentDtEqualTo(Date value) { addCriterion("shipment_dt =", value, "shipmentDt"); return this; } public Criteria andShipmentDtNotEqualTo(Date value) { addCriterion("shipment_dt <>", value, "shipmentDt"); return this; } public Criteria andShipmentDtGreaterThan(Date value) { addCriterion("shipment_dt >", value, "shipmentDt"); return this; } public Criteria andShipmentDtGreaterThanOrEqualTo(Date value) { addCriterion("shipment_dt >=", value, "shipmentDt"); return this; } public Criteria andShipmentDtLessThan(Date value) { addCriterion("shipment_dt <", value, "shipmentDt"); return this; } public Criteria andShipmentDtLessThanOrEqualTo(Date value) { addCriterion("shipment_dt <=", value, "shipmentDt"); return this; } public Criteria andShipmentDtIn(List values) { addCriterion("shipment_dt in", values, "shipmentDt"); return this; } public Criteria andShipmentDtNotIn(List values) { addCriterion("shipment_dt not in", values, "shipmentDt"); return this; } public Criteria andShipmentDtBetween(Date value1, Date value2) { addCriterion("shipment_dt between", value1, value2, "shipmentDt"); return this; } public Criteria andShipmentDtNotBetween(Date value1, Date value2) { addCriterion("shipment_dt not between", value1, value2, "shipmentDt"); return this; } public Criteria andOrderIdIsNull() { addCriterion("order_id is null"); return this; } public Criteria andOrderIdIsNotNull() { addCriterion("order_id is not null"); return this; } public Criteria andOrderIdEqualTo(Long value) { addCriterion("order_id =", value, "orderId"); return this; } public Criteria andOrderIdNotEqualTo(Long value) { addCriterion("order_id <>", value, "orderId"); return this; } public Criteria andOrderIdGreaterThan(Long value) { addCriterion("order_id >", value, "orderId"); return this; } public Criteria andOrderIdGreaterThanOrEqualTo(Long value) { addCriterion("order_id >=", value, "orderId"); return this; } public Criteria andOrderIdLessThan(Long value) { addCriterion("order_id <", value, "orderId"); return this; } public Criteria andOrderIdLessThanOrEqualTo(Long value) { addCriterion("order_id <=", value, "orderId"); return this; } public Criteria andOrderIdIn(List values) { addCriterion("order_id in", values, "orderId"); return this; } public Criteria andOrderIdNotIn(List values) { addCriterion("order_id not in", values, "orderId"); return this; } public Criteria andOrderIdBetween(Long value1, Long value2) { addCriterion("order_id between", value1, value2, "orderId"); return this; } public Criteria andOrderIdNotBetween(Long value1, Long value2) { addCriterion("order_id not between", value1, value2, "orderId"); return this; } public Criteria andStateIsNull() { addCriterion("state is null"); return this; } public Criteria andStateIsNotNull() { addCriterion("state is not null"); return this; } public Criteria andStateEqualTo(String value) { addCriterion("state =", value, "state"); return this; } public Criteria andStateNotEqualTo(String value) { addCriterion("state <>", value, "state"); return this; } public Criteria andStateGreaterThan(String value) { addCriterion("state >", value, "state"); return this; } public Criteria andStateGreaterThanOrEqualTo(String value) { addCriterion("state >=", value, "state"); return this; } public Criteria andStateLessThan(String value) { addCriterion("state <", value, "state"); return this; } public Criteria andStateLessThanOrEqualTo(String value) { addCriterion("state <=", value, "state"); return this; } public Criteria andStateLike(String value) { addCriterion("state like", value, "state"); return this; } public Criteria andStateNotLike(String value) { addCriterion("state not like", value, "state"); return this; } public Criteria andStateIn(List values) { addCriterion("state in", values, "state"); return this; } public Criteria andStateNotIn(List values) { addCriterion("state not in", values, "state"); return this; } public Criteria andStateBetween(String value1, String value2) { addCriterion("state between", value1, value2, "state"); return this; } public Criteria andStateNotBetween(String value1, String value2) { addCriterion("state not between", value1, value2, "state"); return this; } public Criteria andOrderTypeIsNull() { addCriterion("order_type is null"); return this; } public Criteria andOrderTypeIsNotNull() { addCriterion("order_type is not null"); return this; } public Criteria andOrderTypeEqualTo(Integer value) { addCriterion("order_type =", value, "orderType"); return this; } public Criteria andOrderTypeNotEqualTo(Integer value) { addCriterion("order_type <>", value, "orderType"); return this; } public Criteria andOrderTypeGreaterThan(Integer value) { addCriterion("order_type >", value, "orderType"); return this; } public Criteria andOrderTypeGreaterThanOrEqualTo(Integer value) { addCriterion("order_type >=", value, "orderType"); return this; } public Criteria andOrderTypeLessThan(Integer value) { addCriterion("order_type <", value, "orderType"); return this; } public Criteria andOrderTypeLessThanOrEqualTo(Integer value) { addCriterion("order_type <=", value, "orderType"); return this; } public Criteria andOrderTypeIn(List values) { addCriterion("order_type in", values, "orderType"); return this; } public Criteria andOrderTypeNotIn(List values) { addCriterion("order_type not in", values, "orderType"); return this; } public Criteria andOrderTypeBetween(Integer value1, Integer value2) { addCriterion("order_type between", value1, value2, "orderType"); return this; } public Criteria andOrderTypeNotBetween(Integer value1, Integer value2) { addCriterion("order_type not between", value1, value2, "orderType"); return this; } } }
package org.linphone.core; public abstract interface LinphoneChatRoom { public abstract LinphoneAddress getPeerAddress(); public abstract void sendMessage(String paramString); @Deprecated public abstract void sendMessage(LinphoneChatMessage paramLinphoneChatMessage, LinphoneChatMessage.StateListener paramStateListener); public abstract LinphoneChatMessage createLinphoneChatMessage(String paramString); public abstract LinphoneChatMessage[] getHistory(); public abstract LinphoneChatMessage[] getHistory(int paramInt); public abstract LinphoneChatMessage[] getHistoryRange(int paramInt1, int paramInt2); public abstract void destroy(); public abstract int getUnreadMessagesCount(); public abstract int getHistorySize(); public abstract void deleteHistory(); public abstract void compose(); public abstract boolean isRemoteComposing(); public abstract void markAsRead(); public abstract void deleteMessage(LinphoneChatMessage paramLinphoneChatMessage); public abstract void updateUrl(LinphoneChatMessage paramLinphoneChatMessage); public abstract LinphoneChatMessage createLinphoneChatMessage(String paramString1, String paramString2, LinphoneChatMessage.State paramState, long paramLong, boolean paramBoolean1, boolean paramBoolean2); public abstract LinphoneCore getCore(); public abstract LinphoneChatMessage createFileTransferMessage(LinphoneContent paramLinphoneContent); public abstract void sendChatMessage(LinphoneChatMessage paramLinphoneChatMessage); } /* Location: E:\DO-AN\Libraries\linphone-android-sdk-2.4.0\libs\LinLinphone\linphone.jar * Qualified Name: org.linphone.core.LinphoneChatRoom * JD-Core Version: 0.7.0.1 */
package com.bfchengnuo.security.demo.web.controller; import lombok.Cleanup; import org.springframework.util.FileCopyUtils; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * 处理文件上传下载等请求 * * @author Created by 冰封承諾Andy on 2019/7/14. */ @RestController @RequestMapping("/file") public class FileController { @PostMapping public Map<String, Object> upload(@RequestParam("file") MultipartFile multipartFile) throws IOException { System.out.println("Name:" + multipartFile.getName()); System.out.println("OriginalFilename:" + multipartFile.getOriginalFilename()); System.out.println("Size:" + multipartFile.getSize()); File localFile = new File(ResourceUtils.getFile("classpath:upload/"), Objects.requireNonNull(multipartFile.getOriginalFilename())); multipartFile.transferTo(localFile); Map<String, Object> result = new HashMap<>(); result.put("path", localFile.getAbsolutePath()); return result; } @GetMapping("/{name}") public void download(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws IOException { File file = ResourceUtils.getFile("classpath:upload/" + name); @Cleanup InputStream is = new FileInputStream(file); @Cleanup OutputStream os = response.getOutputStream(); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + name); // 或者使用 Apache 的 IOUtils.copy(inputStream, outputStream); FileCopyUtils.copy(is, os); os.flush(); } }
package org.adv25.ADVNTRIP.Network; import org.adv25.ADVNTRIP.Clients.Client; import org.adv25.ADVNTRIP.Servers.NtripCaster; import org.adv25.ADVNTRIP.Servers.ReferenceStation; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class NetworkProcessor implements Runnable { final static private Logger logger = LogManager.getLogger(NetworkProcessor.class.getName()); private Selector selector; private Thread thread; private ExecutorService executor = Executors.newCachedThreadPool(); private static NetworkProcessor instance; public static NetworkProcessor getInstance() { if (instance == null) instance = new NetworkProcessor(); return instance; } private NetworkProcessor() { try { this.selector = Selector.open(); this.thread = new Thread(this); this.thread.start(); logger.debug("Socket acceptor has initialized!"); } catch (IOException e) { logger.log(Level.ERROR, e); } } // update ports public SelectionKey registerChannel(ServerSocketChannel socket, NtripCaster caster) throws IOException { selector.wakeup(); return socket.register(this.selector, SelectionKey.OP_ACCEPT, caster); } public void close() throws IOException { this.selector.close(); this.thread.interrupt(); } public void run() { while (true) { try { int count = selector.select(); if (count < 1) continue; Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (!key.isValid()) continue; if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel socket = server.accept(); socket.configureBlocking(false); socket.register(selector, SelectionKey.OP_READ, key.attachment()); //attached caster logger.debug("Socket accept."); } else if (key.isReadable()) { if (key.attachment() instanceof ReferenceStation) { //Reference station sends gnss data ReferenceStation referenceStation = (ReferenceStation) key.attachment(); if (referenceStation.readSelf()) executor.submit(referenceStation); } else if (key.attachment() instanceof Client) { //Client sends nmea message Client client = (Client) key.attachment(); client.read(); executor.submit(client); } else { //New connect sends request message ConnectHandler connectHandler = new ConnectHandler(key); connectHandler.read(); executor.submit(connectHandler); } } iterator.remove(); } } catch (IOException ex) { logger.log(Level.ERROR, ex); } } } }
package com.dais.utils; import com.common.utils.HttpClientUtils; import com.common.utils.JsonUtils; import com.dais.model.CoinTradeRank; import com.dais.model.FvitualCoinTradeRank; import com.dais.vo.BterResponseVo; import org.apache.http.client.methods.HttpPost; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static com.common.utils.JsonUtils.jsonToPojo; /** * @author xxp * @version 2017- 08- 10 18:28 * @description * @copyright www.zhgtrade.com */ public class CoinTradeRankRquestUtil { public static List<CoinTradeRank> requestJson(){ String userAgent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5"; HttpPost post = new HttpPost("http://api.btc38.com/v1/ticker.php?c=all&mk_type=cny"); post.setHeader("User-Agent",userAgent); String json = HttpClientUtils.execute(post,"utf-8"); //保存接口返回的所有数据 String[] arr = json.split("},"); List<String> list = new ArrayList<>(); //过滤多余的数据 for (int i=0;i<arr.length;i++) { if(arr[i].indexOf("btc") > -1 || arr[i].indexOf("ltc") > -1 || arr[i].indexOf("bcc") > -1 || arr[i].indexOf("eth") > -1 || arr[i].indexOf("etc") > -1 || arr[i].indexOf("xrp") > -1 || arr[i].indexOf("bts") > -1){ list.add(arr[i]); } } //格式化数据 List<String> list2 = new ArrayList<>(); for (int i=0;i<list.size();i++) { String jsonStr = list.get(i); String coinType = "\"coinType\":"+jsonStr.substring(0,jsonStr.indexOf(":{\"ticker\":")).replace("{","")+"}"; String content = jsonStr.substring(jsonStr.indexOf("{\"ticker\":")+"{\"ticker\":".length()).replace("}",""); list2.add(content+","+coinType); } //json数据转换java对象 List<CoinTradeRank> listCtr = new ArrayList<>(); for (int i=0;i<list2.size();i++) { System.out.println(list2.get(i)); listCtr.add(jsonToPojo(list2.get(i),CoinTradeRank.class)); } return listCtr; } public static List<FvitualCoinTradeRank> requestJson2(){ // String[] arr = {"btc", "ltc", "xrp", "bcc" ,"qtum" ,"bts" ,"eth", "etc" ,"eos"}; String[] arr = {"btc", "ltc", "bcc" ,"eth", "etc" }; List<FvitualCoinTradeRank> list = new ArrayList<>(); String json = ""; BterResponseVo brv = null; FvitualCoinTradeRank fvcr = null; for (int i = 0; i < arr.length; i++) { try { json = HttpClientUtils.get("http://data.bter.com/api2/1/ticker/"+arr[i]+"_cny"); brv = JsonUtils.jsonToPojo(json, BterResponseVo.class); fvcr = new FvitualCoinTradeRank(); fvcr.setBasevolume(scale(brv.getBaseVolume())); fvcr.setHigh24hr(scale(brv.getHigh24hr())); fvcr.setHighestBid(scale(brv.getHighestBid())); fvcr.setLast(scale(brv.getLast())); fvcr.setLow24hr(scale(brv.getLow24hr())); fvcr.setLowestAsk(scale(brv.getLowestAsk())); fvcr.setPercentChange(scale(brv.getPercentChange())); fvcr.setQuotevolume(scale(brv.getQuoteVolume())); fvcr.setCoinType(arr[i]); list.add(fvcr); } catch (Exception e) { e.printStackTrace(); } } return list; } public static BigDecimal scale(double f) { BigDecimal bg = new BigDecimal(f); double f1 = bg.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue(); return BigDecimal.valueOf(f1); } }
package com.project.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.project.model.Experience; public interface ExperienceRepository extends JpaRepository<Experience, Long> { }
package com.lbsp.promotion.entity.exception; public class ServiceIsNullException extends RuntimeException { private static final long serialVersionUID = -2871565036661721432L; public ServiceIsNullException(String message) { super(message); } }
package cn.org.cerambycidae.util.DataBaseUtil; import cn.org.cerambycidae.pojo.StudentInfoExample; import java.io.UnsupportedEncodingException; public class FindStudentInfo { public static StudentInfoExample Conversion(String name, String age,String major) throws UnsupportedEncodingException { StudentInfoExample studentExample = new StudentInfoExample(); StudentInfoExample.Criteria criteria = studentExample.createCriteria(); if (name == null||name.equals("")) { criteria.andNameLike("%%"); }else{ //这里因为Get请求的字符编码转换是不能通过request直接转的,所以需要再转换一下 criteria.andNameLike( "%"+new String(name.getBytes("ISO-8859-1"),"utf-8")+"%"); } if (age != null&&!age.equals("")) { Integer integer = Integer.valueOf(age); criteria.andAgeEqualTo(integer); } if (major == null||major.equals("")){ criteria.andMajorLike("%%"); }else{ criteria.andMajorLike( "%"+new String(major.getBytes("ISO-8859-1"),"utf-8")+"%"); } return studentExample; } }
public class CSftpRespond { private String respCode; private String respText; public CSftpRespond(String respCode, String respText){ this.respCode = respCode; this.respText = respText; } public String getRespCode(){ return this.respCode; } public String getRespText(){ return this.respText; } }
package com.thinhlp.cocshopapp.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.squareup.picasso.Picasso; import com.thinhlp.cocshopapp.R; import com.thinhlp.cocshopapp.entities.CartItem; import com.thinhlp.cocshopapp.fragments.CartFragment; import com.thinhlp.cocshopapp.listeners.CartListener; import com.thinhlp.cocshopapp.viewholders.CartViewHolder; import java.util.ArrayList; import java.util.List; /** * Created by thinhlp on 7/9/17. */ public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> { private List<CartItem> items = new ArrayList<>(); private Context context; private CartListener cartListener; public CartAdapter(Context context, List<CartItem> items, CartListener cartListener) { this.items = items; this.context = context; this.cartListener = cartListener; } @Override public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.cart_item_view, parent, false); return new CartViewHolder(context, itemView, cartListener); } @Override public void onBindViewHolder(CartViewHolder holder, int position) { CartItem item = items.get(position); holder.itemName.setText(item.getProductName()); holder.itemPrice.setText(item.getPrice() + "đ"); holder.itemQuantity.setText(item.getQuantity() + ""); holder.cartItem = item; String imageUrl = item.getImageUrl(); if (imageUrl != null) { Picasso.with(context).load(imageUrl).into(holder.itemImg); } } @Override public int getItemCount() { return items.size(); } public void updateItemInCart(int position, List<CartItem> items) { this.items = items; notifyItemChanged(position); } }
package controller; import dao.yorumlarDAO; import entity.yorumlar; import java.io.Serializable; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; @Named @SessionScoped public class yorumlarController implements Serializable { private List<yorumlar> ylist; private yorumlarDAO ydao; private yorumlar yorumlar; private String bul = ""; private int page = 1; private int pageSize = 5; private int pageCount; public void next() { if (this.page == this.getPageCount()) { this.page = 1; } else { this.page++; } } public void previous() { if (this.page == 1) { this.page = this.getPageCount(); } else { this.page--; } } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageCount() { this.pageCount = (int) Math.ceil(this.getYdao().count() / (double) pageSize); return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } @Inject private filmlerController filmlerController; public void updateForm(yorumlar yorumlar) { this.yorumlar = yorumlar; } public void clearForm() { this.yorumlar = new yorumlar(); } public void update() { this.getYdao().update(this.yorumlar); this.clearForm(); } public void delete() { this.getYdao().delete(this.yorumlar); this.clearForm(); } public void create() { this.getYdao().create(this.yorumlar); this.clearForm(); } public List<yorumlar> getYlist() { this.ylist = this.getYdao().getYorumlar(this.bul, this.page, this.pageSize); return ylist; } public void setYlist(List<yorumlar> ylist) { this.ylist = ylist; } public yorumlarDAO getYdao() { if (this.ydao == null) { this.ydao = new yorumlarDAO(); } return ydao; } public void setYdao(yorumlarDAO ydao) { this.ydao = ydao; } public yorumlar getYorumlar() { if (this.yorumlar == null) { this.yorumlar = new yorumlar(); } return yorumlar; } public void setYorumlar(yorumlar yorumlar) { this.yorumlar = yorumlar; } public filmlerController getFilmlerController() { return filmlerController; } public void setFilmlerController(filmlerController filmlerController) { this.filmlerController = filmlerController; } public String getBul() { return bul; } public void setBul(String bul) { this.bul = bul; } }
package com.maven.quartz; import org.springframework.stereotype.Component; @Component public class CommonsUtil4Quartz { public void testMethod() { System.out.println("定时任务QuartzJob testMethod run..."); } }
package www.chaayos.com.chaimonkbluetoothapp.activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.math.BigDecimal; import java.util.ArrayList; import www.chaayos.com.chaimonkbluetoothapp.GlobalVariables; import www.chaayos.com.chaimonkbluetoothapp.R; import www.chaayos.com.chaimonkbluetoothapp.db.DatabaseAdapter; import www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model.OrderItem; public class MakePaymentActivity extends AppCompatActivity implements View.OnClickListener{ private Button oneButton; private Button twoButton; private Button threeButton; private Button fourButton; private Button fiveButton; private Button sixButton; private Button sevenButton; private Button eightButton; private Button nineButton; private Button zeroButton; private Button cancelButton; private Button clearButton; private Button finishButton; private TextView amountReceived; private TextView balanceAmountTextView; private int amountToPay = 0; private BigDecimal receiveAmount = new BigDecimal(0); private boolean isAppending = false; private int balanceAmount = 0; private GlobalVariables globalVariables; private ArrayList<OrderItem> orderItemArrayList; DatabaseAdapter databaseAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); globalVariables = (GlobalVariables) getApplicationContext(); orderItemArrayList = getIntent().getParcelableArrayListExtra("parcelableOrderItem"); globalVariables.setLatestOrderItemArrayList(orderItemArrayList); setContentView(R.layout.activity_make_payment); zeroButton = (Button) findViewById(R.id.button0); oneButton = (Button) findViewById(R.id.button1); twoButton = (Button) findViewById(R.id.button2); threeButton = (Button) findViewById(R.id.button3); fourButton = (Button) findViewById(R.id.button4); fiveButton = (Button)findViewById(R.id.button5); sixButton = (Button) findViewById(R.id.button6); sevenButton = (Button) findViewById(R.id.button7); eightButton = (Button) findViewById(R.id.button8); nineButton = (Button) findViewById(R.id.button9); cancelButton = (Button) findViewById(R.id.buttonCancel); clearButton = (Button) findViewById(R.id.buttonClear); amountReceived = (TextView) findViewById(R.id.amountReceived); balanceAmountTextView = (TextView) findViewById(R.id.balanceAmount); finishButton = (Button) findViewById(R.id.finishButton); databaseAdapter = new DatabaseAdapter(this); oneButton.setOnClickListener(this); twoButton.setOnClickListener(this); threeButton.setOnClickListener(this); fourButton.setOnClickListener(this); fiveButton.setOnClickListener(this); sixButton.setOnClickListener(this); sevenButton.setOnClickListener(this); eightButton.setOnClickListener(this); nineButton.setOnClickListener(this); zeroButton.setOnClickListener(this); cancelButton.setOnClickListener(this); clearButton.setOnClickListener(this); finishButton.setOnClickListener(this); calculateBalance(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button0: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("0"); } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "0"); } } calculateBalance(); break; case R.id.button1: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("1"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "1"); } } calculateBalance(); break; case R.id.button2: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("2"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "2"); } } calculateBalance(); break; case R.id.button3: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("3"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "3"); } } calculateBalance(); break; case R.id.button4: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("4"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "4"); } } calculateBalance(); break; case R.id.button5: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("5"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "5"); } } calculateBalance(); break; case R.id.button6: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("6"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "6"); } } calculateBalance(); break; case R.id.button7: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("7"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "7"); } } calculateBalance(); break; case R.id.button8: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("8"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "8"); } } calculateBalance(); break; case R.id.button9: if(!isAppending){ if(amountReceived.getText().length() < 6){ amountReceived.setText("9"); isAppending = true; } }else{ if(amountReceived.getText().length() < 6){ amountReceived.setText(amountReceived.getText() + "9"); } } calculateBalance(); break; case R.id.buttonCancel:int length = amountReceived.length(); if(length >1){ String numberEntered = amountReceived.getText().toString().substring(0,amountReceived.length()-1); amountReceived.setText(numberEntered); }else{ amountReceived.setText("0"); isAppending = false; } calculateBalance(); break; case R.id.buttonClear: receiveAmount = new BigDecimal(0); calculateBalance(); amountReceived.setText("" + receiveAmount); isAppending = false; calculateBalance(); break; case R.id.finishButton:System.out.print(globalVariables.getOrderArrayList()); globalVariables.setTaxListModel(null); Intent intent = new Intent(MakePaymentActivity.this,SettlementActivity.class); startActivity(intent); break; } } public ArrayList<OrderItem> getOrderItemArrayList() { return orderItemArrayList; } public void setAmountToPay(int amountToPay) { this.amountToPay = amountToPay; } public void calculateBalance(){ balanceAmount = amountToPay - Integer.parseInt(amountReceived.getText().toString()); balanceAmountTextView.setText(String.valueOf(balanceAmount)); } }
package br.com.zup.zupacademy.daniel.mercadolivre.eventos.transacao; import br.com.zup.zupacademy.daniel.mercadolivre.compra.Compra; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Set; @Service public class EventosNovaTransacao { @Autowired Set<EventoSucessoTransacao> eventosSucessoTransacao; @Autowired Set<EventoFalhaTrasacao> eventosFalhaTrasacao; public void processa(Compra compra) { if (compra.foiProcessadaComSucesso()) { eventosSucessoTransacao.forEach(e -> e.processa(compra)); } else { eventosFalhaTrasacao.forEach(e -> e.processa(compra)); } } }
package com.xwq520.excel.PoiDemo; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; public class MakeExcel { public static void main(String[] args)throws Exception { Workbook wb = new HSSFWorkbook();//定义一个新的工作簿 FileOutputStream fileOut = new FileOutputStream("e:\\poi创建的工作簿.xls"); wb.write(fileOut); fileOut.close(); } }
package com.test.data.test; import com.test.data.config.Neo4jConfig; import com.test.data.domain.Actor; import com.test.data.domain.Movie; import com.test.data.domain.Role; import com.test.data.repositories.ActorRepository; import com.test.data.repositories.MovieRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import java.util.Date; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {Neo4jConfig.class}) public class MovieTest { private static Logger logger = LoggerFactory.getLogger(MovieTest.class); @Autowired MovieRepository movieRepository; @Autowired ActorRepository actorRepository; @Before public void initData(){ movieRepository.deleteAll(); actorRepository.deleteAll(); Movie matrix1 = new Movie(); matrix1.setName("西游记"); matrix1.setPhoto("/images/movie/西游记.jpg"); matrix1.setCreateDate(new Date()); Actor swk = new Actor(); swk.setName("六小龄童"); Actor zbj = new Actor(); zbj.setName("马德华"); Actor ccr = new Actor(); ccr.setName("迟重瑞"); Actor yhl = new Actor(); yhl.setName("闫怀礼"); matrix1.addRole(swk, "孙悟空"); matrix1.addRole(zbj, "猪八戒"); matrix1.addRole(ccr, "唐僧"); matrix1.addRole(yhl, "沙僧"); movieRepository.save(matrix1); Assert.notNull(matrix1.getId()); } @Test public void get(){ Movie movie = movieRepository.findByName("西游记"); Assert.notNull(movie); logger.info("===movie=== movie:{}, {}",movie.getName(), movie.getCreateDate()); for(Role role : movie.getRoles()){ logger.info("====== actor:{}, role:{}", role.getActor().getName(), role.getName()); } } }
/* * NewRoad * CopyRight Rech Informática Ltda. Todos os direitos reservados. */ package br.com.tlr.elements; import br.com.tlr.interfaces.Renderable; import java.util.List; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; /** * Itens equipados no jogador */ public class Equipped implements Renderable { /** Lista de itens equipados */ List<Item> itens; @Override public void load(GameContainer container) throws SlickException { for (Item item : itens) { item.load(container); } } @Override public void update(GameContainer container, int delta) throws SlickException { for (Item item : itens) { item.update(container, delta); } } @Override public void render(GameContainer container, Graphics g) throws SlickException { for (Item item : itens) { item.render(container, g); } } }
/* * 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 DAO; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Usuario */ public class Operaciones { String driver; String url; String uss; String contra; public Operaciones() { driver = "com.mysql.jdbc.Driver"; url = "jdbc:mysql://localhost:3306/CRUD"; uss = "root"; contra = ""; } public int logear(String us, String pass) { Connection conn; PreparedStatement pst; ResultSet rs; int cont = 0; int nivel = 0; String sql = "select nivel from login where usuario='" + us + "' and contra='" + pass + "'"; try { Class.forName(this.driver); conn = (Connection) DriverManager.getConnection( this.url, this.uss, this.contra); pst = (PreparedStatement) conn.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()) { nivel = rs.getInt(1); } conn.close(); } catch (ClassNotFoundException | SQLException e) { } return nivel; } public int registrar(String us, String pass) { Connection conn; PreparedStatement pst; ResultSet rs; int cont = 0; int nivel = 1; String sql = "insert into login values('" + us + "','" + pass + "', 1)"; try { Class.forName(this.driver); conn = (Connection) DriverManager.getConnection( this.url, this.uss, this.contra); pst = (PreparedStatement) conn.prepareStatement(sql); rs = pst.executeQuery(); conn.close(); } catch (ClassNotFoundException | SQLException e) { } return nivel; } }
package com.duanxr.yith.easy; /** * @author 段然 2021/5/14 */ public class ProductSWorthOverInvoices { /** * Product 表: * * +-------------+---------+ * | Column Name | Type | * +-------------+---------+ * | product_id | int | * | name | varchar | * +-------------+---------+ * product_id 是这张表的主键 * 表中含有产品 id 、产品名称。产品名称都是小写的英文字母,产品名称都是唯一的 *   * * Invoice 表: * * +-------------+------+ * | Column Name | Type | * +-------------+------+ * | invoice_id | int | * | product_id | int | * | rest | int | * | paid | int | * | canceled | int | * | refunded | int | * +-------------+------+ * invoice_id 发票 id ,是这张表的主键 * product_id 产品 id * rest 应缴款项 * paid 已支付金额 * canceled 已取消金额 * refunded 已退款金额 *   * * 要求写一个SQL查询,返回全部发票中每个产品的产品名称、总应缴款项、总已支付金额、总已取消金额、总已退款金额 * * 查询结果按 product_name排序 * * 示例: * * Product 表: * +------------+-------+ * | product_id | name | * +------------+-------+ * | 0 | ham | * | 1 | bacon | * +------------+-------+ * Invoice table: * +------------+------------+------+------+----------+----------+ * | invoice_id | product_id | rest | paid | canceled | refunded | * +------------+------------+------+------+----------+----------+ * | 23 | 0 | 2 | 0 | 5 | 0 | * | 12 | 0 | 0 | 4 | 0 | 3 | * | 1 | 1 | 1 | 1 | 0 | 1 | * | 2 | 1 | 1 | 0 | 1 | 1 | * | 3 | 1 | 0 | 1 | 1 | 1 | * | 4 | 1 | 1 | 1 | 1 | 0 | * +------------+------------+------+------+----------+----------+ * Result 表: * +-------+------+------+----------+----------+ * | name | rest | paid | canceled | refunded | * +-------+------+------+----------+----------+ * | bacon | 3 | 3 | 3 | 3 | * | ham | 2 | 4 | 5 | 3 | * +-------+------+------+----------+----------+ * - bacon 的总应缴款项为 1 + 1 + 0 + 1 = 3 * - bacon 的总已支付金额为 1 + 0 + 1 + 1 = 3 * - bacon 的总已取消金额为 0 + 1 + 1 + 1 = 3 * - bacon 的总已退款金额为 1 + 1 + 1 + 0 = 3 * - ham 的总应缴款项为 2 + 0 = 2 * - ham 的总已支付金额为 0 + 4 = 4 * - ham 的总已取消金额为 5 + 0 = 5 * - ham 的总已退款金额为 0 + 3 = 3 * * * Table: Product * * +-------------+---------+ * | Column Name | Type | * +-------------+---------+ * | product_id | int | * | name | varchar | * +-------------+---------+ * product_id is the primary key for this table. * This table contains the ID and the name of the product. The name consists of only lowercase English letters. No two products have the same name. *   * * Table: Invoice * * +-------------+------+ * | Column Name | Type | * +-------------+------+ * | invoice_id | int | * | product_id | int | * | rest | int | * | paid | int | * | canceled | int | * | refunded | int | * +-------------+------+ * invoice_id is the primary key for this table and the id of this invoice. * product_id is the id of the product for this invoice. * rest is the amount left to pay for this invoice. * paid is the amount paid for this invoice. * canceled is the amount canceled for this invoice. * refunded is the amount refunded for this invoice. *   * * Write an SQL query that will, for all products, return each product name with total amount due, paid, canceled, and refunded across all invoices. * * Return the result table ordered by product_name. * * The query result format is in the following example: * *   * * Product table: * +------------+-------+ * | product_id | name | * +------------+-------+ * | 0 | ham | * | 1 | bacon | * +------------+-------+ * Invoice table: * +------------+------------+------+------+----------+----------+ * | invoice_id | product_id | rest | paid | canceled | refunded | * +------------+------------+------+------+----------+----------+ * | 23 | 0 | 2 | 0 | 5 | 0 | * | 12 | 0 | 0 | 4 | 0 | 3 | * | 1 | 1 | 1 | 1 | 0 | 1 | * | 2 | 1 | 1 | 0 | 1 | 1 | * | 3 | 1 | 0 | 1 | 1 | 1 | * | 4 | 1 | 1 | 1 | 1 | 0 | * +------------+------------+------+------+----------+----------+ * Result table: * +-------+------+------+----------+----------+ * | name | rest | paid | canceled | refunded | * +-------+------+------+----------+----------+ * | bacon | 3 | 3 | 3 | 3 | * | ham | 2 | 4 | 5 | 3 | * +-------+------+------+----------+----------+ * - The amount of money left to pay for bacon is 1 + 1 + 0 + 1 = 3 * - The amount of money paid for bacon is 1 + 0 + 1 + 1 = 3 * - The amount of money canceled for bacon is 0 + 1 + 1 + 1 = 3 * - The amount of money refunded for bacon is 1 + 1 + 1 + 0 = 3 * - The amount of money left to pay for ham is 2 + 0 = 2 * - The amount of money paid for ham is 0 + 4 = 4 * - The amount of money canceled for ham is 5 + 0 = 5 * - The amount of money refunded for ham is 0 + 3 = 3 * */ private static final String SQL = "" + "SELECT\n" + "\tProduct.NAME AS NAME,\n" + "\tCOALESCE ( SUM( Invoice.rest ), 0 ) AS rest,\n" + "\tCOALESCE ( SUM( Invoice.paid ), 0 ) AS paid,\n" + "\tCOALESCE ( SUM( Invoice.canceled ), 0 ) AS canceled,\n" + "\tCOALESCE ( SUM( Invoice.refunded ), 0 ) AS refunded \n" + "FROM\n" + "\tProduct\n" + "\tLEFT JOIN Invoice ON Product.product_id = Invoice.product_id \n" + "GROUP BY\n" + "\tProduct.product_id \n" + "ORDER BY\n" + "\tProduct.NAME"; }
package org.fhcrc.honeycomb.metapop; import org.fhcrc.honeycomb.metapop.*; import org.fhcrc.honeycomb.metapop.fitness.cheaterloadcalculator.*; import org.fhcrc.honeycomb.metapop.fitness.fitnesscalculator.*; import org.fhcrc.honeycomb.metapop.environmentchanger.*; import org.fhcrc.honeycomb.metapop.coordinate.*; import org.junit.*; import static org.junit.Assert.*; import static org.hamcrest.core.Is.is; import java.util.Set; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; public class PopulationTest { private List<Double> fitnesses = Arrays.asList(StrictMath.log(2), StrictMath.log(2)*1.1); private List<Double> freqs = Arrays.asList(0.5, 0.5); private int initial_size = 4; private double initial_cheat_freq = 0.7; private double cheat_adv = 0.02; private List<Double> coops = Arrays.asList(30.0,3.0); private List<Double> cheats = Arrays.asList(70.0,7.0); private double no_u = 0; private double u = 1e-4; private long seed = 12345L; private RandomNumberUser rng = new RandomNumberUser(seed); private FitnessCalculator fc; private CheaterLoadCalculator clc; private double each_pop; private Types types; private Population pop1; private Population pop2; private List<Population> pops; @Before public void setUp() { rng = new RandomNumberUser(seed); fc = new FitnessUnchanged(); each_pop = initial_size * initial_cheat_freq / freqs.size(); types = new Types(fitnesses, freqs); pop1 = new Population(initial_size, initial_cheat_freq, cheat_adv, no_u, types, fc, rng); pop2 = new Population(coops, cheats, fitnesses, cheat_adv, no_u, fc, rng); pops = Arrays.asList(pop1, pop2); } @Test public void mutation() { double coops = 1e7; double cheats = 2e6; double small_coops = 1; double small_cheats = 10; double expected_coops = coops * (1 - u); double expected_cheats = cheats + u*coops; List<Double> mutants = pop1.mutate(coops,cheats); assertEquals("coops", coops, mutants.get(0), 0.0); assertEquals("cheats", cheats, mutants.get(1), 0.0); mutants = pop1.mutate(small_coops, small_cheats); assertEquals("small coops", small_coops, mutants.get(0), 0.0); assertEquals("small cheats", small_cheats, mutants.get(1), 0.0); Population pop = new Population(initial_size, initial_cheat_freq, cheat_adv, u, types, fc, rng); mutants = pop.mutate(coops, cheats); assertEquals("coops", expected_coops, mutants.get(0), 0.0); assertEquals("cheats", expected_cheats, mutants.get(1), 0.0); for (int i=0; i<100; i++) { mutants = pop.mutate(small_coops, small_cheats); double mutant_coops = mutants.get(0); double mutant_cheats = mutants.get(1); assertTrue("coop mutate one", mutant_coops == 1.0 || mutant_coops == 0.0); assertTrue("cheat mutate ten", mutant_cheats == 11.0 || mutant_cheats == 10.0); } } @Test public void generatePops() { initial_size = 1000; List<Population> test_pops = Population.generate(10, initial_size, initial_cheat_freq, cheat_adv, no_u, types, fc, rng); List<Double> type1_coops = new ArrayList<Double>(); List<Double> type1_cheats = new ArrayList<Double>(); for (Population pop : test_pops) { type1_coops.add(pop.getCoops().get(0)); type1_cheats.add(pop.getCheats().get(0)); assertEquals("cheat freq", initial_cheat_freq, pop.getNCheats()/(pop.getNCoops()+pop.getNCheats()), 0.01); } Set<Double> type1_coop_set = new HashSet<Double>(type1_coops); Set<Double> type1_cheat_set = new HashSet<Double>(type1_cheats); assertTrue("type1 coop", type1_coop_set.size() > 1); assertTrue("type1 cheat", type1_cheat_set.size() > 1); } @Test(expected=IllegalArgumentException.class) public void initializeError() { List<Double> coops2 = Arrays.asList(1.0, 2.0, 4.0, 8.0, 16.0); Population bad_pop = new Population(coops2, cheats, fitnesses, cheat_adv, no_u, fc, rng); } @Test public void checkInitialization() { assertEquals("pop1 size", initial_size, pop1.getSize(), 0.0); assertEquals("pop2 size", 110, pop2.getSize(), 0.0); assertEquals("pop1 coop size", initial_size*(1-initial_cheat_freq), pop1.getNCoops(), 0.0); assertEquals("pop2 coop size", 33, pop2.getNCoops(), 0.0); assertEquals("pop1 cheat size", initial_size*initial_cheat_freq, pop1.getNCheats(), 0.0); assertEquals("pop2 cheat size", 77, pop2.getNCheats(), 0.0); assertEquals("pop1 cheat freq", initial_cheat_freq, pop1.getCheatFrequency(), 0.0); assertEquals("pop2 cheat freq", initial_cheat_freq, pop2.getCheatFrequency(), 0.0); assertEquals("pop1 cheat advantage", cheat_adv, pop1.getCheatAdvantage(), 0.0); assertEquals("pop2 cheat advantage", cheat_adv, pop2.getCheatAdvantage(), 0.0); for (Population pop : pops) { assertSame("rng", rng, pop.getRNG()); assertEquals("seed", seed, pop.getRNG().getSeed()); assertThat("fitnesses", fitnesses, is(pop.getMaxFitnesses())); } } @Test public void copyPopulation() { Population pop_copy = new Population(pop1); assertNotSame("population", pop1, pop_copy); assertNotSame("coop array", pop1.getCoops(), pop_copy.getCoops()); assertThat("coop array", pop1.getCoops(), is(pop_copy.getCoops())); assertNotSame("cheat array", pop1.getCheats(), pop_copy.getCheats()); assertThat("cheat array", pop1.getCheats(), is(pop_copy.getCheats())); assertNotSame("coop freq array", pop1.getCoopFrequencies(), pop_copy.getCoopFrequencies()); assertThat("coop freq array", pop1.getCoopFrequencies(), is(pop_copy.getCoopFrequencies())); assertNotSame("cheat freq array", pop1.getCheatFrequencies(), pop_copy.getCheatFrequencies()); assertThat("cheat freq array", pop1.getCheatFrequencies(), is(pop_copy.getCheatFrequencies())); assertNotSame("fitness array", pop1.getMaxFitnesses(), pop_copy.getMaxFitnesses()); assertThat("fitness array", pop1.getMaxFitnesses(), is(pop_copy.getMaxFitnesses())); assertSame("RNG", pop_copy.getRNG(), pop1.getRNG()); assertEquals("seeds", pop_copy.getRNG().getSeed(), pop1.getRNG().getSeed()); } @Test public void persistenceGivesUniqueNumbers() { List<Double> pop1_res = new ArrayList<Double>(5); List<Double> pop_copy_res = new ArrayList<Double>(5); int size = 100; Population pop_copy = new Population(pop1); for (int i=0; i<size; i++) pop1_res.add(pop1.persistence(0.5)); for (int i=0; i<size; i++) pop_copy_res.add(pop_copy.persistence(0.5)); int same = 0; for (int i=0; i<size; i++) { if (pop1_res.get(i).equals(pop_copy_res.get(i))) ++same; } assertNotEquals("samples different", pop1_res, pop_copy_res); } @Test public void growPopulation() { List<Double> fitnesses = Arrays.asList(Math.log(2), Math.log(2)*1.1); List<Double> freqs = Arrays.asList(0.5, 0.5); int initial_size = 4; double initial_cheat_freq = 0.5; double cheat_adv = 0.02; Types types = new Types(fitnesses, freqs); Population pop = new Population(initial_size, initial_cheat_freq, cheat_adv, no_u, types, fc, rng); double each_pop = initial_size * initial_cheat_freq / freqs.size(); double type1_coop_expected = 2.0; double type2_coop_expected = growthFormula(each_pop, fitnesses.get(1), 1); double type1_cheat_expected = growthFormula(each_pop, fitnesses.get(0)*(1+cheat_adv), 1); double type2_cheat_expected = growthFormula(each_pop, fitnesses.get(1)*(1+cheat_adv), 1); double nCoops = type1_coop_expected + type2_coop_expected; double nCheats = type1_cheat_expected + type2_cheat_expected; double expected_cheat_freq = nCheats/(nCoops+nCheats); //System.out.println("Growing..."); pop.grow(); //System.out.println("Coops: " + pop.getCoops()); //System.out.println("Cheats: " + pop.getCheats()); //System.out.println("New coop freq: " + pop.getCoopFrequency()); assertEquals("New type1 coop pop", type1_coop_expected, pop.getCoops().get(0), 0); assertEquals("New type2 coop pop", type2_coop_expected, pop.getCoops().get(1), 0); assertEquals("New type1 cheat pop", type1_cheat_expected, pop.getCheats().get(0), 0); assertEquals("New type2 cheat pop", type2_cheat_expected, pop.getCheats().get(1), 0); assertEquals("New coop pop", type1_coop_expected+type2_coop_expected, pop.getNCoops(), 0); assertEquals("New cheat pop", type1_cheat_expected+type2_cheat_expected, pop.getNCheats(), 0); assertEquals("New nCoops", nCoops, pop.getNCoops(), 0); assertEquals("New nCheats", nCheats, pop.getNCheats(), 0); assertEquals("New cheat freq", expected_cheat_freq, pop.getCheatFrequency(), 0); //System.out.println(); } @Test public void dilutePopulation() { double large_pop = 1e8; double small_pop = 9.0; double lt1_pop = 0.9; List<Double> coops = Arrays.asList(large_pop, small_pop, lt1_pop); List<Double> cheats = Arrays.asList(large_pop, small_pop, lt1_pop); List<Double> fitnesses = Arrays.asList(Math.log(2), Math.log(2), Math.log(2)); double cheat_advantage = 0.02; double dilution_amount = 0.1; Population pop = new Population(coops, cheats, fitnesses, cheat_advantage, no_u, fc, rng); //System.out.println("\n\ndilutePopulation()"); Population diluted = pop.dilute(dilution_amount); //System.out.println("Diluted"); //System.out.println(diluted); //System.out.println("Remaining"); //System.out.println("coops " + pop.getCoops()); //System.out.println("cheats " + pop.getCheats()); assertEquals("remaining coops", large_pop*(1-dilution_amount), pop.getCoops().get(0),0); assertEquals("remaining cheats", large_pop*(1-dilution_amount), pop.getCheats().get(0),0); assertEquals("diluted coops", large_pop*dilution_amount, diluted.getCoops().get(0),0); assertEquals("diluted cheats", large_pop*dilution_amount, diluted.getCheats().get(0),0); // getNextBinomal currently returns two 1s in a row. assertEquals(8.0, pop.getCoops().get(1),0); assertEquals(8.0, pop.getCheats().get(1),0); assertEquals(1.0, diluted.getCoops().get(1),0); assertEquals(1.0, diluted.getCheats().get(1),0); pop = new Population(coops, cheats, fitnesses, cheat_advantage, no_u, fc, rng); while(pop.getCoops().get(2) > 0) { assertEquals("correct amount remains", lt1_pop, pop.getCoops().get(2), 0.0); assertEquals("nothing in diluted", 0.0, diluted.getCoops().get(2), 0.0); //System.out.println("\n\ndilutePopulation()"); diluted = pop.dilute(dilution_amount); //System.out.println("Diluted"); //System.out.println(diluted); //System.out.println("Remaining"); //System.out.println("coops " + pop.getCoops()); //System.out.println("cheats " + pop.getCheats()); } assertEquals("no coops remain", 0.0, pop.getCoops().get(2), 0.0); assertEquals("nothing is migrated", 0.0, diluted.getCoops().get(2), 0.0); } private double growthFormula(double A, double r, double dt) { return A*Math.exp(r*dt); } @Test public void mixPopulations() { List<Double> coops = Arrays.asList(1.0, 2.0, 4.0, 8.0, 16.0); List<Double> cheats = Arrays.asList(12.0, 10.0, 8.0, 6.0, 4.0); double coop_sum = 0; double cheat_sum = 0; for (double d:coops) coop_sum += d; for (double d:cheats) cheat_sum += d; List<Double> fitnesses = Arrays.asList(Math.log(2), Math.log(2), Math.log(2), Math.log(2), Math.log(2)); double cheat_adv = 0.02; Population pop = new Population(coops, cheats, fitnesses, cheat_adv, no_u, fc, rng); pop.mix(pop); assertNotSame(coops, pop.getCoops()); assertNotSame(cheats, pop.getCheats()); assertEquals("nCoops updated", coop_sum*2, pop.getNCoops(), 0.0); assertEquals("nCheats updated", cheat_sum*2, pop.getNCheats(), 0.0); //System.out.println("\n\nNew population"); //System.out.println(pop); for (int i=0; i<coops.size(); i++) { assertEquals(coops.get(i)*2, pop.getCoops().get(i), 0.0); assertEquals(cheats.get(i)*2, pop.getCheats().get(i), 0.0); } } @Test public void mixLargePopulations() { List<Double> coops = Arrays.asList(1e9); List<Double> cheats = Arrays.asList(2e9); List<Double> fitnesses = Arrays.asList(Math.log(2)); double cheat_adv = 0.02; Population pop = new Population(coops, cheats, fitnesses, cheat_adv, no_u, fc, rng); //System.out.println("\n\nOriginal population"); //System.out.println(pop); pop.mix(pop); //System.out.println("\n\nNew population"); //System.out.println(pop); for (int i=0; i<coops.size(); i++) { assertEquals(coops.get(i)*2, pop.getCoops().get(i), 0.0); assertEquals(cheats.get(i)*2, pop.getCheats().get(i), 0.0); } } @Test public void shiftFitness() { List<Double> coops = Arrays.asList(100.0, 1e6); List<Double> cheats = Arrays.asList(200.0, 2e7); Population pop = new Population(coops, cheats, fitnesses, cheat_adv, no_u, fc, rng); double mutant_freq = 1e-4; List<Double> new_freqs = Arrays.asList(1-mutant_freq, mutant_freq); pop.shiftFitness(new_freqs); assertTrue("more type 0 than type 1 coops", pop.getCoops().get(0) > pop.getCoops().get(1)); assertTrue("more type 0 than type 1 cheats", pop.getCheats().get(0) > pop.getCheats().get(1)); assertEquals("total coop amount correct", coops.get(1), pop.getCoops().get(0) + pop.getCoops().get(1), 0.0); assertEquals("total cheat amount correct", cheats.get(1), pop.getCheats().get(0) + pop.getCheats().get(1), 0.0); double coop_expect = mutant_freq * coops.get(1); double coop_samp_error = 2*StrictMath.sqrt(mutant_freq*coops.get(1)); assertEquals("new coops within sampling error", coop_expect, pop.getCoops().get(1), coop_samp_error); double cheat_expect = mutant_freq * cheats.get(1); double cheat_samp_error = 2*StrictMath.sqrt(mutant_freq*cheats.get(1)); assertEquals("new cheats within sampling error", cheat_expect, pop.getCheats().get(1), cheat_samp_error); double coop1 = pop.getCoops().get(0); double coop2 = pop.getCoops().get(1); double cheat1 = pop.getCheats().get(0); double cheat2 = pop.getCheats().get(1); double coop1_expected = coop1 * StrictMath.exp(fitnesses.get(0)); double coop2_expected = coop2 * StrictMath.exp(fitnesses.get(1)); double cheat1_expected = cheat1 * StrictMath.exp(fitnesses.get(0)*(1+cheat_adv)); double cheat2_expected = cheat2 * StrictMath.exp(fitnesses.get(1)*(1+cheat_adv)); pop.grow(); assertEquals("type 1 coop shifted growth", coop1_expected, pop.getCoops().get(0), 0.0); assertEquals("type 2 coop shifted growth", coop2_expected, pop.getCoops().get(1), 0.0); assertEquals("type 1 cheat shifted growth", cheat1_expected, pop.getCheats().get(0), 0.0); assertEquals("type 2 cheat shifted growth", cheat2_expected, pop.getCheats().get(1), 0.0); } }
package com.debugers.alltv.model.dto; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import java.util.Date; @Data public class DouYuDTO { @JSONField(name = "room_id") private String roomId; @JSONField(name = "cate_id") private String cateId; @JSONField(name = "room_src") private String roomThumb; @JSONField(name = "game_name") private String cateName;//分类名 @JSONField(name = "room_name") private String roomName; @JSONField(name = "show_status") private Integer roomStatus; //1 开播 2 未开播 @JSONField(name = "show_time") private Date startTime; @JSONField(name = "nickname") private String ownerName; @JSONField(name = "avatar") private String avatar; @JSONField(name = "online") private Long online; //热度 private String realUrl; //真是直播地址 }
package com.tencent.mm.plugin.fts.b; import android.database.Cursor; import android.support.design.a$i; import com.tencent.mm.g.c.ai; import com.tencent.mm.kernel.g; import com.tencent.mm.model.s; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.plugin.fts.PluginFTS; import com.tencent.mm.plugin.fts.a.a.i; import com.tencent.mm.plugin.fts.a.b; import com.tencent.mm.plugin.fts.a.c$a; import com.tencent.mm.plugin.fts.a.d; import com.tencent.mm.plugin.fts.a.j; import com.tencent.mm.plugin.fts.a.m; import com.tencent.mm.plugin.fts.a.n; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import junit.framework.AssertionFailedError; public final class a extends b { private static Set<String> jtI = new HashSet(); private m dhW; private j iXo; private com.tencent.mm.sdk.e.m.b jtA = new 1(this); private com.tencent.mm.sdk.e.m.b jtB = new 2(this); private com.tencent.mm.sdk.e.j.a jtC = new 3(this); private com.tencent.mm.sdk.e.j.a jtD = new 4(this); private com.tencent.mm.sdk.b.c jtE = new 5(this); private com.tencent.mm.sdk.b.c jtF = new 6(this); private al jtG = new al(g.Em().lnJ.getLooper(), new 7(this), true); private al jtH = new al(g.Em().lnJ.getLooper(), new 8(this), false); private com.tencent.mm.plugin.fts.c.a jtu; private HashSet<String> jtv; private HashMap<String, List<Long>> jtw; private HashMap<String, String[]> jtx; private HashMap<String, List<Long>> jty; private Method jtz; private class a extends com.tencent.mm.plugin.fts.a.a.a { private int iXv; private int iXw; private a() { this.iXv = 0; this.iXw = 0; } /* synthetic */ a(a aVar, byte b) { this(); } public final boolean execute() { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "Start building chatroom index."); HashSet hashSet = new HashSet(); Cursor rawQuery = a.this.jtu.jpT.rawQuery("SELECT DISTINCT chatroom FROM FTS5ChatRoomMembers;", null); while (rawQuery.moveToNext()) { hashSet.add(rawQuery.getString(0)); } rawQuery.close(); Cursor h = a.this.iXo.h("SELECT chatroomname, memberlist FROM chatroom;", null); int i = 5; while (h.moveToNext()) { if (Thread.interrupted()) { h.close(); a.this.jtu.commit(); throw new InterruptedException(); } String string = h.getString(0); Object split = c$a.jqy.split(h.getString(1)); a.this.jtx.put(string, split); if (!hashSet.remove(string)) { if (i >= 5) { a.this.jtu.commit(); a.this.jtu.beginTransaction(); i = 0; } a.this.jtu.j(string, split); i++; this.iXv++; } } h.close(); a.this.jtu.commit(); Iterator it = hashSet.iterator(); int i2 = 5; while (it.hasNext()) { String str = (String) it.next(); if (i2 >= 5) { a.this.jtu.commit(); a.this.jtu.beginTransaction(); i2 = 0; } a.this.jtu.CK(str); i = i2 + 1; this.iXw++; i2 = i; } a.this.jtu.commit(); return true; } public final String getName() { return "BuildChatroomIndexTask"; } public final String afC() { return String.format("{new: %d removed: %d}", new Object[]{Integer.valueOf(this.iXv), Integer.valueOf(this.iXw)}); } public final int getId() { return 3; } } private class c extends com.tencent.mm.plugin.fts.a.a.a { private c() { } /* synthetic */ c(a aVar, byte b) { this(); } public final boolean execute() { a.this.jtu.k(com.tencent.mm.plugin.fts.a.c.jqi); return true; } public final String getName() { return "DeleteAllFriendTask"; } } private class e extends com.tencent.mm.plugin.fts.a.a.a { private String cYO; private boolean dio = false; public e(String str) { this.cYO = str; } public final boolean execute() { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "Insert Contact %s", new Object[]{this.cYO}); ab Co = a.this.iXo.Co(this.cYO); if (Co == null || Co.field_username.length() <= 0 || !a.this.E(Co)) { this.dio = true; } else { a.this.F(Co); } a.this.jtw.remove(this.cYO); a.this.jtv.remove(this.cYO); return true; } public final String afC() { return String.format("{username: %s isSkipped: %b}", new Object[]{this.cYO, Boolean.valueOf(this.dio)}); } public final String getName() { return "InsertContactTask"; } } private class h extends com.tencent.mm.plugin.fts.a.a.a { private String cYO; private boolean dio = false; private boolean jud = false; public h(String str) { this.cYO = str; } public final boolean execute() { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "Dirty Contact %s", new Object[]{this.cYO}); if (a.this.jtw.containsKey(this.cYO)) { this.jud = true; } else { a.this.jtu.Cs(this.cYO); List c = a.this.jtu.c(com.tencent.mm.plugin.fts.a.c.jqk, this.cYO); a.this.jtw.put(this.cYO, c); if (c.isEmpty()) { this.dio = true; a.this.dhW.a(65556, new e(this.cYO)); } else { Cursor CJ = a.this.jtu.CJ(this.cYO); HashSet hashSet = new HashSet(); while (CJ.moveToNext()) { hashSet.add(CJ.getString(0)); } CJ.close(); Iterator it = hashSet.iterator(); while (it.hasNext()) { String str = (String) it.next(); a.this.jtu.Cs(str); if (!a.this.jtw.containsKey(str)) { a.this.jtw.put(str, a.this.jtu.c(com.tencent.mm.plugin.fts.a.c.jqk, str)); } } a.this.jtv.remove(this.cYO); ((PluginFTS) g.n(PluginFTS.class)).getTopHitsLogic().CH(this.cYO); } } return true; } public final String afC() { return String.format("{username: %s cached: %b isSkipped: %b}", new Object[]{this.cYO, Boolean.valueOf(this.jud), Boolean.valueOf(this.dio)}); } public final String getName() { return "MarkContactDirtyTask"; } public final int getId() { return 17; } } private class l extends com.tencent.mm.plugin.fts.a.a.h { public l(i iVar) { super(iVar); } protected final void a(com.tencent.mm.plugin.fts.a.a.j jVar) { int i = 0; super.a(jVar); com.tencent.mm.plugin.fts.c.a a = a.this.jtu; String str = this.jsj.bWm; Cursor rawQuery = a.jpT.rawQuery("SELECT count(*) FROM FTS5ChatRoomMembers WHERE member=?", new String[]{str}); if (rawQuery.moveToNext()) { i = rawQuery.getInt(0); } rawQuery.close(); com.tencent.mm.plugin.fts.a.a.l lVar = new com.tencent.mm.plugin.fts.a.a.l(); lVar.userData = Integer.valueOf(i); jVar.jsx = new ArrayList(); jVar.jsx.add(lVar); } public final String getName() { return "SearchChatroomCountTask"; } } public final com.tencent.mm.plugin.fts.a.a.a a(i iVar) { com.tencent.mm.plugin.fts.a.a.a lVar; switch (iVar.jsn) { case 5: lVar = new l(iVar); break; case 6: lVar = new k(this, iVar); break; case 7: lVar = new m(this, iVar); break; case 8: lVar = new o(this, iVar); break; case 9: lVar = new p(this, iVar); break; case 16: lVar = new q(this, iVar); break; case a$i.AppCompatTheme_actionModeCutDrawable /*32*/: lVar = new n(this, iVar); break; case a$i.AppCompatTheme_homeAsUpIndicator /*48*/: lVar = new t(this, iVar); break; case 64: lVar = new s(this, iVar); break; case 96: lVar = new r(this, iVar); break; default: lVar = new j(this, iVar); break; } return this.dhW.a(-65536, lVar); } protected final boolean onCreate() { if (((n) g.n(n.class)).isFTSContextReady()) { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "Create Success!"); this.jtu = (com.tencent.mm.plugin.fts.c.a) ((n) g.n(n.class)).getFTSIndexStorage(3); this.dhW = ((n) g.n(n.class)).getFTSTaskDaemon(); this.iXo = ((n) g.n(n.class)).getFTSMainDB(); this.jtv = new HashSet(); this.jtw = new HashMap(); this.jtx = new HashMap(); this.jty = new HashMap(); try { this.jtz = ai.class.getDeclaredMethod("wS", new Class[0]); this.jtz.setAccessible(true); this.dhW.a(WXMediaMessage.MINI_PROGRAM__THUMB_LENGHT, new f(this, (byte) 0)); this.dhW.a(131082, new a(this, (byte) 0)); this.dhW.a(131092, new b(this, (byte) 0)); this.dhW.a(Integer.MAX_VALUE, new c(this, (byte) 0)); ((com.tencent.mm.plugin.chatroom.b.b) g.l(com.tencent.mm.plugin.chatroom.b.b.class)).Ga().c(this.jtC); ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().a(this.jtB); ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FW().a(this.jtA); com.tencent.mm.sdk.e.j.a aVar = this.jtD; if (com.tencent.mm.am.b.dYB != null) { com.tencent.mm.am.b.dYB.a(aVar); } this.jtG.J(600000, 600000); this.jtE.cht(); this.jtF.cht(); return true; } catch (Throwable e) { AssertionFailedError assertionFailedError = new AssertionFailedError("Can't find BaseContact.parseBuff method, class prototype has changed."); assertionFailedError.initCause(e); throw assertionFailedError; } } x.i("MicroMsg.FTS.FTS5SearchContactLogic", "Create Fail!"); return false; } protected final boolean BT() { this.jtE.dead(); this.jtF.dead(); this.jtH.SO(); this.jtG.SO(); ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().b(this.jtB); ((com.tencent.mm.plugin.chatroom.b.b) g.l(com.tencent.mm.plugin.chatroom.b.b.class)).Ga().d(this.jtC); ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FW().b(this.jtA); com.tencent.mm.sdk.e.j.a aVar = this.jtD; if (com.tencent.mm.am.b.dYB != null) { com.tencent.mm.am.b.dYB.b(aVar); } if (this.jtw != null) { this.jtw.clear(); } if (this.jtv != null) { this.jtv.clear(); } this.jtu = null; this.dhW = null; return true; } public final String getName() { return "FTS5SearchContactLogic"; } final int a(String str, ab abVar, String[] strArr, byte[] bArr, HashMap<String, ab> hashMap) { int i = 0; String str2 = abVar.field_nickname; String av = d.av(str2, false); String av2 = d.av(str2, true); long j = 0; long Cq = this.iXo.Cq(str); StringBuffer stringBuffer = new StringBuffer(); if (strArr != null) { j = (long) strArr.length; HashMap hashMap2 = new HashMap(); com.tencent.mm.i.a.a.a aVar = new com.tencent.mm.i.a.a.a(); try { aVar.aG(bArr); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.FTS.FTS5SearchContactLogic", e, "parse chatroom data", new Object[0]); } Iterator it = aVar.dav.iterator(); while (it.hasNext()) { com.tencent.mm.i.a.a.b bVar = (com.tencent.mm.i.a.a.b) it.next(); if (!bi.oW(bVar.daA)) { hashMap2.put(bVar.userName, bVar.daA); } } int length = strArr.length; int i2 = 0; while (true) { int i3 = i2; if (i3 >= length) { break; } String str3 = strArr[i3]; ab abVar2 = (ab) hashMap.get(str3); if (abVar2 != null) { String str4 = abVar2.field_conRemark; String str5 = abVar2.field_nickname; String av3 = d.av(str4, false); String av4 = d.av(str4, true); stringBuffer.append(bi.aG(str4, " ")).append("‌"); stringBuffer.append(bi.aG(av3, " ")).append("‌"); stringBuffer.append(bi.aG(av4, " ")).append("‌"); str4 = d.av(str5, false); av3 = d.av(str5, true); stringBuffer.append(bi.aG(str5, " ")).append("‌"); stringBuffer.append(bi.aG(str4, " ")).append("‌"); stringBuffer.append(bi.aG(av3, " ")).append("‌"); stringBuffer.append(bi.aG((String) hashMap2.get(str3), " ")).append("‌"); C(abVar2); stringBuffer.append(bi.aG(abVar2.csT, " ")).append("‌"); stringBuffer.append(bi.aG(d.cS(str3, abVar2.wM()), " ")).append("‌"); stringBuffer.append("​"); } i2 = i3 + 1; } } if (!bi.oW(str2)) { this.jtu.a(131075, 5, j, str, Cq, str2); if (bi.oW(av)) { i = 1; } else { this.jtu.a(131075, 6, j, str, Cq, av); i = 2; } if (!bi.oW(av2)) { this.jtu.a(131075, 7, j, str, Cq, av2); i++; } } if (stringBuffer.length() <= 0) { return i; } stringBuffer.setLength(stringBuffer.length() - 1); this.jtu.a(131075, 38, j, str, Cq, stringBuffer.toString()); return i + 1; } public final int i(String str, String[] strArr) { int simpleQueryForLong; String[] strArr2 = (String[]) this.jtx.get(str); this.jtu.beginTransaction(); if (strArr2 == null) { this.jtu.CK(str); simpleQueryForLong = ((int) this.jtu.jvg.simpleQueryForLong()) + 0; if (strArr != null) { this.jtu.j(str, strArr); this.jtx.put(str, strArr); simpleQueryForLong += strArr.length; } } else if (strArr == null) { this.jtu.CK(str); simpleQueryForLong = ((int) this.jtu.jvg.simpleQueryForLong()) + 0; this.jtx.remove(str); } else { HashSet hashSet = new HashSet(Arrays.asList(strArr2)); int i = 0; for (String str2 : strArr) { if (!hashSet.remove(str2)) { com.tencent.mm.plugin.fts.c.a aVar = this.jtu; aVar.jva.bindString(1, str); aVar.jva.bindString(2, str2); aVar.jva.execute(); i++; } } Iterator it = hashSet.iterator(); while (true) { simpleQueryForLong = i; if (!it.hasNext()) { break; } String str3 = (String) it.next(); com.tencent.mm.plugin.fts.c.a aVar2 = this.jtu; aVar2.jvb.bindString(1, str); aVar2.jvb.bindString(2, str3); aVar2.jvb.execute(); i = simpleQueryForLong + 1; } this.jtx.put(str, strArr); } this.jtu.commit(); return simpleQueryForLong; } final void C(ab abVar) { try { this.jtz.invoke(abVar, new Object[0]); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.FTS.FTS5SearchContactLogic", e, "Failed parsing RContact LVBuffer.", new Object[0]); } } static boolean CE(String str) { if (bi.oW(str) || str.endsWith("@stranger") || str.endsWith("@qqim") || str.endsWith("@app") || str.startsWith("fake_")) { return false; } return true; } static boolean D(ab abVar) { if ((abVar.isHidden() && !"notifymessage".equals(abVar.field_username)) || abVar.BA() || abVar.field_deleteFlag != 0) { return false; } if (com.tencent.mm.l.a.gd(abVar.field_type) || (!abVar.Bz() && !abVar.ckW())) { return true; } return false; } final boolean E(ab abVar) { String str = abVar.field_username; if (!D(abVar) || !CE(str)) { return false; } if (com.tencent.mm.l.a.gd(abVar.field_type)) { return true; } if (abVar.Bz() || abVar.ckW() || !this.iXo.Cp(str)) { return false; } return true; } final int F(ab abVar) { byte[] blob; if (!s.fq(abVar.field_username)) { return G(abVar); } String format = String.format("SELECT memberlist, roomdata FROM %s WHERE chatroomname = ?", new Object[]{"chatroom"}); Cursor h = this.iXo.h(format, new String[]{abVar.field_username}); CharSequence string; try { if (h.moveToNext()) { string = h.getString(0); blob = h.getBlob(1); } else { blob = null; string = null; } if (h != null) { h.close(); } if (bi.oW(string) || blob == null) { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "error chatroom data %s", new Object[]{abVar.field_username}); if (i(abVar.field_username, null) <= 0) { return 0; } x.i("MicroMsg.FTS.FTS5SearchContactLogic", "updateChatroomMember %s %d", new Object[]{abVar.field_username, Integer.valueOf(i(abVar.field_username, null))}); return 0; } String[] split = c$a.jqy.split(string); Arrays.sort(split, new 9(this)); if (i(abVar.field_username, split) > 0) { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "updateChatroomMember %s %d", new Object[]{abVar.field_username, Integer.valueOf(i(abVar.field_username, split))}); } HashMap hashMap = new HashMap(); Cursor h2 = this.iXo.h("SELECT rowid, username, alias, conRemark, nickname , lvbuff FROM rcontact WHERE username IN " + d.v(split) + ";", null); while (h2.moveToNext()) { try { ab abVar2 = new ab(); abVar2.dhP = h2.getLong(0); abVar2.setUsername(h2.getString(1)); abVar2.du(h2.getString(2)); abVar2.dv(h2.getString(3)); abVar2.dx(h2.getString(4)); abVar2.B(h2.getBlob(5)); hashMap.put(abVar2.field_username, abVar2); } finally { if (h2 != null) { h2.close(); } } } return a(abVar.field_username, abVar, split, blob, hashMap); } catch (Throwable th) { if (h != null) { h.close(); } String[] split2 = c$a.jqy.split(string); Arrays.sort(split2, new 9(this)); if (i(abVar.field_username, split2) > 0) { x.i("MicroMsg.FTS.FTS5SearchContactLogic", "updateChatroomMember %s %d", new Object[]{abVar.field_username, Integer.valueOf(i(abVar.field_username, split2))}); } HashMap hashMap2 = new HashMap(); Cursor h22 = this.iXo.h("SELECT rowid, username, alias, conRemark, nickname , lvbuff FROM rcontact WHERE username IN " + d.v(split2) + ";", null); while (h22.moveToNext()) { try { ab abVar22 = new ab(); abVar22.dhP = h22.getLong(0); abVar22.setUsername(h22.getString(1)); abVar22.du(h22.getString(2)); abVar22.dv(h22.getString(3)); abVar22.dx(h22.getString(4)); abVar22.B(h22.getBlob(5)); hashMap2.put(abVar22.field_username, abVar22); } finally { if (h22 != null) { h22.close(); } } } return a(abVar.field_username, abVar, split2, blob, hashMap2); } } final int G(ab abVar) { int i; int i2; String str; int i3; String str2; String str3; String str4; String str5; long j = abVar.dhP; String str6 = abVar.field_username; String wM = abVar.wM(); String str7 = abVar.field_nickname; String av = d.av(str7, false); String av2 = d.av(str7, true); String str8 = abVar.field_conRemark; String av3 = d.av(str8, false); String av4 = d.av(str8, true); String str9 = abVar.csT; String str10 = abVar.field_contactLabelIds; String str11 = abVar.csZ; int i4 = abVar.field_verifyFlag; String str12 = ""; long currentTimeMillis = System.currentTimeMillis(); if ((i4 & ab.ckY()) != 0) { i4 = 131076; i = 0; str12 = bi.c(((com.tencent.mm.api.h) g.l(com.tencent.mm.api.h.class)).cC(str6), "​"); } else if (ab.XR(str6)) { i4 = 131081; i = 0; } else { currentTimeMillis = this.iXo.Cq(str6); if (str10 == null || str10.length() <= 0) { i = 0; i4 = WXMediaMessage.MINI_PROGRAM__THUMB_LENGHT; } else { if (str10 != null) { Object substring; if (str10.endsWith("\u0000")) { substring = str10.substring(0, str10.length() - 1); } else { String substring2 = str10; } if (substring2.length() == 0) { i2 = 0; } else { List arrayList; String[] split = c$a.jqF.split(substring2); List list; if (split.length != 0) { arrayList = new ArrayList(split.length); for (String str13 : split) { arrayList.add(Long.valueOf(bi.getLong(str13, 0))); } list = arrayList; } else { list = null; } arrayList = (List) this.jty.get(str6); if (arrayList == null) { this.jtu.CI(str6); if (!(list == null || list.isEmpty())) { this.jtu.h(str6, list); this.jty.put(str6, list); } } else if (list == null || list.isEmpty()) { this.jtu.CI(str6); this.jty.remove(str6); } else { long longValue; com.tencent.mm.plugin.fts.c.a aVar; HashSet hashSet = new HashSet(arrayList); for (Long longValue2 : list) { longValue = longValue2.longValue(); if (!hashSet.remove(Long.valueOf(longValue))) { aVar = this.jtu; aVar.jvd.bindString(1, str6); aVar.jvd.bindLong(2, longValue); aVar.jvd.execute(); } } Iterator it = hashSet.iterator(); while (it.hasNext()) { longValue = ((Long) it.next()).longValue(); aVar = this.jtu; aVar.jve.bindString(1, str6); aVar.jve.bindLong(2, longValue); aVar.jve.execute(); } this.jty.put(str6, list); } arrayList = this.iXo.Cr(substring2); if (arrayList.size() == 0) { i2 = 0; } else { this.jtu.a(WXMediaMessage.MINI_PROGRAM__THUMB_LENGHT, 11, j, str6, currentTimeMillis, bi.c(arrayList, "​")); i2 = 1; } } } else { i2 = 0; } i = i2 + 0; i4 = WXMediaMessage.MINI_PROGRAM__THUMB_LENGHT; } } String cS = d.cS(str6, wM); if (cS == null || cS.length() == 0) { i3 = i; } else { this.jtu.a(i4, 15, j, str6, currentTimeMillis, cS); i3 = i + 1; } if (str8 == null || str8.length() == 0) { str13 = null; str2 = null; str10 = av2; str3 = av; cS = str7; str4 = null; } else { str10 = av4; str3 = av3; cS = str8; str2 = av2; str13 = av; str4 = str7; } if (!(cS == null || cS.length() == 0)) { if (cS.equalsIgnoreCase(str3)) { av4 = null; } else { av4 = str3; } if (av4 == null || av4.length() == 0 || av4.equalsIgnoreCase(str10)) { str5 = null; } else { str5 = str10; } this.jtu.a(i4, 1, j, str6, currentTimeMillis, cS); if (!(av4 == null || av4.length() == 0)) { this.jtu.a(i4, 2, j, str6, currentTimeMillis, av4); } if (!(str5 == null || str5.length() == 0)) { this.jtu.a(i4, 3, j, str6, currentTimeMillis, str5); } i3 += 3; } if (str4 == null || str4.length() == 0) { i = i3; } else { if (str4.equalsIgnoreCase(str13)) { str13 = null; } if (str13 == null || str13.length() == 0 || str13.equalsIgnoreCase(str2)) { str5 = null; } else { str5 = str2; } this.jtu.a(i4, 5, j, str6, currentTimeMillis, str4); if (!(str13 == null || str13.length() == 0)) { this.jtu.a(i4, 6, j, str6, currentTimeMillis, str13); } if (!(str5 == null || str5.length() == 0)) { this.jtu.a(i4, 7, j, str6, currentTimeMillis, str5); } i = i3 + 3; } if (str9 != null && str9.length() > 0) { this.jtu.a(i4, 4, j, str6, currentTimeMillis, str9); i++; } if (i4 == WXMediaMessage.MINI_PROGRAM__THUMB_LENGHT) { if (bi.oW(str11)) { Cursor h = this.iXo.h("SELECT moblie FROM addr_upload2 WHERE username=?;", new String[]{str6}); if (h.moveToFirst()) { this.jtu.a(i4, 16, j, str6, currentTimeMillis, h.getString(0)); i2 = i + 1; } else { i2 = i; } h.close(); i = i2; } else { this.jtu.a(i4, 16, j, str6, currentTimeMillis, str11.replace(",", "​")); i++; } cS = abVar.getProvince(); if (jtI.contains(cS)) { cS = ""; } if (!(cS == null || cS.length() == 0)) { this.jtu.a(i4, 18, j, str6, currentTimeMillis, cS); i++; } cS = abVar.getCity(); if (!(cS == null || cS.length() == 0)) { this.jtu.a(i4, 17, j, str6, currentTimeMillis, cS); i++; } } if (i4 == 131076 && !bi.oW(str12)) { this.jtu.a(i4, 19, j, str6, currentTimeMillis, str12); i++; cS = d.av(str12, false); if (!bi.oW(cS)) { this.jtu.a(i4, 20, j, str6, currentTimeMillis, cS); i++; } cS = d.av(str12, true); if (!bi.oW(cS)) { this.jtu.a(i4, 21, j, str6, currentTimeMillis, cS); i2 = i + 1; if (i4 != 131081) { return i2 + a(abVar, currentTimeMillis); } return i2; } } i2 = i; if (i4 != 131081) { return i2; } return i2 + a(abVar, currentTimeMillis); } private int a(ab abVar, long j) { String str = abVar.cte; if (bi.oW(str)) { return 0; } com.tencent.mm.openim.a.c cVar = new com.tencent.mm.openim.a.c(); cVar.oE(str); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < cVar.eul.size(); i++) { for (com.tencent.mm.openim.a.c.b oF : ((com.tencent.mm.openim.a.c.a) cVar.eul.get(i)).eum) { str = oF.oF(abVar.field_openImAppid); if (!bi.oW(str)) { stringBuffer.append(str); stringBuffer.append("‌"); } } stringBuffer.append("​"); } if (bi.oW(stringBuffer.toString())) { return 0; } x.i("MicroMsg.FTS.FTS5SearchContactLogic", "buildOpenIMContact %s", new Object[]{stringBuffer.toString()}); this.jtu.a(131081, 51, abVar.dhP, abVar.field_username, j, stringBuffer.toString()); return 1; } static { String[] split = ad.getContext().getString(com.tencent.mm.plugin.fts.h.a.country_others).split(";"); if (split != null) { for (Object add : split) { jtI.add(add); } } } }
package MyFirstApp.AppMessages; import javax.persistence.*; import javax.xml.bind.annotation.*; import java.util.Date; /** * Message class. Path Root.a */ @XmlRootElement @Entity @Table(name = "ROOT_TAB") public class Root { public Integer getId() { return id; } @XmlTransient public void setId(Integer id) { this.id = id; } @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "TIME") private String time = new Date().toString(); @Column(name = "A") private String a; public String getA() { return a; } @XmlElement public void setA(String a) { this.a = a; } }
/* * Copyright (c) 2016. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qianmi.demo.order.config; import com.qianmi.demo.order.CreateOrderSaga; import com.qianmi.demo.order.Order; import com.qianmi.demo.order.OrderCommandHandler; import org.axonframework.commandhandling.model.GenericJpaRepository; import org.axonframework.commandhandling.model.Repository; import org.axonframework.common.jpa.ContainerManagedEntityManagerProvider; import org.axonframework.common.jpa.EntityManagerProvider; import org.axonframework.common.transaction.TransactionManager; import org.axonframework.config.SagaConfiguration; import org.axonframework.eventhandling.EventBus; import org.axonframework.eventhandling.SimpleEventBus; import org.axonframework.eventsourcing.EventSourcingRepository; import org.axonframework.eventsourcing.eventstore.EventStore; import org.axonframework.serialization.Serializer; import org.axonframework.spring.config.AxonConfiguration; import org.axonframework.spring.messaging.unitofwork.SpringTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; @Configuration public class AxonConfig { @Autowired private PlatformTransactionManager transactionManager; @Bean public TransactionManager axonTransactionManager() { return new SpringTransactionManager(transactionManager); } @Bean() public Repository<Order> repository(EventStore eventStore){ return new EventSourcingRepository<>(Order.class, eventStore); } }
package com.wt.jiaduo.controller.pojovalid; // Generated 2018-3-31 10:29:38 by Hibernate Tools 5.2.8.Final import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; /** * XiaomaiYexiubing generated by hbm2java */ public class XiaomaiYexiubingAddValid implements java.io.Serializable { private String place; @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date dateTime; private String serialNumber; private String variety; private String sowingDate; private String growthPeriod; private String fieldArea; private String allfieldConditions; private String checkArea; private String bladeDensity; private String monolithicLeafDensity; private String surveyBladenum; private String onsetBladenum; private String diseasedLeafrate; private String severity; private String diseaseIndex; private String reactive; private Integer userId; private String userName; private String longitude; private String latitude; public XiaomaiYexiubingAddValid() { } public XiaomaiYexiubingAddValid(String place, Date dateTime, String serialNumber, String variety, String sowingDate, String growthPeriod, String fieldArea, String allfieldConditions, String checkArea, String bladeDensity, String monolithicLeafDensity, String surveyBladenum, String onsetBladenum, String diseasedLeafrate, String severity, String diseaseIndex, String reactive, Integer userId, String userName, String longitude, String latitude) { this.place = place; this.dateTime = dateTime; this.serialNumber = serialNumber; this.variety = variety; this.sowingDate = sowingDate; this.growthPeriod = growthPeriod; this.fieldArea = fieldArea; this.allfieldConditions = allfieldConditions; this.checkArea = checkArea; this.bladeDensity = bladeDensity; this.monolithicLeafDensity = monolithicLeafDensity; this.surveyBladenum = surveyBladenum; this.onsetBladenum = onsetBladenum; this.diseasedLeafrate = diseasedLeafrate; this.severity = severity; this.diseaseIndex = diseaseIndex; this.reactive = reactive; this.userId = userId; this.userName = userName; this.longitude = longitude; this.latitude = latitude; } public String getPlace() { return this.place; } public void setPlace(String place) { this.place = place; } public Date getDateTime() { return this.dateTime; } public void setDateTime(Date dateTime) { this.dateTime = dateTime; } public String getSerialNumber() { return this.serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getVariety() { return this.variety; } public void setVariety(String variety) { this.variety = variety; } public String getSowingDate() { return this.sowingDate; } public void setSowingDate(String sowingDate) { this.sowingDate = sowingDate; } public String getGrowthPeriod() { return this.growthPeriod; } public void setGrowthPeriod(String growthPeriod) { this.growthPeriod = growthPeriod; } public String getFieldArea() { return this.fieldArea; } public void setFieldArea(String fieldArea) { this.fieldArea = fieldArea; } public String getAllfieldConditions() { return this.allfieldConditions; } public void setAllfieldConditions(String allfieldConditions) { this.allfieldConditions = allfieldConditions; } public String getCheckArea() { return this.checkArea; } public void setCheckArea(String checkArea) { this.checkArea = checkArea; } public String getBladeDensity() { return this.bladeDensity; } public void setBladeDensity(String bladeDensity) { this.bladeDensity = bladeDensity; } public String getMonolithicLeafDensity() { return this.monolithicLeafDensity; } public void setMonolithicLeafDensity(String monolithicLeafDensity) { this.monolithicLeafDensity = monolithicLeafDensity; } public String getSurveyBladenum() { return this.surveyBladenum; } public void setSurveyBladenum(String surveyBladenum) { this.surveyBladenum = surveyBladenum; } public String getOnsetBladenum() { return this.onsetBladenum; } public void setOnsetBladenum(String onsetBladenum) { this.onsetBladenum = onsetBladenum; } public String getDiseasedLeafrate() { return this.diseasedLeafrate; } public void setDiseasedLeafrate(String diseasedLeafrate) { this.diseasedLeafrate = diseasedLeafrate; } public String getSeverity() { return this.severity; } public void setSeverity(String severity) { this.severity = severity; } public String getDiseaseIndex() { return this.diseaseIndex; } public void setDiseaseIndex(String diseaseIndex) { this.diseaseIndex = diseaseIndex; } public String getReactive() { return this.reactive; } public void setReactive(String reactive) { this.reactive = reactive; } public Integer getUserId() { return this.userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getLongitude() { return this.longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return this.latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } }
package sort; public class SelectionSort { public static void main(String[] args) { int i, j, min, index = 0, temp; int[] arr = { 1, 10, 5, 8, 7, 6, 4, 3, 2, 9 }; for (i = 0; i < 10; i++) { min = 999; for (j = i; j < 10; j++) { if (min > arr[j]) { min = arr[j]; index = j; } } temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; } for (i = 0; i < 10; i++) { System.out.print(arr[i] + " "); } } }
package com.cszjkj.aisc.tms_user; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableTransactionManagement(proxyTargetClass = true) @ComponentScan(basePackages = {"com.cszjkj.aisc.tms_user.*"}) @MapperScan({"com.cszjkj.aisc.tms_user.mapper"}) // 可逗号分隔的多个 public class TmsUserApplication { public static void main(String[] args) { System.out.println("app 1"); SpringApplication.run(TmsUserApplication.class, args); System.out.println("app 2"); } }
package com.petersoft.mgl.leltar; public class TranzakcioRaktar extends Tranzakcio{ private RaktarHely raktarHelyHova; }
/** * */ package site.com.google.anywaywrite.component.menu; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JMenuItem; import site.com.google.anywaywrite.action.BgAreaActionEnableControlPlugin; import site.com.google.anywaywrite.action.BgAreaRemoveAction; import site.com.google.anywaywrite.action.BgRemoveActionSuccessHook; import site.com.google.anywaywrite.component.gui.BgAreaLabel; import site.com.google.anywaywrite.component.gui.BgAreaLabelPane; import site.com.google.anywaywrite.component.gui.BgTempAreaInternalFrame; import site.com.google.anywaywrite.item.card.BgCardItem; import site.com.google.anywaywrite.util.control.BgAreaControlUtil; /** * @author kitajima * */ public class BgCreateDetailAllMoveActionMenu implements BgCreateActionMenu { private BgAreaLabel fromArea; private BgAreaLabelPane labelPane; private BgTempAreaInternalFrame frame; private JDialog dialog; private BgCreateDetailAllMoveActionMenu(BgAreaLabel fromArea, BgAreaLabelPane labelPane, BgTempAreaInternalFrame frame, JDialog dialog) { setFromArea(fromArea); setLabelPane(labelPane); setFrame(frame); setDialog(dialog); } public static BgCreateDetailAllMoveActionMenu newInstance( BgAreaLabel fromArea, BgAreaLabelPane labelPane, BgTempAreaInternalFrame frame, JDialog dialog) { return new BgCreateDetailAllMoveActionMenu(fromArea, labelPane, frame, dialog); } private final BgAreaLabel getFromArea() { return fromArea; } private final void setFromArea(BgAreaLabel fromArea) { this.fromArea = fromArea; } private final BgAreaLabelPane getLabelPane() { return labelPane; } private final void setLabelPane(BgAreaLabelPane labelPane) { this.labelPane = labelPane; } private final void setFrame(BgTempAreaInternalFrame frame) { this.frame = frame; } private final BgTempAreaInternalFrame getFrame() { return this.frame; } private final JDialog getDialog() { return dialog; } private final void setDialog(JDialog dialog) { this.dialog = dialog; } @Override public BgMenuItem createActionMenu(BgAreaLabel area) { JMenu allMove = new JMenu("allMove"); Iterator<BgAreaLabel> it = getLabelPane().getAreaSet().iterator(); while (it.hasNext()) { final BgAreaLabel al = it.next(); if (getFromArea().getAreaName().equals(al.getAreaName()) || "temp".equals(al.getAreaName())) { continue; } BgAreaRemoveAction action = BgAreaRemoveAction.namedInstance(area, al.getAreaName()); action.setRemoveActionSuccessHook(new BgRemoveActionSuccessHook() { @Override public void actionDone(BgAreaLabel fromArea, List<BgCardItem> moveCards, List<Integer> moveIndexes) { BgAreaControlUtil.moveAll(getFromArea(), al); getDialog().setTitle( getFromArea().getAreaName() + " [" + getFromArea().getCards().size() + "]"); getDialog().dispose(); if (getFrame() != null) { if (getFromArea().getCards().size() > 0) { getFrame().setVisible(true); } else { getFrame().setVisible(false); } } } }); action .setEnableControlPlugin(new BgAreaActionEnableControlPlugin() { @Override public boolean isEnable() { List<BgCardItem> cards = new ArrayList<BgCardItem>( al.getCards()); for (BgCardItem card : getFromArea().getCards()) { BgCardItem item = BgCardItem.newInstance(card .getInfo()); item.setDirection(al.getAreaLayout() .getInitialDirection()); item.setSide(al.getAreaLayout() .getInitialSide()); cards.add(item); } if (al.getAreaLayout().verify(cards) != null) { return false; } return true; } }); JMenuItem item = new JMenuItem(action); allMove.add(item); } return BgMenuItem.newInstance(allMove); } }
package com.habiture; import java.util.List; /** * Created by GawinHsu on 4/22/15. */ public class StubPostSwearFailed extends StubLoginSuccessfully { @Override public boolean httpPostDeclaration(int uid, String frequency, String declaration, String punishment, String goal, String do_it_time) { return false; } }
package com.lvym.config; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; import org.springframework.amqp.support.ConsumerTagStrategy; import org.springframework.amqp.support.converter.ContentTypeDelegatingMessageConverter; import org.springframework.amqp.support.converter.DefaultJackson2JavaTypeMapper; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.lvym.adapter.MessageDelegate; import com.lvym.covert.ImageMessageConverter; import com.lvym.covert.PDFMessageConverter; import com.lvym.covert.TextMessageConverter; @Configuration @ComponentScan({"com.lvym.*"}) public class RabbitMQConfig { @Bean public ConnectionFactory factory() { CachingConnectionFactory factory=new CachingConnectionFactory(); factory.setAddresses("192.168.168.128:5672"); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); return factory; } @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory factory) { RabbitAdmin rabbitAdmin=new RabbitAdmin(factory); rabbitAdmin.setAutoStartup(true); return rabbitAdmin; } /** * 针对消费者配置 * 1. 设置交换机类型 * 2. 将队列绑定到交换机 FanoutExchange: 将消息分发到所有的绑定队列,无routingkey的概念 HeadersExchange :通过添加属性key-value匹配 DirectExchange:按照routingkey分发到指定队列 TopicExchange:多关键字匹配 */ @Bean public TopicExchange exchange01() { return new TopicExchange("topic01", true, false); } @Bean public Queue queue01() { return new Queue("queue01", true); } @Bean public Binding binding01() { return BindingBuilder.bind(queue01()).to(exchange01()).with("spring.*"); } @Bean public TopicExchange exchange02() { return new TopicExchange("topic02", true, false); } @Bean public Queue queue02() { return new Queue("queue02", true); } @Bean public Binding binding02() { return BindingBuilder.bind(queue02()).to(exchange02()).with("rabbit.*"); } @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory factory) { return new RabbitTemplate(factory); } @Bean public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory factory) { SimpleMessageListenerContainer container=new SimpleMessageListenerContainer(factory); container.setQueues(queue01(),queue02());//监控多个队列 container.setConcurrentConsumers(1);//消费者数量 container.setMaxConcurrentConsumers(6);//最大消费数 container.setDefaultRequeueRejected(false);//是否重回队列 container.setAcknowledgeMode(AcknowledgeMode.AUTO);//签收策略 container.setConsumerTagStrategy(new ConsumerTagStrategy() { @Override public String createConsumerTag(String queue) { // TODO Auto-generated method stub 标签策略 return queue+"-"+UUID.randomUUID().toString(); } }); /* container.setMessageListener(new ChannelAwareMessageListener() { @Override public void onMessage(Message message, Channel channel) throws Exception { String msg=new String(message.getBody()); System.err.println("----消费:--------"+msg); } });*/ /** * 1 适配器方式. 默认是有自己的方法名字的:handleMessage // 可以自己指定一个方法的名字: consumeMessage // 也可以添加一个转换器: 从字节数组转换为String*/ /* MessageListenerAdapter adapter=new MessageListenerAdapter(new MessageDelegate()); adapter.setDefaultListenerMethod("consumeMessage"); adapter.setMessageConverter(new TextMessageConverter()); container.setMessageListener(adapter); */ /** * 2 适配器方式: 我们的队列名称 和 方法名称 也可以进行一一的匹配 */ /* Map<String,String> queueOrTagToMethodName=new HashMap<String, String>(); queueOrTagToMethodName.put("queue01","method1"); queueOrTagToMethodName.put("queue02","method2"); MessageListenerAdapter adapter=new MessageListenerAdapter(new MessageDelegate()); adapter.setMessageConverter(new TextMessageConverter()); adapter.setQueueOrTagToMethodName(queueOrTagToMethodName); container.setMessageListener(adapter); */ // 1.1 支持json格式的转换器 /* MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageDelegate()); adapter.setDefaultListenerMethod("consumeMessage"); Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter(); adapter.setMessageConverter(jackson2JsonMessageConverter); container.setMessageListener(adapter); */ // 1.2 DefaultJackson2JavaTypeMapper & Jackson2JsonMessageConverter 支持java对象转换 /* MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageDelegate()); adapter.setDefaultListenerMethod("consumeMessage"); Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter(); DefaultJackson2JavaTypeMapper javaTypeMapper = new DefaultJackson2JavaTypeMapper(); jackson2JsonMessageConverter.setJavaTypeMapper(javaTypeMapper); adapter.setMessageConverter(jackson2JsonMessageConverter); container.setMessageListener(adapter);*/ //1.3 DefaultJackson2JavaTypeMapper & Jackson2JsonMessageConverter 支持java对象多映射转换 /** MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageDelegate()); adapter.setDefaultListenerMethod("consumeMessage"); Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter(); DefaultJackson2JavaTypeMapper javaTypeMapper = new DefaultJackson2JavaTypeMapper(); Map<String, Class<?>> idClassMapping = new HashMap<String, Class<?>>(); idClassMapping.put("order", com.lvym.entity.Order.class); idClassMapping.put("packaged", com.bfxy.spring.entity.Packaged.class); javaTypeMapper.setIdClassMapping(idClassMapping); jackson2JsonMessageConverter.setJavaTypeMapper(javaTypeMapper); adapter.setMessageConverter(jackson2JsonMessageConverter); container.setMessageListener(adapter); */ //1.4 ext convert MessageListenerAdapter adapter = new MessageListenerAdapter(new MessageDelegate()); adapter.setDefaultListenerMethod("consumeMessage"); //全局的转换器: ContentTypeDelegatingMessageConverter convert = new ContentTypeDelegatingMessageConverter(); TextMessageConverter textConvert = new TextMessageConverter(); convert.addDelegate("text", textConvert); convert.addDelegate("html/text", textConvert); convert.addDelegate("xml/text", textConvert); convert.addDelegate("text/plain", textConvert); Jackson2JsonMessageConverter jsonConvert = new Jackson2JsonMessageConverter(); convert.addDelegate("json", jsonConvert); convert.addDelegate("application/json", jsonConvert); ImageMessageConverter imageConverter = new ImageMessageConverter(); convert.addDelegate("image/png", imageConverter); convert.addDelegate("image", imageConverter); PDFMessageConverter pdfConverter = new PDFMessageConverter(); convert.addDelegate("application/pdf", pdfConverter); adapter.setMessageConverter(convert); container.setMessageListener(adapter); return container; } }
package com.example.matthewtimmons.guessthatsong.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.matthewtimmons.guessthatsong.Activities.LevelSelectActivity; import com.example.matthewtimmons.guessthatsong.Models.Level; import com.example.matthewtimmons.guessthatsong.R; import java.util.List; public class LevelsAdapter extends BaseAdapter { Context context; List<Level> levels; public LevelsAdapter(Context context, List<Level> levels) { this.context = context; this.levels = levels; } @Override public int getCount() { return levels.size(); } @Override public Object getItem(int i) { return levels.get(i); } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { Level level = levels.get(i); if (view == null) { final LayoutInflater layoutInflater = LayoutInflater.from(context); view = layoutInflater.inflate(R.layout.viewholder_level, null); } TextView levelNumberTextView = view.findViewById(R.id.level_number); ImageView checkboxImageView = view.findViewById(R.id.green_checkmark_icon_image_view); levelNumberTextView.setText("" + (i + 1)); if (level.getUserHasBeatenThisLevel()) { checkboxImageView.setVisibility(View.VISIBLE); } return view; } }
package com.onplan.connector; import com.onplan.service.HistoricalPriceServiceRemote; public interface HistoricalPriceService extends HistoricalPriceServiceRemote { }
package game; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class Game extends JPanel implements Runnable, KeyListener{ //http://www.gameart2d.com/ private static final long serialVersionUID = 1L; int xOffset = 0; int yOffset = 0; public static final int WIDTH = 600; public static final int HEIGHT = WIDTH / 12 * 9; public static final String NAME = "Platformer"; public boolean running = false; public int tickCount = 0; private BufferedImage image; Graphics2D g; JFrame frame; private TileMap tileMap; private Player player; private Menu menu; private MouseInput mouseInput; public static enum STATE { MENU, LEVEL, SETTINGS, ABOUT, GAME, DEATH, WIN }; public static STATE State = STATE.MENU; public Game(){ setMinimumSize(new Dimension(WIDTH, HEIGHT)); setMaximumSize(new Dimension(WIDTH, HEIGHT)); setPreferredSize(new Dimension(WIDTH, HEIGHT)); frame = new JFrame(NAME); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(this, BorderLayout.CENTER); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); init(); requestFocus(); }; public synchronized void start() { running = true; this.addKeyListener(this); new Thread(this).start(); } public synchronized void stop() { running = false; } public void run() { long lastTime = System.nanoTime(); double nsPerTick = 1000000000D / 60D; int frames = 0; int ticks = 0; long lastTimer = System.currentTimeMillis(); double delta = 0; while (running) { long now = System.nanoTime(); delta += (now - lastTime) / nsPerTick; lastTime = now; boolean shouldRender = true; while (delta >= 1) { ticks++; tick(); delta -= 1; shouldRender = true; } try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } if (shouldRender) { frames++; render(); } if (System.currentTimeMillis() - lastTimer >= 1000) { lastTimer += 1000; System.out.println(frames + "," + ticks); frames = 0; ticks = 0; } } } public void init(){ tileMap = new TileMap("levels/level1.txt", 40); player = new Player(tileMap); player.setX(100); player.setY(100); menu = new Menu(); mouseInput = new MouseInput(); image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) image.getGraphics(); this.addMouseListener(mouseInput); this.addMouseMotionListener(mouseInput); } public void tick(){ tickCount++; if(State==STATE.GAME){ tileMap.tick(); player.tick(); } else if(State==STATE.MENU){ menu.tick(); } } @SuppressWarnings("static-access") public void render(){ Graphics g2 = getGraphics(); g2.drawImage(image, 0, 0, null); g2.dispose(); if(State==STATE.GAME){ tileMap.render(g); player.render(g); g.setColor(Color.RED); Font fnt0 = new Font("arial", Font.BOLD, 18); g.setFont(fnt0); g.drawString("Coins: " + player.coins + "/" + tileMap.totalCoins, 30, 30); } else if(State==STATE.MENU){ menu.render(g); } else if(State==STATE.DEATH){ Font fnt1 = new Font("arial", Font.BOLD, 30); g.setFont(fnt1); g.drawString("YOU DIED!", 250, 200); } else if(State==STATE.WIN){ Font fnt1 = new Font("arial", Font.BOLD, 30); g.setFont(fnt1); g.drawString("YOU WON!", 250, 200); } } public static void main(String[] args){ new Game().start(); } @Override public void keyPressed(KeyEvent key) { int code = key.getKeyCode(); if(code==KeyEvent.VK_LEFT){ player.setLeft(true); } if(code==KeyEvent.VK_RIGHT){ player.setRight(true); } if(code==KeyEvent.VK_UP){ player.setJumping(); } if(code==KeyEvent.VK_ESCAPE){ State = STATE.MENU; } } @Override public void keyReleased(KeyEvent key) { int code = key.getKeyCode(); if(code==KeyEvent.VK_LEFT){ player.setLeft(false); } if(code==KeyEvent.VK_RIGHT){ player.setRight(false); } } @Override public void keyTyped(KeyEvent key) { } }
package com.se.details.util; public class PDMicroserviceConstants { public static class AsyncConfig { private AsyncConfig() { } public static final String MAX_NUMBER_OF_THREADS = "max.number.of.threads"; public static final String NUMBER_OF_THREADS = "number.of.threads"; } public static class RequestResponseFormat { private RequestResponseFormat() { } public static final String ACCEPT_HEADER = "Accept"; public static final String XML_FORMAT = "xml"; public static final String DEFAULT_FORMAT = "json"; public static final String REQUEST_FORMAT = "fmt"; } public static class PararmeterNames { private PararmeterNames() { } public static final String COM_IDS = "comIds"; public static final String CATEGORIES = "categories"; } public static class ActorNames { private ActorNames() { } public static final String PART_DETAILS_ACTOR = "partdetailsActor"; public static final String PARAMETRICFEATURES = "ParametricFeatures"; public static final String SUMMARYFEATURES = "SummaryFeatures"; public static final String RISKFEATURES = "RiskFeatures"; } public static class LCForecastSolrFields { public static final String FILTERED_FIELDS = "COM_ID,LIFECYCLE_STATUS,YEARS_EOL,LIFECYCLE_RISK,AVAILABILITY_RISK,NUMBER_OF_OTHER_SOURCES"; public static final String COMID = "COM_ID"; public static final String LIFECYCLE_STATUS = "LIFECYCLE_STATUS"; public static final String YEARS_EOL = "YEARS_EOL"; public static final String LIFECYCLE_RISK = "LIFECYCLE_RISK"; public static final String AVAILABILITY_RISK = "AVAILABILITY_RISK"; public static final String NUMBER_OF_OTHER_SOURCES = "NUMBER_OF_OTHER_SOURCES"; private LCForecastSolrFields() { } } public static class TaxonomySolrFields { public static final String TAX_PL_TYPE_SORT = "PL_TYPE_SORT"; public static final String TAX_PL_TYPE_NAME = "TYPENAME"; public static final String TAX_MAIN_NAME = "MAINNAME"; public static final String TAX_MAIN_ID = "MAINID"; public static final String TAX_SUB_NAME = "SUBNAME"; public static final String TAX_SUB_ID = "SUBID"; public static final String TAX_PL_ID = "PLID"; public static final String TAX_SUBSEARCHABLE_FLAG = "SUBSEARCHABLEFLAG"; public static final String TAX_MAINSEARCHABLE_FLAG = "MAINSEARCHABLEFLAG"; public static final String TAX_PL_NAME = "PLNAME"; public static final String HCOLNAME = "HCOLNAME"; public static final String FEATURENAME = "FEATURENAME"; private TaxonomySolrFields() { } } public static class ParametricSolrFields { public static final String PART_ID = "PART_ID"; public static final String UNIT = "UNIT"; public static final String HCOLNAME = "HCOLNAME"; public static final String FEATURENAME = "FEATURENAME"; public static final String FILTERD_FIELDS = "PART_ID,PL_NAME,*_FULL"; public static final String FULL_VALUE = "_FULL"; public static final String VALUE = "_VALUE"; private ParametricSolrFields() { } } public static class RiksFeaturesNames { public static final String INVENTORYRISK = "InventoryRisk"; public static final String LIFECYCLERISK = "LifecycleRisk"; public static final String YEARSTOENDOFLIFE = "EstimatedYearsToEOL"; public static final String OTHERSOURCES = "OtherSources"; public static final String AVAILABILITYRISK = "availabiltyRisk"; public static final String LIFECYCLESTATUS = "lifecycleStatus"; private RiksFeaturesNames() { } } public static class GSheetStatisticsFeaturesNames { public static final String SOLESOURCE = "SoleSource"; public static final String SINGLESOURCE = "SingleSource"; public static final String MULTISOURCE = "MultiSource"; private GSheetStatisticsFeaturesNames() { } } public static class PartDetailsEndPointResponseColumns { private PartDetailsEndPointResponseColumns() { } public static final String STATUS = "Status"; public static final String SERVICE_TIME = "ServiceTime"; public static final String STATISTICS = "Statistics"; public static final String PART_FEATURES = "PartsFeatures"; } public static class Jackson { private Jackson() { } public static final String PART_DETAILS_FILTER_NAME = "partDetailsFilter"; } public static class SummaryCoreFields { private SummaryCoreFields() { } public static final String COO = "COO"; public static final String HTSUSA = "HTSUSA"; } public static class SummaryFeatureName { private SummaryFeatureName() { } public static final String COO = "CountryOfOrigin"; public static final String HTSUSA = "HTSUSA"; } }
package aplicacionusuario.datos; import java.util.ArrayList; public class Liga { private String nombre; private String clave; private ArrayList<Usuario> listausuarios; public Liga(String nombre, String clave) { super(); this.nombre = nombre; this.clave = clave; this.listausuarios = new ArrayList<>(); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public ArrayList<Usuario> getListausuarios() { return listausuarios; } public void setListausuarios(ArrayList<Usuario> listausuarios) { this.listausuarios = listausuarios; } public Liga() { } public void entrarLiga(Usuario u) { listausuarios.add(u); } }