text
stringlengths
10
2.72M
package com.sailaminoak.saiii; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.os.Handler; import android.os.SystemClock; import android.provider.MediaStore; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.ismaeldivita.chipnavigation.ChipNavigationBar; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import static android.app.Activity.RESULT_OK; /** * A simple {@link Fragment} subclass. * Use the {@link NewNote#newInstance} factory method to * create an instance of this fragment. */ public class NewNote extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private int someStateValue; private final String SOME_VALUE_KEY = "someValueToSave"; boolean first=true; LinearLayout linearLayout; int h=90; int helperForTime=88; SQLHelper sqlHelper; int specialId=40000; public String editCollectorId=""; LinearLayout layoutForWrite; EditText editText; SharedPreferences sharedPreferences; private static final int IMAGE_PICKER_CODE=1000; private static final int PERMISSION_CODE=1001; String realFilename=""; boolean noWordWatcher=true; int realWidth=0; int realHeight=0; int count=0; RelativeLayout relativeLayout; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; View view; int textColor; String nickiminaj=""; public NewNote() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment NewNote. */ // TODO: Rename and change types and number of parameters public static NewNote newInstance(String param1, String param2) { NewNote fragment = new NewNote(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public void onSaveInstanceState(Bundle outState) { outState.putInt(SOME_VALUE_KEY, someStateValue); super.onSaveInstanceState(outState); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((AppCompatActivity) getActivity()).getSupportActionBar().hide(); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @RequiresApi(api = Build.VERSION_CODES.Q) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view=inflater.inflate(R.layout.fragment_content,container,false); sharedPreferences =this.getActivity().getSharedPreferences("Saii", Context.MODE_PRIVATE); int num=sharedPreferences.getInt("BackgroundColor",0); textColor=sharedPreferences.getInt("textColor",R.color.colorAccent); final int sdk = android.os.Build.VERSION.SDK_INT; long currentTime = Calendar.getInstance().getTimeInMillis(); sqlHelper=new SQLHelper(getActivity(),"db.sqlite",null,2); realFilename="Tables"+currentTime; Toast.makeText(getActivity(),"New Note Created",Toast.LENGTH_SHORT).show(); try{ boolean a=sqlHelper.queryData("CREATE TABLE " + realFilename + "( name TEXT ,image BLOB, ids INTEGER )"); }catch (Exception e){ Toast.makeText(getActivity(),e+" error ",Toast.LENGTH_SHORT).show(); } view = inflater.inflate(R.layout.fragment_new_note, container, false); linearLayout = view.findViewById(R.id.linearLayout); RelativeLayout backgroundImage =view.findViewById(R.id.backgroundImage); try{ switch (num){ case 0: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 1: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 2: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 3: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 4: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 5: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 6: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; case 7: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); break; default: backgroundImage.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.girl)); Toast.makeText(getActivity(),"Not Understanding Background"+num,Toast.LENGTH_SHORT).show(); break; } }catch ( Exception e){ Toast.makeText(getActivity(),"background error and stick with oldpaper"+num,Toast.LENGTH_SHORT).show(); } byte[] b612 = new byte[0]; String android_id = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a"); String formattedDate = df.format(c.getTime()); nickiminaj="asdfjkl;yokelaminoak,,,"+android_id+",,,"+formattedDate+",,,"+getDeviceName(); sqlHelper.insertData(nickiminaj,b612,9999,realFilename); addEditText(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); first=false; BottomNavigationView bottomNavigationView=view.findViewById(R.id.chipNavigationView); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_add: FragmentTransaction tr = getFragmentManager().beginTransaction(); tr.replace(R.id.container,new NewNote(),"newnote"); tr.commit(); break; case R.id.navigation_image: if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions( new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2000); } else { startGallery(); } break; case R.id.navigation_done: save(); break; } return true; } }); return view; } private void startGallery() { Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); cameraIntent.setType("image/*"); if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(cameraIntent, 1000); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == 1000) { Uri returnUri = data.getData(); Bitmap bitmapImage = null; try { bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri); } catch (IOException e) { e.printStackTrace(); } ImageView imageView = new ImageView(getActivity()); imageView.setImageBitmap(bitmapImage); addView(imageView,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); addEditText(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); } } } public void addView(ImageView imageV, int width, int height){ first=false; try{ EditText e=getActivity().findViewById(specialId); e.setHint(""); }catch (Exception e){ Toast.makeText(getActivity(),"unsuccessful deleting hint",Toast.LENGTH_LONG).show(); } LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(width,height); layoutParams.setMargins(30,0,30,0); imageV.setLayoutParams(layoutParams); imageV.setAdjustViewBounds(true); imageV.setScaleType(ImageView.ScaleType.FIT_CENTER); linearLayout.addView(imageV); final int idForImage=helperForTime; ++helperForTime; noWordWatcher=false; boolean v=sqlHelper.insertData("",imageToByte(imageV),idForImage,realFilename); } public byte[] imageToByte(ImageView image){ Bitmap bitmap= ((BitmapDrawable)image.getDrawable()).getBitmap(); ByteArrayOutputStream stream=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream); return stream.toByteArray(); } public void addEditText(int width, int height){ LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(width,height); layoutParams.setMargins(30,0,30,0); final EditText a=new EditText(getActivity()); a.setLayoutParams(layoutParams); a.setBackgroundResource(android.R.color.transparent); a.setId(h); a.requestFocus(); a.setTextColor(textColor); //setKeyboardFocus(a); if(first){ a.setHint("Start writing your note please hehe..."); a.setId(specialId); } a.setAutoLinkMask(Linkify.WEB_URLS); a.setMovementMethod(LinkMovementMethod.getInstance()); a.setLinksClickable(false); Linkify.addLinks(a, Linkify.WEB_URLS); a.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { textColor=sharedPreferences.getInt("textColor",R.color.colorAccent); a.setTextColor(textColor); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { Linkify.addLinks(s, Linkify.WEB_URLS); } }); byte[] b = new byte[0]; int temp=0; if(first){ temp=specialId; }else{ temp=h; } if(a.getText().toString().trim().length()!=0)noWordWatcher=false; if(sqlHelper.insertData(a.getText().toString().trim(),b,temp,realFilename)){ //Toast.makeText(getActivity(),"success inserting edittext",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getActivity(),"Error occur when inserting EDIT TEXT",Toast.LENGTH_LONG).show(); } editCollectorId=editCollectorId+","+h; ++h; a.setLayoutParams(layoutParams); linearLayout.addView(a); } public void save(){ count++; editCollectorId=specialId+","+editCollectorId; String[] ids=editCollectorId.split(","); String android_id = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a"); String formattedDate = df.format(c.getTime()); nickiminaj="asdfjkl;yokelaminoak,,,"+android_id+",,,"+formattedDate+",,,"+getDeviceName()+",,,"+textColor; sqlHelper.update(nickiminaj,9999,realFilename); for(int i=0;i<ids.length;i++){ if(ids[i].length()>0) { int z= Integer.valueOf(ids[i]); try{ EditText a=view.findViewById(z); String newName=a.getText().toString().trim(); if(newName.length()!=0)noWordWatcher=false; sqlHelper.update(newName,z,realFilename); }catch (Exception e){ //no error actually , just catch for the remove view or view doesn't exists. } } } boolean success = false; if(noWordWatcher){ success=true; } if(!success) { SharedPreferences.Editor editor=sharedPreferences.edit(); String a=sharedPreferences.getString("ggg",","); if(a.contains(realFilename)){ }else{ String collle=realFilename+","+sharedPreferences.getString("ggg",","); editor.putString("ggg",collle); editor.apply(); } Toast.makeText(getActivity(), "Saved Successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(),"Can't save empty blank",Toast.LENGTH_SHORT).show(); } } public static String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return model; } return manufacturer + " " + model; } }
package com.cs.player; import com.cs.bonus.PlayerBonus; import com.cs.payment.Money; import com.cs.payment.MoneyConverter; import com.google.common.base.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Converts; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.math.BigDecimal; import static javax.persistence.GenerationType.IDENTITY; /** * @author Joakim Gottzén */ @Entity @Table(name = "wallets") @Converts(value = { @Convert(attributeName = "moneyBalance", converter = MoneyConverter.class), @Convert(attributeName = "reservedBalance", converter = MoneyConverter.class), @Convert(attributeName = "bonusBalance", converter = MoneyConverter.class), @Convert(attributeName = "turnoverCashback", converter = MoneyConverter.class), @Convert(attributeName = "reservedBonusBalance", converter = MoneyConverter.class), @Convert(attributeName = "reservedBonusBonus", converter = MoneyConverter.class), @Convert(attributeName = "reservedBonusProgressionGoal", converter = MoneyConverter.class), @Convert(attributeName = "bonusConversionProgress", converter = MoneyConverter.class), @Convert(attributeName = "bonusConversionGoal", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedCashback", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedMoneyTurnover", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedBonusTurnover", converter = MoneyConverter.class), @Convert(attributeName = "levelProgress", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedWeeklyTurnover", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedMonthlyTurnover", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedMonthlyBonusTurnover", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedDailyLoss", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedWeeklyLoss", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedMonthlyLoss", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedDailyBet", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedWeeklyBet", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedMonthlyBet", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedDeposit", converter = MoneyConverter.class), @Convert(attributeName = "accumulatedWithdrawal", converter = MoneyConverter.class) }) public class Wallet implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", nullable = false, unique = true) @Nonnull private Long id; @OneToOne @JoinColumn(name = "player_id", referencedColumnName = "id") @Nonnull @Valid private Player player; @Column(name = "money_balance", nullable = false) @Nonnull @NotNull private Money moneyBalance; @Column(name = "reserved_balance", nullable = false) @Nonnull @NotNull private Money reservedBalance; @Column(name = "credits_balance", nullable = false) @Nonnull @NotNull private Integer creditsBalance; @Column(name = "accumulated_cashback", nullable = false) @Nonnull @NotNull private Money accumulatedCashback; @Column(name = "accumulated_money_turnover", nullable = false) @Nonnull @NotNull private Money accumulatedMoneyTurnover; @Column(name = "accumulated_bonus_turnover", nullable = false) @Nonnull @NotNull private Money accumulatedBonusTurnover; @Column(name = "level_progress", nullable = false) @Nonnull @NotNull private Money levelProgress; @Column(name = "accumulated_weekly_turnover", nullable = false) @Nonnull @NotNull private Money accumulatedWeeklyTurnover; @Column(name = "accumulated_monthly_turnover", nullable = false) @Nonnull @NotNull private Money accumulatedMonthlyTurnover; @Column(name = "accumulated_monthly_bonus_turnover", nullable = false) @Nonnull @NotNull private Money accumulatedMonthlyBonusTurnover; @Column(name = "accumulated_daily_loss", nullable = false) @Nonnull @NotNull private Money accumulatedDailyLoss; @Column(name = "accumulated_weekly_loss", nullable = false) @Nonnull @NotNull private Money accumulatedWeeklyLoss; @Column(name = "accumulated_monthly_loss", nullable = false) @Nonnull @NotNull private Money accumulatedMonthlyLoss; @Column(name = "accumulated_daily_bet", nullable = false) @Nonnull @NotNull private Money accumulatedDailyBet; @Column(name = "accumulated_weekly_bet", nullable = false) @Nonnull @NotNull private Money accumulatedWeeklyBet; @Column(name = "accumulated_monthly_bet", nullable = false) @Nonnull @NotNull private Money accumulatedMonthlyBet; @Column(name = "accumulated_deposits", nullable = false) @Nonnull @NotNull private Money accumulatedDeposit; @Column(name = "accumulated_withdrawals", nullable = false) @Nonnull @NotNull private Money accumulatedWithdrawal; @Transient @Nullable private BigDecimal nextLevelPercentage; @OneToOne @JoinColumn(name = "player_bonus_id") @Nullable private PlayerBonus activePlayerBonus; public Wallet() {} public Wallet(@Nonnull final Player player) { this.player = player; moneyBalance = Money.ZERO; reservedBalance = Money.ZERO; creditsBalance = 0; accumulatedCashback = Money.ZERO; accumulatedMoneyTurnover = Money.ZERO; accumulatedBonusTurnover = Money.ZERO; levelProgress = Money.ZERO; accumulatedWeeklyTurnover = Money.ZERO; accumulatedMonthlyTurnover = Money.ZERO; accumulatedMonthlyBonusTurnover = Money.ZERO; accumulatedDailyLoss = Money.ZERO; accumulatedWeeklyLoss = Money.ZERO; accumulatedMonthlyLoss = Money.ZERO; accumulatedDailyBet = Money.ZERO; accumulatedWeeklyBet = Money.ZERO; accumulatedMonthlyBet = Money.ZERO; nextLevelPercentage = BigDecimal.ZERO; accumulatedDeposit = Money.ZERO; accumulatedWithdrawal = Money.ZERO; } @Nonnull public Long getId() { return id; } public void setId(@Nonnull final Long id) { this.id = id; } @Nonnull public Player getPlayer() { return player; } public void setPlayer(@Nonnull final Player player) { this.player = player; } @Nonnull public Money getMoneyBalance() { return moneyBalance; } public void setMoneyBalance(@Nonnull final Money moneyBalance) { this.moneyBalance = moneyBalance; } @Nonnull public Money getReservedBalance() { return reservedBalance; } public void setReservedBalance(@Nonnull final Money reservedBalance) { this.reservedBalance = reservedBalance; } @Nonnull public Integer getCreditsBalance() { return creditsBalance; } public void setCreditsBalance(@Nonnull final Integer creditsBalance) { this.creditsBalance = creditsBalance; } @Nonnull public Money getAccumulatedCashback() { return accumulatedCashback; } public void setAccumulatedCashback(@Nonnull final Money accumulatedCashback) { this.accumulatedCashback = accumulatedCashback; } @Nonnull public Money getAccumulatedMoneyTurnover() { return accumulatedMoneyTurnover; } public void setAccumulatedMoneyTurnover(@Nonnull final Money accumulatedMoneyTurnover) { this.accumulatedMoneyTurnover = accumulatedMoneyTurnover; } @Nonnull public Money getAccumulatedBonusTurnover() { return accumulatedBonusTurnover; } public void setAccumulatedBonusTurnover(@Nonnull final Money accumulatedBonusTurnover) { this.accumulatedBonusTurnover = accumulatedBonusTurnover; } @Nonnull public Money getLevelProgress() { return levelProgress; } public void setLevelProgress(@Nonnull final Money levelProgress) { this.levelProgress = levelProgress; } @Nonnull public Money getAccumulatedWeeklyTurnover() { return accumulatedWeeklyTurnover; } public void setAccumulatedWeeklyTurnover(@Nonnull final Money accumulatedWeeklyTurnover) { this.accumulatedWeeklyTurnover = accumulatedWeeklyTurnover; } @Nonnull public Money getAccumulatedMonthlyTurnover() { return accumulatedMonthlyTurnover; } public void setAccumulatedMonthlyTurnover(@Nonnull final Money accumulatedMonthlyTurnover) { this.accumulatedMonthlyTurnover = accumulatedMonthlyTurnover; } @Nonnull public Money getAccumulatedMonthlyBonusTurnover() { return accumulatedMonthlyBonusTurnover; } public void setAccumulatedMonthlyBonusTurnover(@Nonnull final Money accumulatedMonthlyBonusTurnover) { this.accumulatedMonthlyBonusTurnover = accumulatedMonthlyBonusTurnover; } @Nonnull public Money getAccumulatedDailyLoss() { return accumulatedDailyLoss; } @Nonnull public Money getAccumulatedWeeklyLoss() { return accumulatedWeeklyLoss; } @Nonnull public Money getAccumulatedMonthlyLoss() { return accumulatedMonthlyLoss; } @Nonnull public Money getAccumulatedDailyBet() { return accumulatedDailyBet; } @Nonnull public Money getAccumulatedWeeklyBet() { return accumulatedWeeklyBet; } @Nonnull public Money getAccumulatedMonthlyBet() { return accumulatedMonthlyBet; } @Nullable public BigDecimal getNextLevelPercentage() { return nextLevelPercentage; } public void setNextLevelPercentage(@Nullable final BigDecimal nextLevelPercentage) { this.nextLevelPercentage = nextLevelPercentage; } @Nonnull public Money getAccumulatedDeposit() { return accumulatedDeposit; } public void setAccumulatedDeposit(@Nonnull final Money accumulatedDeposit) { this.accumulatedDeposit = accumulatedDeposit; } @Nonnull public Money getAccumulatedWithdrawal() { return accumulatedWithdrawal; } public void setAccumulatedWithdrawal(@Nonnull final Money accumulatedWithdrawal) { this.accumulatedWithdrawal = accumulatedWithdrawal; } @Nonnull public Money getBonusBalance() { if (activePlayerBonus != null) { return activePlayerBonus.getCurrentBalance() != null ? activePlayerBonus.getCurrentBalance() : Money.ZERO; } return Money.ZERO; } @Nonnull public Money getBonusConversionProgress() { if (activePlayerBonus != null) { return activePlayerBonus.getBonusConversionProgress() != null ? activePlayerBonus.getBonusConversionProgress() : Money.ZERO; } return Money.ZERO; } @Nonnull public Money getBonusConversionGoal() { if (activePlayerBonus != null) { return activePlayerBonus.getBonusConversionGoal() != null ? activePlayerBonus.getBonusConversionGoal() : Money.ZERO; } return Money.ZERO; } @Nullable public PlayerBonus getActivePlayerBonus() { return activePlayerBonus; } public void setActivePlayerBonus(@Nullable final PlayerBonus activePlayerBonus) { this.activePlayerBonus = activePlayerBonus; } public Money getAccumulatedLossAmountByTimeUnit(final TimeUnit timeUnit) { switch (timeUnit) { case DAY: return accumulatedDailyLoss; case WEEK: return accumulatedWeeklyLoss; case MONTH: return accumulatedMonthlyLoss; } throw new IllegalArgumentException("Unsupported time unit " + timeUnit); } public Money setAccumulatedLossAmountByTimeUnit(final TimeUnit timeUnit, final Money amount) { switch (timeUnit) { case DAY: accumulatedDailyLoss = amount; return accumulatedDailyLoss; case WEEK: accumulatedWeeklyLoss = amount; return accumulatedWeeklyLoss; case MONTH: accumulatedMonthlyLoss = amount; return accumulatedMonthlyLoss; } throw new IllegalArgumentException("Unsupported time unit " + timeUnit); } public Money getAccumulatedBetAmountByTimeUnit(final TimeUnit timeUnit) { switch (timeUnit) { case DAY: return accumulatedDailyBet; case WEEK: return accumulatedWeeklyBet; case MONTH: return accumulatedMonthlyBet; } throw new IllegalArgumentException("Unsupported time unit " + timeUnit); } public Money setAccumulatedBetAmountByTimeUnit(final TimeUnit timeUnit, final Money amount) { switch (timeUnit) { case DAY: accumulatedDailyBet = amount; return accumulatedDailyBet; case WEEK: accumulatedWeeklyBet = amount; return accumulatedWeeklyBet; case MONTH: accumulatedMonthlyBet = amount; return accumulatedMonthlyBet; } throw new IllegalArgumentException("Unsupported time unit " + timeUnit); } public Money getTotalBalance() { return moneyBalance.add(getBonusBalance()); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Wallet that = (Wallet) o; return Objects.equal(id, that.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return Objects.toStringHelper(this) .add("id", id) .add("player", player.getId()) .add("moneyBalance", moneyBalance) .add("reservedBalance", reservedBalance) .add("creditsBalance", creditsBalance) .add("accumulatedCashback", accumulatedCashback) .add("accumulatedMoneyTurnover", accumulatedMoneyTurnover) .add("accumulatedBonusTurnover", accumulatedBonusTurnover) .add("levelProgress", levelProgress) .add("accumulatedWeeklyTurnover", accumulatedWeeklyTurnover) .add("accumulatedMonthlyTurnover", accumulatedMonthlyTurnover) .add("accumulatedMonthlyBonusTurnover", accumulatedMonthlyBonusTurnover) .add("accumulatedDailyLoss", accumulatedDailyLoss) .add("accumulatedWeeklyLoss", accumulatedWeeklyLoss) .add("accumulatedMonthlyLoss", accumulatedMonthlyLoss) .add("accumulatedDailyBet", accumulatedDailyBet) .add("accumulatedWeeklyBet", accumulatedWeeklyBet) .add("accumulatedMonthlyBet", accumulatedMonthlyBet) .add("nextLevelTurnoverTarget", nextLevelPercentage) .add("accumulatedDeposit", accumulatedDeposit) .add("accumulatedWithdrawal", accumulatedWithdrawal) .add("activePlayerBonus", activePlayerBonus != null ? activePlayerBonus.getId() : null) .toString(); } }
public class TokenFactory { public Token parseAndBuildToken(String string) { try { return new Operand(Integer.parseInt(string)); } catch (NumberFormatException e) { return new Operator(string); } } }
package ch06; public class PurseTester { /** * @param args */ public static void main(String[] args) { Purse purse = new Purse(); purse.addCoin("Quater"); purse.addCoin("Dime"); purse.addCoin("Nickel"); purse.addCoin("Dime"); System.out.println("Purse toString test:"); System.out.println(purse.toString()); System.out.println(); System.out.println("Purse reverse test:"); purse.reverse(); System.out.println(purse.toString()); System.out.println(); System.out.print("Create new Purse called Other: "); Purse other = new Purse(); other.addCoin("Dime"); other.addCoin("Nickel"); System.out.println(other.toString()); System.out.println("Purse transfer test"); purse.transfer(other); System.out.println("Other: " + other.toString()); System.out.println("Purse: " + purse.toString()); System.out.println(); System.out.println("Create new Purse called yetAnother with same content as purse: "); Purse yetAnother = new Purse(); yetAnother.addCoin("Dime"); yetAnother.addCoin("Nickel"); yetAnother.addCoin("Dime"); yetAnother.addCoin("Quater"); yetAnother.addCoin("Dime"); yetAnother.addCoin("Nickel"); System.out.println("yetAnother: " + yetAnother.toString()); System.out.println("Purse sameContents test:"); if(purse.sameContents(yetAnother)){ System.out.println("sameCoins works"); } else { } } }
package chemistry; /** * a class with static methods to check for exceptions * * This is the only place where F will be printed to console * @author Ted Kim * @email tkk21@case.edu * */ public class ExceptionUtils { public static void checkNulls (Object ... args){ if (args == null){ throw new NullPointerException(); } for (Object o: args){ if (o == null){ throw new NullPointerException(); } } } public static void checkIllegalString (String s){ try{ ExceptionUtils.checkNulls(s);//throw NPE if input is null } catch(NullPointerException e){ Chemistry.failChemistry(); } if (s.length()==0){ Chemistry.failChemistry(); } } }
package com.codingthamizha; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by Appoyy on 18/08/16. */ public class StringCompress { static BufferedReader br; static StringBuilder output; public StringCompress() { // Initializing the Buffered Reader & output buffer br = new BufferedReader(new InputStreamReader(System.in)); output = new StringBuilder(); } public static void main(String args[]) throws IOException { StringCompress sc = new StringCompress(); String inputString = br.readLine(); System.out.println(sc.solve(inputString.toLowerCase())); } public String solve(String str) { if (str.length() == 0) { // If String is null return ""; } int cCount = 0; for (int i = 0; i < str.length(); i++) { cCount += 1; char c = str.charAt(i); // Make note of this weird condition buddy if (i + 1 >= str.length() || c != str.charAt(i + 1)) { output.append(c); output.append(Integer.toString(cCount)); cCount = 0; } } // Compare size of string and compressed string b4 returning return output.toString().length() < str.length() ? output.toString() : str; } }
// Copyright 2010 Google Inc. All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.google.jgments; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.io.Resources; import com.google.jgments.syntax.LanguageDefinition; import com.google.jgments.syntax.PythonSyntax; import java.io.IOException; import java.nio.charset.Charset; import javax.annotation.Nullable; /** * A lexer based on regular expressions and state transitions. * This is a port of the corresponding class from Pygments. */ public class RegexLexer implements Iterable<SyntaxSpan> { private final LanguageDefinition lang; private final String text; private final LexerState state; public RegexLexer(LanguageDefinition lang, String text) { this(lang, text, null); } public RegexLexer(LanguageDefinition lang, String text, @Nullable LexerState state) { this.lang = checkNotNull(lang); this.text = checkNotNull(text); this.state = state; } public RegexLexerIterator iterator() { return new RegexLexerIterator(lang, text, state); } /** Sample method for exercising RegexLexer. */ public static void main(String[] argv) throws IOException { String text = Resources.toString( RegexLexer.class.getResource("extract.py"), Charset.defaultCharset()); RegexLexer lexer = new RegexLexer(PythonSyntax.INSTANCE, text); for (SyntaxSpan annotation : lexer) { System.out.println(annotation); } } }
package com.binarysprite.evemat.entity; import org.seasar.doma.Column; import org.seasar.doma.Entity; import org.seasar.doma.Id; import org.seasar.doma.Table; /** * */ @Entity(listener = UnitListener.class) @Table(name = "UNIT") public class Unit { /** */ @Id @Column(name = "UNIT_ID") Integer unitId; /** */ @Column(name = "UNIT_NAME") String unitName; /** */ @Column(name = "DISPLAY_NAME") String displayName; /** */ @Column(name = "DESCRIPTION") String description; /** * Returns the unitId. * * @return the unitId */ public Integer getUnitId() { return unitId; } /** * Sets the unitId. * * @param unitId the unitId */ public void setUnitId(Integer unitId) { this.unitId = unitId; } /** * Returns the unitName. * * @return the unitName */ public String getUnitName() { return unitName; } /** * Sets the unitName. * * @param unitName the unitName */ public void setUnitName(String unitName) { this.unitName = unitName; } /** * Returns the displayName. * * @return the displayName */ public String getDisplayName() { return displayName; } /** * Sets the displayName. * * @param displayName the displayName */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * Returns the description. * * @return the description */ public String getDescription() { return description; } /** * Sets the description. * * @param description the description */ public void setDescription(String description) { this.description = description; } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ package pwnbrew.network.control.messages; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.logging.Level; import pwnbrew.log.Log; import pwnbrew.manager.ClassManager; import pwnbrew.manager.PortManager; import pwnbrew.manager.DataManager; import pwnbrew.misc.Directories; import pwnbrew.utilities.FileUtilities; import pwnbrew.utilities.Utilities; import pwnbrew.xml.JarItem; import pwnbrew.xml.JarItemException; /** * * */ public final class AddToJarLibrary extends JarItemMsg{ // NO_UCD (use default) private static final String NAME_Class = AddToJarLibrary.class.getSimpleName(); public static final short MESSAGE_ID = 0x5a; // ========================================================================== /** * Constructor * * @param dstHostId * @param passedName * @param passedType * @param passedJvmVersion * @param passedJarVersion * @throws java.io.UnsupportedEncodingException */ public AddToJarLibrary(int dstHostId, String passedName, String passedType, String passedJvmVersion, String passedJarVersion ) throws UnsupportedEncodingException { super( MESSAGE_ID, dstHostId, passedName, passedType, passedJvmVersion, passedJarVersion ); } // ========================================================================== /** * Constructor * * @param passedId */ public AddToJarLibrary(byte[] passedId ) { super( passedId ); } //=============================================================== /** * Performs the logic specific to the message. * * @param passedManager */ @Override public void evaluate( PortManager passedManager ) { try { File aFile = File.createTempFile("tmp", null); File libDir = aFile.getParentFile(); aFile.delete(); //Get the filename String[] fileHashFileNameArr = theJarName.split(":", 2); if( fileHashFileNameArr.length != 2 ){ Log.log(Level.SEVERE, NAME_Class, "evaluate()", "Passed hash filename string is not correct.", null); return; } //Get the jar file File tempJarFile = new File( libDir, fileHashFileNameArr[1]); if( tempJarFile.exists()){ //Create a FileContentRef JarItem aJarItem; try { aJarItem = Utilities.getJavaItem( tempJarFile ); } catch (JarItemException ex) { Log.log(Level.SEVERE, NAME_Class, "evaluate()", ex.getMessage(), ex); return; } if( aJarItem != null ){ List<JarItem> jarList = Utilities.getJarItems(); try { for( JarItem currentItem : jarList ){ //Check if the jvm version is the same first if( aJarItem.getJvmMajorVersion().equals(currentItem.getJvmMajorVersion()) && aJarItem.getType().equals( currentItem.getType()) ){ //Only one Stager and Payload are allowed if( aJarItem.getType().equals(JarItem.STAGER_TYPE) || aJarItem.getType().equals(JarItem.PAYLOAD_TYPE)){ Utilities.removeJarItem(currentItem); if( !currentItem.getFileHash().equals(aJarItem.getFileHash())){ currentItem.deleteSelfFromDirectory( new File( Directories.getJarLibPath() )); currentItem.deleteFileContentFromLibrary(); } break; //Check if one with the same name exists } else if( aJarItem.getName().equals(currentItem.getName() )) { Utilities.removeJarItem(currentItem); if( !currentItem.getFileHash().equals(aJarItem.getFileHash())){ currentItem.deleteSelfFromDirectory( new File( Directories.getJarLibPath() )); currentItem.deleteFileContentFromLibrary(); } break; } } } //Add the jar Utilities.addJarItem( aJarItem ); //Write the file to disk String fileHash = FileUtilities.createHashedFile( tempJarFile ); if( fileHash != null ) { //Create a FileContentRef aJarItem.setFileHash( fileHash ); //Set the file's hash //Write to disk aJarItem.writeSelfToDisk(); //If it is a local extension then load it if( aJarItem.getType().equals(JarItem.LOCAL_EXTENSION_TYPE)){ //Load the jar File libraryFile = new File( Directories.getFileLibraryDirectory(), aJarItem.getFileHash() ); //Create a File to represent the library file to be copied List<Class<?>> theClasses = Utilities.loadJar(libraryFile); for( Class aClass : theClasses ) ClassManager.addClassToMap(aClass); } try { //Send the msg AddToJarLibrary aMsg = new AddToJarLibrary( getSrcHostId(), aJarItem.toString(), theJarType, aJarItem.getJvmMajorVersion(), aJarItem.getVersion() ); DataManager.send( passedManager, aMsg); //Delete the file tempJarFile.delete(); } catch (UnsupportedEncodingException ex) { Log.log(Level.WARNING, NAME_Class, "deleteJarItem", ex.getMessage(), ex ); } } } catch ( NoSuchAlgorithmException | IOException ex) { Log.log(Level.SEVERE, NAME_Class, "evaluate()", ex.getMessage(), ex); } } } } catch (IOException ex) { Log.log(Level.SEVERE, NAME_Class, "evaluate()", ex.getMessage(), ex); } } }
package slimeknights.tconstruct.library.client.model; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ItemLayerModel; import net.minecraftforge.client.model.ModelStateComposition; import net.minecraftforge.client.model.PerspectiveMapWrapper; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; import java.util.Collection; import java.util.Map; import java.util.function.Function; import javax.vecmath.Vector3f; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.client.CustomTextureCreator; import slimeknights.tconstruct.library.materials.Material; public class MaterialModel implements IPatternOffset, IModel { protected final int offsetX; protected final int offsetY; private final ImmutableList<ResourceLocation> textures; public MaterialModel(ImmutableList<ResourceLocation> textures) { this(textures, 0, 0); } public MaterialModel(ImmutableList<ResourceLocation> textures, int offsetX, int offsetY) { this.textures = textures; this.offsetX = offsetX; this.offsetY = offsetY; } @Override public IBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) { return bakeIt(state, format, bakedTextureGetter); } // the only difference here is the return-type public BakedMaterialModel bakeIt(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) { // take offset of texture into account if(offsetX != 0 || offsetY != 0) { state = new ModelStateComposition(state, TRSRTransformation .blockCenterToCorner(new TRSRTransformation(new Vector3f(offsetX / 16f, -offsetY / 16f, 0), null, null, null))); } ImmutableMap<TransformType, TRSRTransformation> map = PerspectiveMapWrapper.getTransforms(state); // normal model as the base IBakedModel base = new ItemLayerModel(textures).bake(state, format, bakedTextureGetter); // turn it into a baked material-model BakedMaterialModel bakedMaterialModel = new BakedMaterialModel(base, map); // and generate the baked model for each material-variant we have for the base texture String baseTexture = base.getParticleTexture().getIconName(); Map<String, TextureAtlasSprite> sprites = CustomTextureCreator.sprites.get(baseTexture); if(sprites != null) { for(Map.Entry<String, TextureAtlasSprite> entry : sprites.entrySet()) { Material material = TinkerRegistry.getMaterial(entry.getKey()); IModel model2 = ItemLayerModel.INSTANCE.retexture(ImmutableMap.of("layer0", entry.getValue().getIconName())); IBakedModel bakedModel2 = model2.bake(state, format, bakedTextureGetter); // if it's a colored material we need to color the quads. But only if the texture was not a custom texture if(material.renderInfo.useVertexColoring() && !CustomTextureCreator.exists(baseTexture + "_" + material.identifier)) { int color = (material.renderInfo).getVertexColor(); ImmutableList.Builder<BakedQuad> quads = ImmutableList.builder(); // ItemLayerModel.BakedModel only uses general quads for(BakedQuad quad : bakedModel2.getQuads(null, null, 0)) { quads.add(ModelHelper.colorQuad(color, quad)); } // create a new model with the colored quads bakedModel2 = new BakedSimpleItem(quads.build(), map, bakedModel2); } bakedMaterialModel.addMaterialModel(material, bakedModel2); } } return bakedMaterialModel; } @Override public Collection<ResourceLocation> getDependencies() { return ImmutableList.of(); } @Override public Collection<ResourceLocation> getTextures() { return textures; } @Override public IModelState getDefaultState() { return ModelHelper.DEFAULT_ITEM_STATE; } @Override public int getXOffset() { return offsetX; } @Override public int getYOffset() { return offsetY; } }
package com.study.zookeeper.DistributeLock.zkClient; import java.io.Serializable; /** * @author XiaoBai * @description 模拟竞争Master的机器 * @date */ public class UserCenter implements Serializable { private static final long serialVersionUID = 4422973397777606336L; // private static final long serialVersionUID = 1L; //机器信息 private int mac_id; //机器名称 private String mac_name; public int getMac_id() { return mac_id; } public void setMac_id(int mac_id) { this.mac_id = mac_id; } public String getMac_name() { return mac_name; } public void setMac_name(String mac_name) { this.mac_name = mac_name; } }
package app.android.com.gitrepostriesApp.view_model; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import java.util.List; import app.android.com.gitrepostriesApp.model.ContributorModel; import app.android.com.gitrepostriesApp.model.RepositoryModel; import app.android.com.gitrepostriesApp.repository.GitRepository; import static app.android.com.gitrepostriesApp.constant.AppConstant.PAGE_SIZE; import static app.android.com.gitrepostriesApp.constant.AppConstant.TOKEN_KEY; public class RepositoryViewModel extends AndroidViewModel { public GitRepository gitRepository; private LiveData<List<RepositoryModel>> articleResponseLiveData; private LiveData<List<ContributorModel>> contributorResponseLiveData; private LiveData<List<RepositoryModel>> contributorDetailResponseLiveData; public RepositoryViewModel(@NonNull Application application) { super(application); } public void repositories(){ gitRepository = new GitRepository(); this.articleResponseLiveData = gitRepository.getRepositories(); } public void contributors(String name){ gitRepository = new GitRepository(); this.contributorResponseLiveData = gitRepository.getContributors(name, PAGE_SIZE, TOKEN_KEY); } public void contributorsDetails(String full_name){ gitRepository = new GitRepository(); this.contributorDetailResponseLiveData = gitRepository.getContributorDetails(full_name); } public LiveData<List<RepositoryModel>> getArticleResponseLiveData() { return articleResponseLiveData; } public LiveData<List<ContributorModel>> getContributorResponseLiveData() { return contributorResponseLiveData; } public LiveData<List<RepositoryModel>> getContributorDetailResponseLiveData() { return contributorDetailResponseLiveData; } }
package com.example.lablnet.quizapp; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnStart=(Button)findViewById(R.id.btnCS); Button btnAddQuestion=(Button)findViewById(R.id.btnAddQuestion); Button btnAbout=(Button)findViewById(R.id.btnAbout); addQuestion addQuestion=new addQuestion(this); addQuestion.WriteData(); btnStart.setOnClickListener(this); btnAddQuestion.setOnClickListener(this); btnAbout.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnCS: //Open quiz activity Intent intent=new Intent(MainActivity.this, QuizActivity.class); startActivity(intent); break; case R.id.btnAddQuestion: // Open Dialog to add question DialogFragment dialogFragment=new DialogAddQuestion(); dialogFragment.show(getSupportFragmentManager(),"123"); break; case R.id.btnAbout: aboutDialog(); //About App break; } } public void aboutDialog(){ final AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("About"); builder.setMessage("Created By Ameer Hamza\nThis is Simple quiz app, you can add more questions.\nQuestions appear randomly"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { builder.create().dismiss(); } }); builder.show(); } }
package business; import java.util.ArrayList; import java.util.List; import java.util.OptionalDouble; public class Livro { private static final double PCT_DIREITOS =0.08; private String titulo; private Autor autor; private IProduto modalidade; private int paginas; private double precoBase; private List<Avaliacao> avaliacoes; public Livro(String titulo, Autor autor, IProduto modalidade, int paginas, double precoBase) { this.setTitulo(titulo); this.setAutor(autor); this.setModalidade(modalidade); this.setPaginas(paginas); this.setPrecoBase(precoBase); avaliacoes = new ArrayList<Avaliacao>(); } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public Autor getAutor() { return autor; } public void setAutor(Autor autor) { this.autor = autor; } public IProduto getModalidade() { return modalidade; } public void setModalidade(IProduto modalidade) { this.modalidade = modalidade; } public int getPaginas() { return paginas; } public void setPaginas(int paginas) { this.paginas = paginas; } public double getPrecoBase() { return precoBase; } public void setPrecoBase(double precoBase) { this.precoBase = precoBase; } public List<Avaliacao> getAvaliacoes() { return avaliacoes; } public void addAvaliacao(Avaliacao a) { avaliacoes.add(a); } public void removeAvaliacao() { avaliacoes.remove(0); } public double precoVenda() { return modalidade.precoVenda(this) + direitosAutorais(); } public double direitosAutorais() { return modalidade.precoVenda(this)*PCT_DIREITOS; } public double avaliacaoMedia() { return this.avaliacoes.stream().mapToDouble((f) -> f.getNota()).average().getAsDouble(); } }
package com.zs.dao.msgs; import com.google.gson.Gson; import com.huaiye.sdk.sdkabi._params.SdkBaseParams; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import com.zs.R; import com.zs.bus.CreateMeet; import com.zs.bus.CreateTalkAndVideo; import com.zs.bus.MeetInvistor; import com.zs.bus.TalkInvistor; import com.zs.common.AppUtils; import com.zs.dao.AppDatas; import ttyy.com.datasdao.annos.Column; /** * author: admin * date: 2018/01/17 * version: 0 * mail: secret * desc: MessageData */ public class BroadcastMessage { public static final int SUCCESS = 1; public static final int ERROR = 2; public static final int DOWNING = 3; public static final int TYPE_AUDIO = 1; public static final int TYPE_VIDEO = 2; @Column int type; @Column int state; @Column String down_path; @Column String save_path; @Column String userId; @Column String domainCode; protected BroadcastMessage() { userId = AppDatas.Auth().getUserID(); domainCode = AppDatas.Auth().getDomainCode(); } public BroadcastMessage(int type,String path) { this.type = type; down_path = path; } public static BroadcastMessage downFile(VssMessageBean message) { BroadcastMessage data = new BroadcastMessage(); data.type = message.type == AppUtils.BROADCAST_VIDEO_TYPE_INT?BroadcastMessage.TYPE_VIDEO:BroadcastMessage.TYPE_AUDIO; data.state = BroadcastMessage.DOWNING; data.down_path = message.content; return data; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getDown_path() { return down_path; } public void setDown_path(String down_path) { this.down_path = down_path; } public String getSave_path() { return save_path; } public void setSave_path(String save_path) { this.save_path = save_path; } }
package ru.app.service; import ru.app.exception.ResourceNotFoundException; import ru.app.model.User; import ru.app.persistence.Store; import ru.app.persistence.UserStore; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; /** * @author Vladimir Ryazanov (v.ryazanov13@gmail.com) */ public enum ValidateService { INSTANCE; private Store<User> userStore = UserStore.INSTANCE; public User add(User user) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); user.setCreateDate(df.format(new Date())); return userStore.add(user); } public User update(int id, User user) { User found = findById(id); if (user.getName() != null) { found.setName(user.getName()); } if (user.getLogin() != null) { found.setLogin(user.getLogin()); } if (user.getEmail() != null) { found.setEmail(user.getEmail()); } return userStore.update(id, found); } public User delete(int id) { User removed = userStore.delete(id); if (removed == null) { throw new ResourceNotFoundException("User not found"); } return removed; } public Collection<User> findAll() { Collection<User> result = userStore.findAll(); if (result.size() == 0) { throw new ResourceNotFoundException("No users stored"); } return result; } public User findById(int id) { User found = userStore.findById(id); if (found==null) { throw new ResourceNotFoundException("User not found"); } return found; } }
package edu.duke.ra.core; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; import edu.duke.ra.core.db.DB; public class RAConfig { private final String propsFileName; private final boolean internalPropsFile; private final boolean verbose; private Properties properties; public static class Builder { private boolean verbose = false; private String propsFileName = "/ra.properties"; private boolean internalPropsFile = true; private String url = ""; private String schema = ""; private String user = ""; private String password = ""; public Builder verbose(boolean verbose) { this.verbose = verbose; return this; } public Builder propsFileName(String name) { this.propsFileName = name; this.internalPropsFile = false; return this; } public Builder url(String url) { this.url = url; return this; } public Builder schema(String schema) { this.schema = schema; return this; } public Builder user(String user) { this.user = user; return this; } public Builder password(String password) { this.password = password; return this; } public RAConfig build() throws IOException, RAConfigException { return new RAConfig(this); } } private RAConfig(Builder builder) throws IOException { this.propsFileName = builder.propsFileName; this.internalPropsFile = builder.internalPropsFile; this.verbose = Boolean.parseBoolean(getValueOf("verbose", Boolean.toString(builder.verbose))); this.properties = new Properties(); this.properties.put("url", getValueOf("url", builder.url)); this.properties.put("schema", getValueOf("schema", builder.schema)); this.properties.put("user", getValueOf("user", builder.user)); this.properties.put("password", getValueOf("password", builder.password)); } public boolean verbose() { return verbose; } public DB configureDB() throws IOException, SQLException { DB database = new DB(properties.getProperty("url"), properties); return database; } private String getValueOf(String property, String value) throws IOException { if (value.length() != 0) { return value; } else if (propsFileName.length() != 0) { Properties properties = new Properties(); InputStream propsFile; if (internalPropsFile) { propsFile = this.getClass().getResourceAsStream(propsFileName); } else { propsFile = new FileInputStream(propsFileName); } if (propsFile == null) { return ""; } properties.load(propsFile); String newValue = properties.getProperty(property); if (newValue == null) { return ""; } return newValue; } else { return ""; } } }
package com.meehoo.biz.core.basic.dao.security; import com.meehoo.biz.core.basic.domain.security.Organization; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * Created by CZ on 2018/1/16. */ public interface IOrganizationDao extends JpaRepository<Organization, String> { @Query("FROM Organization WHERE parentOrg.id = ?1") List<Organization> findByParentOrgId(String id); @Query("FROM Organization WHERE grade = 0 and isLeaf ="+Organization.ISLeaf_NO) List<Organization> findTopOrg(); @Query(nativeQuery=true, value = "select * from sec_org WHERE id=?1 ") Organization queryById(String Id); @Query(nativeQuery=true, value = "select * from sec_org WHERE id in ?1 order by orgType desc") List<Organization> queryByIdList(List<String> orgIdList); @Query("FROM Organization WHERE parentOrg.id = null") List<Organization> listRoot(); List<Organization> findByIsDelete(int isDelete); }
/* * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.miku.r2dbc.mysql.codec.lob; import dev.miku.r2dbc.mysql.util.ServerVersion; import io.r2dbc.spi.Clob; import reactor.core.publisher.Flux; /** * An implementation of {@link Clob} for multi-{@link Node}s. */ final class MultiClob extends MultiLob implements Clob { private final int collationId; private final ServerVersion version; MultiClob(Node[] nodes, int collationId, ServerVersion version) { super(nodes); this.collationId = collationId; this.version = version; } @Override public Flux<CharSequence> stream() { return nodes().map(node -> node.readCharSequence(collationId, version)); } }
package ideablog.service.impl; import ideablog.dao.IRCollectDao; import ideablog.model.RCollect; import ideablog.service.IRCollectService; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("rCollectService") public class RCollectServiceImpl implements IRCollectService { @Resource private IRCollectDao rCollectDao; @Override public RCollect selectRCollect(long blogId, long userId) { return this.rCollectDao.selectRCollect(blogId, userId); } @Override public Boolean insertRCollect(long blogId, long userId) { return this.rCollectDao.insertRCollect(blogId, userId); } @Override public Boolean deleteRCollect(long blogId, long userId) { return this.rCollectDao.deleteRCollect(blogId, userId); } }
package com.lynch.sort.priorityqueue; import java.util.Scanner; import static com.lynch.sort.primary.BaseSort.isSorted; import static com.lynch.sort.primary.BaseSort.show; /** * 堆排序 * TO(N)=NlogN,SO(N)=1 * 1.堆的构造阶段 * 2.下沉排序阶段 * Created by lynch on 2018/9/7. <br> **/ public class HeapSort { public static void sort(Comparable[] a) { int N = a.length; for (int k = N / 2; k >= 1; k--) sink(a, k, N); while (N > 1) { exch(a, 1, N--); sink(a, 1, N); } } //由上至下的堆有序化(下沉)的实现 public static void sink(Comparable[] a, int k, int N) { while (2 * k <= N) { int j = 2 * k; if (j < N && less(a, j, j + 1)) j++; if (!less(a, k, j)) break; exch(a, k, j); k = j; } } private static boolean less(Comparable[] a, int i, int j) { return a[i - 1].compareTo(a[j - 1]) < 0; } private static void exch(Object[] a, int i, int j) { Object swap = a[i - 1]; a[i - 1] = a[j - 1]; a[j - 1] = swap; } public static void main(String[] args) { String[] a = new String[10]; Scanner in = new Scanner(System.in); System.out.println("Please input ten letters:"); for (int i = 0; i < a.length; i++) { String input = in.next(); a[i] = input; } sort(a); assert isSorted(a); show(a); } }
/* * 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 ventanas; import clases.Caja; import java.awt.event.KeyEvent; import javax.swing.JOptionPane; /** * * @author hp desktop */ public class NewJFrameEgreso extends javax.swing.JFrame { private NewJFramePrincipal principal; private Caja cajaActual; /** * Creates new form NewJFrameEgreso */ public NewJFrameEgreso(NewJFramePrincipal principal, Caja cajaA) { this.cajaActual = cajaA; this.principal = principal; initComponents(); setLocationRelativeTo(null); setResizable(false); //setDefaultCloseOperation(0);//anula la CRUZ exit setTitle("Colibrí Arte y Cultura - Egreso / Pago"); } /** * 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() { jPanelEgreso = new javax.swing.JPanel(); jLabelEgreso = new javax.swing.JLabel(); jLabelDescripcion = new javax.swing.JLabel(); jLabelMonto = new javax.swing.JLabel(); jTextFieldDescripcion = new javax.swing.JTextField(); jTextFieldMonto = new javax.swing.JTextField(); jButtonEgreso = new javax.swing.JButton(); jButtonMenuPrincipal = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanelEgreso.setBackground(new java.awt.Color(109, 176, 248)); jPanelEgreso.setForeground(new java.awt.Color(109, 176, 248)); jLabelEgreso.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelEgreso.setText("Egresos / Pagos"); jLabelDescripcion.setText("Descripcion: "); jLabelMonto.setText("Monto: $ "); jTextFieldMonto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldMontoActionPerformed(evt); } }); jTextFieldMonto.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldMontoKeyTyped(evt); } }); jButtonEgreso.setText("Cargar Pago"); jButtonEgreso.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonEgresoActionPerformed(evt); } }); jButtonMenuPrincipal.setText("Menú Principal"); jButtonMenuPrincipal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonMenuPrincipalActionPerformed(evt); } }); javax.swing.GroupLayout jPanelEgresoLayout = new javax.swing.GroupLayout(jPanelEgreso); jPanelEgreso.setLayout(jPanelEgresoLayout); jPanelEgresoLayout.setHorizontalGroup( jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelEgresoLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelDescripcion) .addComponent(jLabelMonto)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelEgresoLayout.createSequentialGroup() .addComponent(jTextFieldMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 167, Short.MAX_VALUE)) .addComponent(jTextFieldDescripcion) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelEgresoLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButtonMenuPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonEgreso))) .addGap(25, 25, 25)) .addGroup(jPanelEgresoLayout.createSequentialGroup() .addGap(127, 127, 127) .addComponent(jLabelEgreso) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelEgresoLayout.setVerticalGroup( jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelEgresoLayout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jLabelEgreso) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelDescripcion)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelMonto) .addComponent(jTextFieldMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanelEgresoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonEgreso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonMenuPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelEgreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelEgreso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextFieldMontoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldMontoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldMontoActionPerformed private void jButtonMenuPrincipalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMenuPrincipalActionPerformed this.principal.setVisible(true); dispose(); }//GEN-LAST:event_jButtonMenuPrincipalActionPerformed private void jButtonEgresoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEgresoActionPerformed // generar PAGO! try{ int eleccion = JOptionPane.showConfirmDialog(null," ¿ DESEA REALIZAR EL PAGO ? ", "Pago / Egreso ", JOptionPane.WARNING_MESSAGE); if (eleccion == JOptionPane.YES_OPTION){ String pago = jTextFieldMonto.getText(); Double egreso = Double.parseDouble(pago); cajaActual.setMonto(cajaActual.getMonto() - egreso); cajaActual.getEgreso().add(jTextFieldDescripcion.getText()); jTextFieldMonto.setText(""); jTextFieldDescripcion.setText(""); }else if (eleccion == JOptionPane.CANCEL_OPTION){ }else if (eleccion == JOptionPane.CLOSED_OPTION){ } //prueba en consola for(int x=0;x<cajaActual.getEgreso().size();x++) { System.out.println(cajaActual.getEgreso().get(x)); } System.out.println(cajaActual.getMonto()); //mensaje operacion exitosa JOptionPane.showMessageDialog(null, " PAGO REALIZADO ", "Pagos / Egresos", JOptionPane.WARNING_MESSAGE); }catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "FORMATO INCORRECTO EN EL INGRESO DE DATOS", "ERROR", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonEgresoActionPerformed private void jTextFieldMontoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldMontoKeyTyped //no deja escribir letras , solamente un solo punto, unicamente deja escribir numeros! int k = evt.getKeyChar(); if ((k >= 46) && (k<= 57) ){ if (k == 46){ String dato = jTextFieldMonto.getText(); int tam = dato.length(); for (int i=0; i<=tam; i++){ if(dato.contains(".")) evt.setKeyChar((char)KeyEvent.VK_CLEAR); } }if (k == 47){ evt.setKeyChar((char)KeyEvent.VK_CLEAR); } }else{ evt.setKeyChar((char)KeyEvent.VK_CLEAR); evt.consume(); } }//GEN-LAST:event_jTextFieldMontoKeyTyped /** * @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(NewJFrameEgreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrameEgreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrameEgreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrameEgreso.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 NewJFrameEgreso(null, null).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonEgreso; private javax.swing.JButton jButtonMenuPrincipal; private javax.swing.JLabel jLabelDescripcion; private javax.swing.JLabel jLabelEgreso; private javax.swing.JLabel jLabelMonto; private javax.swing.JPanel jPanelEgreso; private javax.swing.JTextField jTextFieldDescripcion; private javax.swing.JTextField jTextFieldMonto; // End of variables declaration//GEN-END:variables }
/** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-26 * Time: 下午9:26 * To change this template use File | Settings | File Templates. */ public class MyDirectedDFS { private boolean[] marked; private MyDigraph G; public MyDirectedDFS(MyDigraph G, int s) { this.G = G; marked = new boolean[G.V()]; dfs(s); } public MyDirectedDFS(MyDigraph G, Iterable<Integer> sources) { this.G = G; marked = new boolean[G.V()]; for(int i = 0; i < G.V(); ++i) { if(!marked[i]) dfs(i); } } private void dfs(int v) { marked[v] = true; for(int w:G.adj(v)) if(!marked[w]) dfs(w); } public boolean marked(int v) { return marked[v]; } }
package app.akeorcist.deviceinformation.fragment.main; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.CardView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.inthecheesefactory.thecheeselibrary.fragment.support.v4.app.StatedFragment; import com.pnikosis.materialishprogress.ProgressWheel; import com.squareup.otto.Subscribe; import app.akeorcist.deviceinformation.R; import app.akeorcist.deviceinformation.constants.Constants; import app.akeorcist.deviceinformation.data.device.DataManager; import app.akeorcist.deviceinformation.event.ViewEvent; import app.akeorcist.deviceinformation.provider.BusProvider; import app.akeorcist.deviceinformation.utility.AnimateUtils; import app.akeorcist.deviceinformation.activity.ScreenMeasureActivity; import app.akeorcist.deviceinformation.model.ScreenData; import app.akeorcist.deviceinformation.utility.DevicePreferences; public class ScreenFragment extends StatedFragment { private Activity activity; private CardView cvScreenMeasure; private LinearLayout layoutContent; private ProgressWheel progressWheel; private TextView tvResolutionPx; private TextView tvResolutionDp; private TextView tvDpiX; private TextView tvDpiY; private TextView tvDpi; private TextView tvSize; private TextView tvDensity; private TextView tvMultitouch; public static ScreenFragment newInstance() { ScreenFragment fragment = new ScreenFragment(); Bundle bundle = new Bundle(); fragment.setArguments(bundle); return fragment; } public ScreenFragment() { } @SuppressLint("NewApi") public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_screen, container, false); tvResolutionPx = (TextView) rootView.findViewById(R.id.tv_resolution_px); tvResolutionDp = (TextView) rootView.findViewById(R.id.tv_resolution_dp); tvDpiX = (TextView) rootView.findViewById(R.id.tv_dpi_x); tvDpiY = (TextView) rootView.findViewById(R.id.tv_dpi_y); tvDpi = (TextView) rootView.findViewById(R.id.tv_dpi); tvSize = (TextView) rootView.findViewById(R.id.tv_size); tvDensity = (TextView) rootView.findViewById(R.id.tv_density); tvMultitouch = (TextView) rootView.findViewById(R.id.tv_multitouch); progressWheel = (ProgressWheel) rootView.findViewById(R.id.progress_wheel); layoutContent = (LinearLayout) rootView.findViewById(R.id.layout_content); cvScreenMeasure = (CardView) rootView.findViewById(R.id.cv_screen_measure); cvScreenMeasure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, ScreenMeasureActivity.class); startActivity(intent); } }); if(savedInstanceState == null) { layoutContent.setVisibility(View.GONE); setMeasureScreen(); } setHasOptionsMenu(true); return rootView; } @Override public void onSaveState(Bundle outState) { super.onSaveState(outState); } @Override public void onRestoreState(Bundle savedInstanceState) { super.onRestoreState(savedInstanceState); initialData(); setMeasureScreen(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = getActivity(); BusProvider.getInstance().register(this); } @Override public void onDestroy() { super.onDestroy(); BusProvider.getInstance().unregister(this); } @Subscribe public void loadView(ViewEvent event) { if(ViewEvent.EVENT_MENU_SELECTED.equals(event.getEventState())) { initialData(); AnimateUtils.fadeOutAnimate(progressWheel, new AnimateUtils.OnProgressGoneListener() { @Override public void onGone() { AnimateUtils.fadeInAnimateWithZero(layoutContent); } }); } } private void initialData() { ScreenData screenData = DataManager.getScreenData(activity); tvResolutionPx.setText(screenData.getResolutionPx()); tvResolutionDp.setText(screenData.getResolutionDp()); tvDpiX.setText(screenData.getDpiX()); tvDpiY.setText(screenData.getDpiY()); tvDpi.setText(screenData.getDpi()); tvSize.setText(screenData.getSize()); tvDensity.setText(screenData.getDensity()); tvMultitouch.setText(screenData.getMultitouch()); } private void setMeasureScreen() { boolean isYourDevice = DevicePreferences.getCurrentDevice(activity).equals(Constants.FILE_DEVICE_INFO); if (isYourDevice) { cvScreenMeasure.setVisibility(View.VISIBLE); } else { cvScreenMeasure.setVisibility(View.GONE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); } }
package com.jfronny.raut.api; import net.minecraft.item.ItemGroup; import net.minecraft.item.ToolMaterial; public class BasePaxel extends PaxelItem { public BasePaxel(ToolMaterial material) { super(new ToolMatBuilder(material).setAttackDamage(material.getAttackDamage()), new Settings().group(ItemGroup.TOOLS).maxDamage(material.getDurability() * 3)); } }
package org.w2b.designpatterns.singleton; public class MinimalSingleton { private MinimalSingleton() { /* the body of the constructor here */ } /* pre-initialized instance of the singleton */ private static final MinimalSingleton INSTANCE = new MinimalSingleton(); /* Access point to the unique instance of the singleton */ public static MinimalSingleton getInstance() { return INSTANCE; } }
package miniWat; public class Threadin implements Runnable { public Threadin(){ } public static void main(String[] args){ Threadin t = new Threadin(); t.run(); } public void run() { System.out.println("yep"); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.codec.multipart; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.ResolvableType; import org.springframework.core.codec.DecodingException; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferLimitException; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ReactiveHttpInputMessage; import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.LoggingCodecSupport; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * {@code HttpMessageReader} for parsing {@code "multipart/form-data"} requests * to a stream of {@link PartEvent} elements. * * @author Arjen Poutsma * @since 6.0 * @see PartEvent */ public class PartEventHttpMessageReader extends LoggingCodecSupport implements HttpMessageReader<PartEvent> { private int maxInMemorySize = 256 * 1024; private int maxHeadersSize = 10 * 1024; private Charset headersCharset = StandardCharsets.UTF_8; /** * Get the {@link #setMaxInMemorySize configured} maximum in-memory size. */ public int getMaxInMemorySize() { return this.maxInMemorySize; } /** * Configure the maximum amount of memory allowed for form fields. * When the limit is exceeded, form fields parts are rejected with * {@link DataBufferLimitException}. * <p>By default this is set to 256K. * @param maxInMemorySize the in-memory limit in bytes; if set to -1 the entire * contents will be stored in memory */ public void setMaxInMemorySize(int maxInMemorySize) { this.maxInMemorySize = maxInMemorySize; } /** * Configure the maximum amount of memory that is allowed per headers section of each part. * Defaults to 10K. * @param byteCount the maximum amount of memory for headers */ public void setMaxHeadersSize(int byteCount) { this.maxHeadersSize = byteCount; } /** * Set the character set used to decode headers. * <p>Defaults to UTF-8 as per RFC 7578. * @param headersCharset the charset to use for decoding headers * @see <a href="https://tools.ietf.org/html/rfc7578#section-5.1">RFC-7578 Section 5.1</a> */ public void setHeadersCharset(Charset headersCharset) { Assert.notNull(headersCharset, "Charset must not be null"); this.headersCharset = headersCharset; } @Override public List<MediaType> getReadableMediaTypes() { return Collections.singletonList(MediaType.MULTIPART_FORM_DATA); } @Override public boolean canRead(ResolvableType elementType, @Nullable MediaType mediaType) { return PartEvent.class.equals(elementType.toClass()) && (mediaType == null || MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)); } @Override public Mono<PartEvent> readMono(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { return Mono.error( new UnsupportedOperationException("Cannot read multipart request body into single PartEvent")); } @Override public Flux<PartEvent> read(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { return Flux.defer(() -> { byte[] boundary = MultipartUtils.boundary(message, this.headersCharset); if (boundary == null) { return Flux.error(new DecodingException("No multipart boundary found in Content-Type: \"" + message.getHeaders().getContentType() + "\"")); } return MultipartParser.parse(message.getBody(), boundary, this.maxHeadersSize, this.headersCharset) .windowUntil(t -> t instanceof MultipartParser.HeadersToken, true) .concatMap(tokens -> tokens.switchOnFirst((signal, flux) -> { if (signal.hasValue()) { MultipartParser.HeadersToken headersToken = (MultipartParser.HeadersToken) signal.get(); Assert.state(headersToken != null, "Signal should be headers token"); HttpHeaders headers = headersToken.headers(); Flux<MultipartParser.BodyToken> bodyTokens = flux.filter(t -> t instanceof MultipartParser.BodyToken) .cast(MultipartParser.BodyToken.class); return createEvents(headers, bodyTokens); } else { // complete or error signal return flux.cast(PartEvent.class); } })); }); } private Publisher<? extends PartEvent> createEvents(HttpHeaders headers, Flux<MultipartParser.BodyToken> bodyTokens) { if (MultipartUtils.isFormField(headers)) { Flux<DataBuffer> contents = bodyTokens.map(MultipartParser.BodyToken::buffer); return DataBufferUtils.join(contents, this.maxInMemorySize) .map(content -> { String value = content.toString(MultipartUtils.charset(headers)); DataBufferUtils.release(content); return DefaultPartEvents.form(headers, value); }) .switchIfEmpty(Mono.fromCallable(() -> DefaultPartEvents.form(headers))); } else if (headers.getContentDisposition().getFilename() != null) { return bodyTokens .map(body -> DefaultPartEvents.file(headers, body.buffer(), body.isLast())) .switchIfEmpty(Mono.fromCallable(() -> DefaultPartEvents.file(headers))); } else { return bodyTokens .map(body -> DefaultPartEvents.create(headers, body.buffer(), body.isLast())) .switchIfEmpty(Mono.fromCallable(() -> DefaultPartEvents.create(headers))); // empty body } } }
package com.company; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { SentenceExtractor extractor = new SentenceExtractor(); if (!Files.exists(Paths.get("./dictionary1.txt"))) { try (TextFileReader reader = new TextFileReader("./eng_wikipedia_2016_300K-sentences.txt")) { DictionaryBuilder dictionaryBuilder = new DictionaryBuilder(); dictionaryBuilder.setDictionary(reader, extractor); dictionaryBuilder.toFile("./dictionary1.txt"); } catch (IOException ex) { ex.printStackTrace(); } } Scanner scn= new Scanner(System.in); System.out.println("Please give me the name of file to check:"); String file="./errors/"+scn.nextLine(); TextFileReader reader = new TextFileReader(file); LineWriter lineWriter=new FileLineWriter("output.txt"); (new SpellChecker(DictionaryLoader.load("./dictionary1.txt"))).correctSpelling(reader,lineWriter); } }
package de.trispeedys.resourceplanning; import static org.junit.Assert.assertEquals; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.junit.Rule; import de.trispeedys.resourceplanning.entity.Event; import de.trispeedys.resourceplanning.entity.EventTemplate; import de.trispeedys.resourceplanning.entity.misc.EventState; import de.trispeedys.resourceplanning.interaction.EventManager; import de.trispeedys.resourceplanning.test.TestDataGenerator; import de.trispeedys.resourceplanning.util.SpeedyRoutines; public class EventTest { @Rule public ProcessEngineRule processEngine = new ProcessEngineRule(); // @Test @Deployment(resources = "RequestHelp.bpmn") public void testHelperProcesses() { // clear db HibernateUtil.clearAll(); // there is a new event (with 7 active helpers)... Event event2016 = SpeedyRoutines.duplicateEvent(TestDataGenerator.createRealLifeEvent("Triathlon 2016", "TRI-2016", 21, 6, 2016, EventState.FINISHED, EventTemplate.TEMPLATE_TRI), "Triathlon 2016", "TRI-2016", 21, 6, 2016, null, null); // start processes... EventManager.triggerHelperProcesses(EventTemplate.TEMPLATE_TRI); // there must be seven request processes assertEquals(7, processEngine.getRuntimeService().createExecutionQuery().list().size()); } }
package com.hcmus.pricetracker.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.gson.Gson; import dao.PriceTrackerDAO; /** * * @author Minh Tran */ public class homepage extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //<editor-fold defaultstate="collapsed" desc="HEADER"> response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); String userPath = request.getServletPath(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); //<editor-fold defaultstate="collapsed" desc="EVENT CHECK LOGIN"> if (userPath.equals("/getPriceProduct")) { String url = request.getParameter("url"); PriceTrackerDAO priceTrackerDAO = new PriceTrackerDAO(); String strJson = new Gson().toJson(priceTrackerDAO.getPriceProduct(url)); out.print(strJson); } if (userPath.equals("/getPriceHistory")) { PriceTrackerDAO priceTrackerDAO = new PriceTrackerDAO(); String url = request.getParameter("url"); String strJson = new Gson().toJson(priceTrackerDAO.getPriceHistory(url)); out.print(strJson); } if (userPath.equals("/saveUserRequest")) { PriceTrackerDAO priceTrackerDAO = new PriceTrackerDAO(); String url = request.getParameter("url"); Integer sessionID = request.getParameter("sessionID").equals("") ? -1 : Integer.parseInt(request.getParameter("sessionID")); Integer result = priceTrackerDAO.saveUserRequest(url, sessionID); out.print(result); } if (userPath.equals("/getSuggestUrl")) { PriceTrackerDAO priceTrackerDAO = new PriceTrackerDAO(); String url = request.getParameter("url"); String strJson = new Gson().toJson(priceTrackerDAO.getSuggestUrl(url)); out.print(strJson); } } }
package gov.nih.mipav.view; import java.awt.*; import java.awt.geom.*; // imports for memory monitor import java.awt.image.*; import javax.swing.*; /** * BarMeter presents a vertical, block-style meter to present numerical information as a fraction of a number of * divisions (eg, progress or resource consumption). The default number of divisions is variable, but the default is 1. * The meter represents inputted values as one of either color, one "Used" and the other "Un-Used." Used are filled in * to the the percentage value inputted (integer) divided by the number of divisions. The default color used is Green, * and default unused is Dark Grey. * * <p>$Logfile: /mipav/src/gov/nih/mipav/view/BarMeter.java $ $Revision: 10 $ $Date: 7/02/04 1:30p $</p> */ public class BarMeter extends JPanel { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -560671300642650806L; //~ Instance fields ------------------------------------------------------------------------------------------------ /** DOCUMENT ME! */ int boxHeight; /** DOCUMENT ME! */ int boxWidth; /** DOCUMENT ME! */ Graphics2D g2d; /** DOCUMENT ME! */ int h = 0; // width, height /** DOCUMENT ME! */ BufferedImage img; /** DOCUMENT ME! */ Color unusedColor = Color.darkGray; /** DOCUMENT ME! */ Rectangle2D unusedRect = new Rectangle2D.Float(); /** DOCUMENT ME! */ Color usedColor = Color.cyan; /** DOCUMENT ME! */ Rectangle2D usedRect = new Rectangle2D.Float(); /** DOCUMENT ME! */ int w = 0; /** DOCUMENT ME! */ int whitespaceH = 10; /** DOCUMENT ME! */ int whitespaceW = 10; /** DOCUMENT ME! */ private int amplitude = 0; /** DOCUMENT ME! */ private int divisions = 1; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Constructs a barmeter with a background color of black. Does not show the meter. */ public BarMeter() { super(); setBackground(Color.black); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Maximum size of this panel. * * @return DOCUMENT ME! */ public Dimension getMaximumSize() { return getPreferredSize(); } /** * Minimum size of this panel. * * @return DOCUMENT ME! */ public Dimension getMinimumSize() { return getPreferredSize(); } /** * Preferred size of this panel. * * @return DOCUMENT ME! */ public Dimension getPreferredSize() { return new Dimension(30, 120); } /** * Draws the vertical bar, or all 100&#37 of posible amplitude values. * * @param g DOCUMENT ME! */ public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g; Insets in = getInsets(); Dimension d = getSize(); if ((d.width != w) || (d.height != h)) { w = d.width - in.left - in.right; h = d.height - in.top - in.bottom; boxHeight = (h - (2 * whitespaceH)) / divisions; boxWidth = w - (2 * whitespaceW); } // .. unused .. g2d.setColor(unusedColor); int i; for (i = 0; i < amplitude; i++) { unusedRect.setRect(whitespaceW + in.left, (float) whitespaceH + (i * boxHeight) + in.top, boxWidth, (float) boxHeight - 1); g2d.fill(unusedRect); } // .. used .. g2d.setColor(usedColor); for (; i < divisions; i++) { // takes off where the empty boxes left off usedRect.setRect(whitespaceW + in.left, (float) whitespaceH + (i * boxHeight) + in.top, boxWidth, (float) boxHeight - 1); g2d.fill(usedRect); } } /** * sets the height of the of the bar reading. * * @param amp percentage amount of the amplitude. ARguments greater than 100 (&#37) or less than zero are thrown * out. */ public void setAmplitude(int amp) { if ((amp < 0) || (amp > 100)) { return; } else { amplitude = divisions - (int) (amp / 100.0f * divisions); } } /** * applies the given int to the total number of bars on the display. * * @param div sets the number of bars, or divisions, on the display. the finest resolution that may be displayed, * is then 100/div (&#37). */ public void setDivisions(int div) { if (div < 1) { return; } divisions = div; } /** * applies the given color to bars which are not lit and are above the set amplitude. * * @param c color used in divisions that represent values smaller than the amplitude. */ public void setUnusedColor(Color c) { unusedColor = c; } /** * applies the given color to bars which are "lit" and are up to the set amplitude. * * @param c color used in divisions that represent values smaller than the amplitude. */ public void setUsedColor(Color c) { usedColor = c; } }
package com.zzwc.cms.common.utils; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 不同概率抽奖工具包 * * @author weirdor */ public class LotteryUtil { /** * 抽奖 * * @param orignalRates * 原始的概率列表,保证顺序和实际物品对应 * @return * 物品的索引 */ public static int lottery(List<Double> orignalRates) { if (orignalRates == null || orignalRates.isEmpty()) { return -1; } int size = orignalRates.size(); // 计算总概率,这样可以保证不一定总概率是1 double sumRate = 0d; for (double rate : orignalRates) { sumRate += rate; } //不中奖的概率 double noLuky = 0d; //如果各奖项的总概率大于1,则必然产生其中一个奖项,如果各奖项的总概率小于1,则包括不中奖的概率 if(sumRate<1){ //计算不中奖的概率 noLuky=(1-sumRate)/1; } // 计算每个物品在总概率的基础下的概率情况 List<Double> sortOrignalRates = new ArrayList<Double>(size); Double tempSumRate = 0d; for (double rate : orignalRates) { tempSumRate += rate; sortOrignalRates.add(tempSumRate / sumRate); } // 根据区块值来获取抽取到的物品索引 double nextDouble = Math.random(); //如果区块值在不中奖的概率范围内 if (nextDouble < noLuky) { return -1; } sortOrignalRates.add(nextDouble); Collections.sort(sortOrignalRates); return sortOrignalRates.indexOf(nextDouble); } public static void main(String[] args) { List<Double> orignalRates=new ArrayList<>(); orignalRates.add(0.1); orignalRates.add(0.3); orignalRates.add(0.2); for (int i = 0; i < 100000000; i++) { System.out.println(lottery(orignalRates)); } } }
package com.culturaloffers.maps.services; import static com.culturaloffers.maps.constants.CulturalOfferConstants.*; import static org.assertj.core.api.Assertions.assertThat; import com.culturaloffers.maps.dto.ZoomDTO; import com.culturaloffers.maps.model.CulturalOffer; import com.culturaloffers.maps.model.GeoLocation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource("classpath:test-offer.properties") public class CulturalOfferServiceIntegrationTest { @Autowired private CulturalOfferService service; @Autowired private GeoLocationService geoLocationService; @Test public void testFindAll(){ List<CulturalOffer> all = service.findAll(); assertThat(all).hasSize(15); } @Test public void testFindAllPageable(){ PageRequest request = PageRequest.of(1, 5); Page<CulturalOffer> page = service.findAll(request); assertThat(page).hasSize(5); } @Test public void testFindOne(){ CulturalOffer offer = service.findOne(CO_ID); assertThat(offer).isNotNull(); assertThat(offer.getTitle()).isEqualTo(CO_TITLE); assertThat(offer.getDescription()).isEqualTo(CO_DESCRIPTION); assertThat(offer.getGeoLocation().getAddress()).isEqualTo(CO_ADDRESS); assertThat(offer.getSubtype().getName()).isEqualTo(CO_SUBTYPE); } @Test @Transactional @Rollback(true) public void testCreateCulturalOffer() throws Exception { int sizeBefore = service.findAll().size(); GeoLocation location = new GeoLocation(12.12, 13.13, CO_NEW_ADDRESS); geoLocationService.insert(location); List<String> images = new ArrayList<>(); CulturalOffer culturalOffer = new CulturalOffer(null, CO_NEW_TITLE, CO_NEW_DESCRIPTION, images); service.create(culturalOffer, location.getAddress(), "crkva"); assertThat(sizeBefore).isLessThan(service.findAll().size()); CulturalOffer testOffer = service.findOne(service.findAll().size()); assertThat(testOffer).isNotNull(); assertThat(testOffer.getId()).isEqualTo(culturalOffer.getId()); assertThat(testOffer.getDescription()).isEqualTo(culturalOffer.getDescription()); assertThat(testOffer.getTitle()).isEqualTo(culturalOffer.getTitle()); assertThat(testOffer.getGeoLocation().getAddress()).isEqualTo(location.getAddress()); assertThat(testOffer.getSubtype().getName()).isEqualTo("crkva"); } @Test @Transactional @Rollback(true) public void testRemoveCulturalOffer() throws Exception { int sizeBefore = service.findAll().size(); CulturalOffer offer = service.findOne(CO_ID); assertThat(offer).isNotNull(); service.delete(CO_ID); CulturalOffer delOffer = service.findOne(CO_ID); assertThat(delOffer).isNull(); assertThat(service.findAll().size()).isLessThan(sizeBefore); } @Test @Transactional @Rollback(true) public void testUpdateCulturalOffer() throws Exception{ int sizeBefore = service.findAll().size(); CulturalOffer offer = service.findOne(CO_ID); assertThat(offer).isNotNull(); List<String> images = new ArrayList<>(); CulturalOffer updated = new CulturalOffer(null, CO_NEW_TITLE, CO_NEW_DESCRIPTION, images); updated = service.update(CO_ID, updated); assertThat(service.findAll().size()).isEqualTo(sizeBefore); assertThat(service.findOne(CO_ID)).isNotNull(); assertThat(service.findOne(CO_ID)).isEqualTo(updated); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testCreateCulturalOfferWithNonUniqueName() throws Exception{ GeoLocation geo = new GeoLocation(12.11, 13.11, CO_NEW_ADDRESS); geoLocationService.insert(geo); ArrayList<String> imgs = new ArrayList<>(); CulturalOffer offer = new CulturalOffer(null, CO_TITLE, CO_NEW_DESCRIPTION, imgs); service.create(offer, CO_NEW_ADDRESS, CO_SUBTYPE); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testCreateCulturalOfferWithInvalidGeoLocation() throws Exception{ ArrayList<String> imgs = new ArrayList<>(); CulturalOffer offer = new CulturalOffer(null, CO_NEW_TITLE, CO_NEW_DESCRIPTION, imgs); service.create(offer, CO_NEW_ADDRESS, CO_SUBTYPE); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testCreateCulturalOfferWithInvalidSubtype() throws Exception{ GeoLocation geo = new GeoLocation(12.11, 13.11, CO_NEW_ADDRESS); geoLocationService.insert(geo); ArrayList<String> imgs = new ArrayList<>(); CulturalOffer offer = new CulturalOffer(null, CO_NEW_TITLE, CO_NEW_DESCRIPTION, imgs); service.create(offer, CO_NEW_ADDRESS, "invalid subtype"); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testCreateCulturalOfferWithBlankDesc() throws Exception{ GeoLocation geo = new GeoLocation(12.11, 13.11, CO_NEW_ADDRESS); geoLocationService.insert(geo); ArrayList<String> imgs = new ArrayList<>(); CulturalOffer offer = new CulturalOffer(null, CO_TITLE, " ", imgs); service.create(offer, CO_NEW_ADDRESS, CO_SUBTYPE); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testUpdateCulturalOfferWithInvalidId() throws Exception{ List<String> images = new ArrayList<>(); CulturalOffer updated = new CulturalOffer(null, CO_NEW_TITLE, CO_NEW_DESCRIPTION, images); service.update(50, updated); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testUpdateCulturalOfferWithNonUniqueName() throws Exception{ List<String> images = new ArrayList<>(); CulturalOffer updated = new CulturalOffer(null, CO_TAKEN_TITLE, CO_NEW_DESCRIPTION, images); service.update(CO_ID, updated); } @Test(expected = Exception.class) @Transactional @Rollback(true) public void testRemoveCulturalOfferWithInvalidId() throws Exception { service.delete(50); } @Test public void testGetAllInCurrentZoom() { ZoomDTO zoomDTO = new ZoomDTO( UPPER_LATITUDE, UPPER_LONGITUDE, LOWER_LATITUDE, LOWER_LONGITUDE ); List<CulturalOffer> culturalOffers = service.getAllInCurrentZoom(zoomDTO); assertThat(culturalOffers.size()).isEqualTo(EXPECTED_OFFERS); assertThat(culturalOffers.get(ROW_NUM).getGeoLocation().getLongitude()) .isBetween(UPPER_LONGITUDE, LOWER_LONGITUDE); } }
package tanks.tankField; import java.util.ArrayList; import java.util.Iterator; import java.util.Random; import javax.swing.Timer; import pool.Field; import resources.AllSounds; import score.Score; import square.BorderSquare; import square.Member; import strike.elements.Bullet; import strike.elements.Element; import strike.elements.Rocket; import strike.elements.Stone; import tanks.hangar.HeroTank; import tanks.hangar.Shell; public class TankField implements Field<Member[][]> { private String recordsFilePath = "Records/Tank.txt"; private Score score= new Score(recordsFilePath,150); private Timer timer = score.getTimer(); protected Member[][] field = null; private int column = 40; private int line = 15; private int startPosition=line-2; private HeroTank hTank ; private ArrayList<Shell> shells ; public TankField(int column, int line){ this.column = column; this.line = line; init(); } private void init(){ shells = new ArrayList<Shell>(); field = new Member[column][line]; for(int i=0;i<line;i++){ field[column-1][i]= new BorderSquare(column-1,i); field[0][i]= new BorderSquare(0,i); } for(int i=0;i<column;i++){ field[i][line-1]= new BorderSquare(i,line-1); field[i][0]=new BorderSquare(i,0); } Random generator = new Random(); for(int i=2;i<column-2;i++){ for(int j=2;j<line-2;j++){ if((i>column/2+1||i<column/2-1) && (j>line/2+1||j<line/2-1)) if(generator.nextBoolean()){ field[i][j]=new Stone(i,j); } } } hTank=new HeroTank(column/2,startPosition); deployOnField(hTank); } private void deployOnField(Member b){ field[b.getX()][b.getY()]=b; } private void removeFromField(Member b){ field[b.getX()][b.getY()]=null; } @Override public Timer letsGo() { timer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { go(); } }); timer.start(); return timer; } @Override public Timer pause() { // TODO Auto-generated method stub return null; } @Override public Member[][] getField() { return field; } @Override public void right() { if(HeroTank.RIGHT==hTank.getDirection()) if(collision(hTank)) return; removeFromField(hTank); hTank.moveRight(); deployOnField(hTank); } @Override public void left() { if(HeroTank.LEFT==hTank.getDirection()) if(collision(hTank)) return; removeFromField(hTank); hTank.moveLeft(); deployOnField(hTank); } public void fire(){ int dir=hTank.getDirection(); Shell shell=new Shell(hTank.getX(),hTank.getY(),dir); Member mem = field[shell.getX()][shell.getY()]; //if there is situation when under bullet exist stone if(mem!=null){ if(!(mem instanceof Shell)){ AllSounds.shot.multyPlay(); elementDestroy(mem); } return; } AllSounds.shot.multyPlay(); field[shell.getX()][shell.getY()]=shell; shells.add(shell); } private void elementDestroy(Member element){ if(element==null)return; if(!(element instanceof Element)){ AllSounds.ricochet.multyPlay(); return; } removeFromField(element); AllSounds.stoneDestroy.multyPlay(); } @Override public void go() { for(Shell s:shells){ removeFromField(s); if(collision(s)){ shells.remove(s); s.move(); elementDestroy(field[s.getX()][s.getY()]); return; } s.move(); deployOnField(s); } } private boolean collision(HeroTank tank){ Member mem; switch (tank.getDirection()){ case HeroTank.DOWN: mem=field[tank.getX()][tank.getY()+1];break; case HeroTank.UP: mem=field[tank.getX()][tank.getY()-1];break; case HeroTank.RIGHT: mem=field[tank.getX()+1][tank.getY()];break; case HeroTank.LEFT: mem=field[tank.getX()-1][tank.getY()];break; default: throw new IllegalArgumentException("Unknown direction"); } if(mem!=null) return true; return false; } @Override public void up() { if(HeroTank.UP==hTank.getDirection()) if(collision(hTank)) return; removeFromField(hTank); hTank.moveUp(); deployOnField(hTank); } @Override public void down() { if(HeroTank.DOWN==hTank.getDirection()) if(collision(hTank)) return; removeFromField(hTank); hTank.moveDown(); deployOnField(hTank); } @Override public int getScore() { // TODO Auto-generated method stub return 0; } @Override public String getBonusName() { // TODO Auto-generated method stub return null; } }
package eu.kutik.accelerometertest; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; public abstract class TestListener implements SensorEventListener { @Override public final void onSensorChanged(final SensorEvent event) { if (event != null && event.sensor != null && Sensor.TYPE_ACCELEROMETER == event.sensor.getType()) { onAccelerometerChanged(event); } } abstract void onAccelerometerChanged(final SensorEvent state); @Override public final void onAccuracyChanged(final Sensor sensor, final int accuracy) { //ignored } }
package 自定义注解; /** * Created by Yingjie.Lu on 2018/7/26. */ import java.lang.reflect.Field; /** * 注解解析器 */ public class FruitINfoUtil { public static void getFruitInfo(Class<?> clazz){ Field[] fields=clazz.getDeclaredFields(); for(Field f:fields){ if(f.isAnnotationPresent(FruitName.class)){ FruitName fruitName = (FruitName) f.getAnnotation(FruitName.class);//获得注解里的值 System.out.println(fruitName.value()); }else if(f.isAnnotationPresent(FruitColor.class)){ FruitColor fruitColor= (FruitColor) f.getAnnotation(FruitColor.class); System.out.println(fruitColor.fruitColor()); } } } public static void main(String[] args) throws Exception { getFruitInfo(Class.forName("自定义注解.Apple")); } }
package 新的线程创建方式; import java.util.concurrent.*; class RunnbaleDemo implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { if (i % 2 == 0){ System.out.println(Thread.currentThread().getName()+":"+i); } } } } class CallableDemo1 implements Callable { @Override public Object call() throws Exception { int sum = 0; for (int i = 0; i < 100; i++) { if (i % 2 != 0){ System.out.println(Thread.currentThread().getName()+":"+i); sum += i; } } return sum; } } public class ThreadPool { public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(10); //适用于callable service.submit(new CallableDemo1()); //适用于runnable service.execute(new RunnbaleDemo()); FutureTask futureTask = new FutureTask(new CallableDemo1()); try { Object sum = futureTask.get(); System.out.println(sum); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } service.shutdown(); } }
package org.gracejvc.vanrin.service; import java.util.List; import org.gracejvc.vanrin.dao.AdminDAOimpl; import org.gracejvc.vanrin.model.Admins; import org.springframework.transaction.annotation.Transactional; public class AdminServiceImpl implements AdminService { private AdminDAOimpl adminADO; public AdminServiceImpl(AdminDAOimpl adminADO) { this.adminADO = adminADO; } @Override @Transactional public List<Admins> allAdmins() { return adminADO.allAdmins(); } @Override @Transactional public void newAdmin(Admins admin) { this.adminADO.newAdmin(admin); } @Override @Transactional public void removeAdmin(int id) { this.adminADO.removeAdmin(id); } @Override @Transactional public void updateAdmin(Admins admin) { this.adminADO.updateAdmin(admin); } @Override @Transactional public Admins findAdminById(int id) { return this.adminADO.findAdminById(id); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.support; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.messaging.SubscribableChannel; /** * A {@link SubscribableChannel} that sends messages to each of its subscribers. * * @author Phillip Webb * @author Rossen Stoyanchev * @since 4.0 */ public class ExecutorSubscribableChannel extends AbstractSubscribableChannel { @Nullable private final Executor executor; private final List<ExecutorChannelInterceptor> executorInterceptors = new ArrayList<>(4); /** * Create a new {@link ExecutorSubscribableChannel} instance * where messages will be sent in the callers thread. */ public ExecutorSubscribableChannel() { this(null); } /** * Create a new {@link ExecutorSubscribableChannel} instance * where messages will be sent via the specified executor. * @param executor the executor used to send the message, * or {@code null} to execute in the callers thread. */ public ExecutorSubscribableChannel(@Nullable Executor executor) { this.executor = executor; } @Nullable public Executor getExecutor() { return this.executor; } @Override public void setInterceptors(List<ChannelInterceptor> interceptors) { super.setInterceptors(interceptors); this.executorInterceptors.clear(); interceptors.forEach(this::updateExecutorInterceptorsFor); } @Override public void addInterceptor(ChannelInterceptor interceptor) { super.addInterceptor(interceptor); updateExecutorInterceptorsFor(interceptor); } @Override public void addInterceptor(int index, ChannelInterceptor interceptor) { super.addInterceptor(index, interceptor); updateExecutorInterceptorsFor(interceptor); } private void updateExecutorInterceptorsFor(ChannelInterceptor interceptor) { if (interceptor instanceof ExecutorChannelInterceptor executorChannelInterceptor) { this.executorInterceptors.add(executorChannelInterceptor); } } @Override public boolean sendInternal(Message<?> message, long timeout) { for (MessageHandler handler : getSubscribers()) { SendTask sendTask = new SendTask(message, handler); if (this.executor == null) { sendTask.run(); } else { this.executor.execute(sendTask); } } return true; } /** * Invoke a MessageHandler with ExecutorChannelInterceptors. */ private class SendTask implements MessageHandlingRunnable { private final Message<?> inputMessage; private final MessageHandler messageHandler; private int interceptorIndex = -1; public SendTask(Message<?> message, MessageHandler messageHandler) { this.inputMessage = message; this.messageHandler = messageHandler; } @Override public Message<?> getMessage() { return this.inputMessage; } @Override public MessageHandler getMessageHandler() { return this.messageHandler; } @Override public void run() { Message<?> message = this.inputMessage; try { message = applyBeforeHandle(message); if (message == null) { return; } this.messageHandler.handleMessage(message); triggerAfterMessageHandled(message, null); } catch (Exception ex) { triggerAfterMessageHandled(message, ex); if (ex instanceof MessagingException messagingException) { throw messagingException; } String description = "Failed to handle " + message + " to " + this + " in " + this.messageHandler; throw new MessageDeliveryException(message, description, ex); } catch (Throwable err) { String description = "Failed to handle " + message + " to " + this + " in " + this.messageHandler; MessageDeliveryException ex2 = new MessageDeliveryException(message, description, err); triggerAfterMessageHandled(message, ex2); throw ex2; } } @Nullable private Message<?> applyBeforeHandle(Message<?> message) { Message<?> messageToUse = message; for (ExecutorChannelInterceptor interceptor : executorInterceptors) { messageToUse = interceptor.beforeHandle(messageToUse, ExecutorSubscribableChannel.this, this.messageHandler); if (messageToUse == null) { String name = interceptor.getClass().getSimpleName(); if (logger.isDebugEnabled()) { logger.debug(name + " returned null from beforeHandle, i.e. precluding the send."); } triggerAfterMessageHandled(message, null); return null; } this.interceptorIndex++; } return messageToUse; } private void triggerAfterMessageHandled(Message<?> message, @Nullable Exception ex) { for (int i = this.interceptorIndex; i >= 0; i--) { ExecutorChannelInterceptor interceptor = executorInterceptors.get(i); try { interceptor.afterMessageHandled(message, ExecutorSubscribableChannel.this, this.messageHandler, ex); } catch (Throwable ex2) { logger.error("Exception from afterMessageHandled in " + interceptor, ex2); } } } } }
package io.pivotal.pcc.ri.mwld.model.mapper; import io.pivotal.pcc.ri.mwld.model.gf.Order; import io.pivotal.pcc.ri.mwld.model.info.OrderInfo; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper(uses = { DateMapper.class }) public interface OrderInfoMapper { OrderInfoMapper MAPPER = Mappers.getMapper(OrderInfoMapper.class); OrderInfo map(Order source); }
package org.firstinspires.ftc.teamcode.ExampleRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.teamcode.ExampleRobot.Motors.ShooterMotor; import org.firstinspires.ftc.teamcode.Robot.DriveTrain; import org.firstinspires.ftc.teamcode.Robot.HwMap; /** * Created by Garrett on 4/4/2017. */ public class ExampleHardwareMap implements HwMap { HardwareMap hwMap; public DcMotor leftMotorA; public DcMotor leftMotorB; public DcMotor rightMotorA; public DcMotor rightMotorB; public DcMotor intakeMotor; public DcMotor shooterMotor; public DcMotor pusherMotor; public ExampleHardwareMap(HardwareMap hwMap){ this.hwMap = hwMap; leftMotorA = hwMap.dcMotor.get("left_driveA"); leftMotorB = hwMap.dcMotor.get("left_driveB"); rightMotorA = hwMap.dcMotor.get("right_driveA"); rightMotorB = hwMap.dcMotor.get("right_driveB"); intakeMotor = hwMap.dcMotor.get("intake"); shooterMotor = hwMap.dcMotor.get("shooter"); pusherMotor = hwMap.dcMotor.get("pusher"); } }
package com.loneless.second_task.entity; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Sentence { private List<Word> words=new ArrayList<>(); public List<Word> getWords() { return words; } public Word getWord(int index){ return words.get(index); } public void setWords(List<Word> words) { this.words = words; } public StringBuilder receiveIdea() { StringBuilder idea=new StringBuilder(); for (Word word : words) { idea.append(word.getWord().append(" ")); } return idea; } public void supplementation(Word word){ words.add(word); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sentence sentence = (Sentence) o; return Objects.equals(words, sentence.words); } @Override public int hashCode() { return Objects.hash(words); } @Override public String toString() { return "Sentence{" + "words=" + words + '}'; } }
package Testing; import util.BoundedBuffer; import util.MovePacket; public class testProducer implements Runnable { BoundedBuffer myB; static int[][] a = {{0, 1, 2}, {2, 1, 0}}; static int[][] b = {{2, 1, 0}, {0, 1, 2}}; static int amount = 0; public testProducer(BoundedBuffer b) { myB = b; } @Override public synchronized void run() { // TODO Auto-generated method stub try { while(true) { myB.put(new MovePacket()); amount++; if((amount % 10000000) == 0) { System.out.println("Amount of times we have 'put' a packet: " + amount); } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
import java.util.Arrays; public class NumberGameAgain { public long solve(int k, long[] table) { Arrays.sort(table); long[] powers = new long[k + 1]; powers[0] = 1; for(int i = 1; i < powers.length; ++i) { powers[i] = 2 * powers[i - 1]; } long total = 0; long worth = 0; long[] value = new long[table.length]; for(int i = k - 1, j = 0; 1 <= i; --i, ++j) { total += powers[i]; worth += powers[j]; for(int m = 0; m < table.length; ++m) { if(powers[i] <= table[m] && table[m] < powers[i + 1]) { value[m] = worth; } } } for(int i = table.length - 1; 0 <= i; --i) { while(table[i] != 1) { for(int j = 0; j < i; ++j) { if(table[i] == table[j]) { value[i] = 0; } } table[i] /= 2; } } for(int i = 0; i < value.length; ++i) { total -= value[i]; } return total; } }
//antar at dette vil skrive ut 5 public class MinKlasse { public int a = 0; public MinKlasse(int b) { a = b; } public static void main(String[] args) { MinKlasse obj = new MinKlasse(5); System.out.println(obj.a); } }
package com.heihei.model.msg.api; import com.heihei.model.msg.bean.AbstractMessage; import com.heihei.model.msg.bean.GiftMessage; import com.heihei.model.msg.bean.LiveMessage; public interface LiveMessageCallback extends MessageCallback { public void addTextCallbackView(AbstractMessage message); public void addGiftCallbackView(GiftMessage message); public void addLiveLikeCallbackView(LiveMessage message); }
package com.asiainfo.worktime.service; import java.util.List; import com.asiainfo.worktime.model.WorkStateModel; public interface WorkStateService { List<WorkStateModel> getAllStates(); }
package edu.ucsb.cs56.pconrad.parsing.tokenizer; public class EqualsToken extends Token { @Override public String toString() { return "EqualsToken"; } }
import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket= new DatagramSocket(9876); byte[] receiveData= new byte[1024]; byte[] sendData= new byte[1024]; while(true) { DatagramPacket receivePacket= new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); int rcvLen = receivePacket.getLength(); String sentence = new String(receivePacket.getData(), 0, rcvLen,"UTF-8"); InetAddress ipAddress= receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence= sentence.toUpperCase(); sendData = capitalizedSentence.getBytes("UTF-8"); DatagramPacket sendPacket= new DatagramPacket(sendData,sendData.length, ipAddress, port); serverSocket.send(sendPacket); } } }
package com.example.awesoman.owo2_comic.httpmanager; /** * Created by Awesome on 2017/6/1. */ public class HttpParam { public static final String KEY = "key"; }
package nichol.springframework.springpetclinic.services.jpa; import nichol.springframework.springpetclinic.model.PetType; import nichol.springframework.springpetclinic.repositories.PetTypeRepository; import nichol.springframework.springpetclinic.services.PetTypeService; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.Optional; import java.util.Set; @Service @Profile("jpadata") public class PetTypeJpaService implements PetTypeService { private final PetTypeRepository petTypeRepository; public PetTypeJpaService(PetTypeRepository petTypeRepository) { this.petTypeRepository = petTypeRepository; } @Override public Set<PetType> findAll() { Set<PetType> petTypes = new HashSet<>(); petTypeRepository.findAll().forEach(petTypes::add); return petTypes; } @Override public PetType findById(Long id) { Optional<PetType> optionalPetType = petTypeRepository.findById(id); return optionalPetType.orElse(null); } @Override public PetType save(PetType petType) { return petTypeRepository.save(petType); } @Override public void delete(PetType petType) { petTypeRepository.save(petType); } @Override public void deleteById(Long id) { petTypeRepository.deleteById(id); } }
package com.mao.springdata.springjpaquery.controller; import com.mao.springdata.springjpaquery.bean.Clazz; import com.mao.springdata.springjpaquery.bean.Student; import com.mao.springdata.springjpaquery.service.SchoolService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Map; @RestController @RequestMapping("/school") public class SchoolController { @Autowired private SchoolService schoolService; @RequestMapping("/save") public String save(){ Clazz cl1=new Clazz("firstClass"); Clazz cl2=new Clazz("secondClass"); List<Clazz> list=new ArrayList<>(); list.add(cl1); list.add(cl2); schoolService.saveClazzAll(list); Student student=new Student("jack","xian",10,'男',cl1); Student student2=new Student("jack2","xian",20,'男',cl1); Student student3=new Student("jack3","xian",30,'男',cl2); List<Student> list2=new ArrayList<>(); list2.add(student); list2.add(student2); list2.add(student3); schoolService.saveStudentAll(list2); return "保存学生成功"; } /* 查询某个班级所有学生姓名、年龄、性别 */ @RequestMapping("/getClazzStus") public List<Map<String,Object>> getClazzStu(String clazzName){ return schoolService.getStusByClazzName(clazzName); } /* 查询某个班级所有学生姓名、年龄 */ @RequestMapping("/findNameAndSexByClazzName") public List<Map<String,Object>> findNameAndSexByClazzName(String clazzName){ return schoolService.findNameAndSexByClazzName(clazzName); } /* 某个班级某种性别所有学生名字 */ @RequestMapping("/findNameByClazzNameAndSex") public List<String> findNameByClazzNameAndSex(String clazzName,Character sex){ return schoolService.findNameByClazzNameAndSex(clazzName,sex); } /* 查询某个学生属于哪个班级 */ @RequestMapping("/findClazzNameByStudentName") public String findClazzNameByStudentName(String stuName){ return schoolService.findClazzNameByStuName(stuName); } /* 删除某个学生对象 */ @RequestMapping("/delteStuByStuName") public String delteStuByStuName(String stuName){ schoolService.deleteStuByName(stuName); return "delete sucess"; } }
/** * * @author E14010 */ public class Complex { private final double x,y; public Complex(double x0,double y0) { this.x=x0; this.y=y0; } public double getX() { return x; } public double getY() { return y; } // for get the (x^2 + y^2)=|z|^2 value for any z=x + yi public double abs2(){ double abs2 = 0d; abs2= x*x + y*y ; return abs2; } // To take the 2 to the power of this complex public Complex pow2(){ Complex ztimes=null; double zx=x*x - y*y; double zy=2*x*y; ztimes = new Complex(zx, zy); return ztimes; } // for adding the complex z public Complex plus(Complex z){ Complex zans=null; double zx=this.x + z.getX(); double zy=this.y + z.getY(); zans = new Complex(zx, zy); return zans; } }
package com.basket.together; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BasketTogetherApplication { public static void main(String[] args) { SpringApplication.run(BasketTogetherApplication.class, args); } }
package framework; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import java.util.List; /** * Created by nika.khaladkar on 18/08/2016. */ public class CheckoutYourDetailsPage extends BasePage { @FindBy(how = How.CSS, using = "input[value='Next']") private WebElement nextButtonElement; public CheckoutYourDetailsPage(WebDriver driver){ super(driver); PageFactory.initElements(driver, this); } public void enterYourContactDetailsForHAH(String email_address){ new Select(driver.findElement(By.id("order_ship_address_attributes_title"))).selectByVisibleText("Mr"); driver.findElement(By.id("order_ship_address_attributes_firstname")).sendKeys("TestUserFirstname"); driver.findElement(By.id("order_ship_address_attributes_lastname")).sendKeys("TestUserLastname"); int randomPhoneNumber; randomPhoneNumber = 100 + (int)(Math.random() * ((999999999 - 99) + 1)); int initialDigits = 07; System.out.println("\n"); System.out.println("User Phone number:"+ initialDigits+""+randomPhoneNumber); driver.findElement(By.id("order_ship_address_attributes_phone")).sendKeys("07"+randomPhoneNumber); driver.findElement(By.id("order_email_confirmation")).sendKeys(email_address); System.out.println("User Email address :"+ email_address); JavascriptExecutor js =(JavascriptExecutor)driver; js.executeScript("$('#order_hivehome_info_attributes_heating_control_separate_from_boiler').parent('.iradio').iCheck('check');"); driver.findElement(By.id("postcodelookup")).sendKeys("SL2 5GF"); driver.findElement(By.xpath(".//*[@data-omniture-ref='PostcodeLU_CTA']")).click(); Utilities.waitForSomeTime(); WebElement unorderedList = driver.findElement(By.className("lookup-results")); selectValueFromUnorderedList(unorderedList, "Flat 73 The Junction Grays Place, Slough"); Utilities.waitForSomeTime(); } public void enterYourContactDetailsForLights(String email_address){ new Select(driver.findElement(By.id("order_ship_address_attributes_title"))).selectByVisibleText("Mr"); driver.findElement(By.id("order_ship_address_attributes_firstname")).sendKeys("TestUserFirstname"); driver.findElement(By.id("order_ship_address_attributes_lastname")).sendKeys("TestUserLastname"); driver.findElement(By.id("order_ship_address_attributes_phone")).sendKeys("07720240790"); driver.findElement(By.id("order_email_confirmation")).sendKeys("testuser250701@yopmail.com"); //click on postcode lookup driver.findElement(By.id("postcodelookup")).sendKeys("SL2 5GF"); //Postcode lookup for Lights kit driver.findElement(By.xpath(".//*[@id='shipping']/div[2]/div/div[7]/div/div[2]/div[1]/a")).click(); WebElement unorderedList = driver.findElement(By.className("lookup-results")); selectValueFromUnorderedList(unorderedList, "Flat 73 The Junction Grays Place, Slough"); JavascriptExecutor js =(JavascriptExecutor)driver; js.executeScript("$('#order_terms_and_conditions').parent('.icheckbox').iCheck('check');"); new Select(driver.findElement(By.id("order_ship_address_attributes_title"))).selectByVisibleText("Mr"); driver.findElement(By.id("order_ship_address_attributes_firstname")).sendKeys("TestUserFirstname"); driver.findElement(By.id("order_ship_address_attributes_lastname")).sendKeys("TestUserLastname"); int randomPhoneNumber; randomPhoneNumber = 100 + (int)(Math.random() * ((999999999 - 99) + 1)); int initialDigits = 07; System.out.println("\n"); System.out.println("User Phone number:"+ initialDigits+""+randomPhoneNumber); driver.findElement(By.id("order_ship_address_attributes_phone")).sendKeys("07"+randomPhoneNumber); driver.findElement(By.id("order_email_confirmation")).sendKeys(email_address); System.out.println("User Email address :"+ email_address); JavascriptExecutor js1 =(JavascriptExecutor)driver; js1.executeScript("$('#order_hivehome_info_attributes_heating_control_separate_from_boiler').parent('.iradio').iCheck('check');"); driver.findElement(By.id("postcodelookup")).sendKeys("SL2 5GF"); driver.findElement(By.xpath(".//*[@data-omniture-ref='PostcodeLU_CTA']")).click(); Utilities.waitForSomeTime(); WebElement unorderedList1 = driver.findElement(By.className("lookup-results")); selectValueFromUnorderedList(unorderedList1, "Flat 73 The Junction Grays Place, Slough"); Utilities.waitForSomeTime(); } public void goToBookAppointmentPage(){ nextButtonElement.click(); Utilities.waitForSomeTime(); } public void goToPaymentPage(){ nextButtonElement.click(); Utilities.waitForSomeTime(); } public void selectValueFromUnorderedList (WebElement unorderedList, final String value) { List<WebElement> options = unorderedList.findElements(By.tagName("li")); for (WebElement option : options) { if (value.equals(option.getText())) { option.click(); break; } } } }
package com.hwj.daoImpl; import java.math.BigInteger; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.hwj.dao.IMindMapDao; import com.hwj.entity.MindMap; import com.hwj.entity.MindNode; @Repository("IMindMapDao") public class MindMapDaoImpl extends BaseDaoImpl<MindMap> implements IMindMapDao { @Resource private SessionFactory sessionFactory; public Session getCurrentSession() { Session session = null; try { session = this.sessionFactory.getCurrentSession(); } catch (Exception e) { System.out.println(e); } return session; } /** * @author Ragty * @param 查询知识图谱(教师端) * @serialData 2018.6.14 */ @Override public List<MindMap> queryMindNap(Object value1, Integer currentPage, Integer pageSize) { String hql = "select * from Mind_map as model where model.nodename like '%" + value1 + "%'"; hql += " or model.userid like '%"+value1+"%'"; hql += " or model.realname like '%"+value1+"%'"; Query query = ((SQLQuery) getCurrentSession().createSQLQuery(hql). setFirstResult((currentPage-1)*pageSize).setMaxResults(pageSize)).addEntity(MindMap.class); @SuppressWarnings("unchecked") List<MindMap> list=query.list(); if(list.size()>0){ return list; } return null; } /** * @author Ragty * @param 查询获取知识图谱总条数 * @serialData 2018.6.14 */ @Override public Long searchMapPage(Object value1) { // TODO Auto-generated method stub String hql = "select count(*) from Mind_map as model where model.nodename like '%" + value1 + "%'"; hql += " or model.userid like '%"+value1+"%'"; hql += " or model.realname like '%"+value1+"%'"; Query query = getCurrentSession().createSQLQuery(hql); BigInteger big = (BigInteger) query.uniqueResult(); Long total = big.longValue(); return total; } /** * @author Ragty * @param 获取当前知识图谱总条数 * @serialData 2018.6.14 */ @Override public Long getAllMapPage() { // TODO Auto-generated method stub String hql = "select count(*) from Mind_map"; Query query = getCurrentSession().createSQLQuery(hql); BigInteger big = (BigInteger) query.uniqueResult(); Long total = big.longValue(); return total; } /** * @author Ragty * @param 获取所有的图谱 * @serialData 2018.10.12 */ @Override public List<MindMap> getAllMap() { String sql = "select * from mind_map"; Query query = getCurrentSession().createSQLQuery(sql).addEntity(MindMap.class); @SuppressWarnings("unchecked") List<MindMap> list=query.list(); if(list.size()>0){ return list; } return null; } }
package com.Premium.bean; import lombok.Data; @Data public class Employee { private Integer employeeId; private String name; private String contactNumber; private String emailId; private Adderss address; public Employee(Integer employee_id, String name, String contact_number, String email_id, Adderss address) { super(); this.employeeId = employee_id; this.name = name; this.contactNumber = contact_number; this.emailId = email_id; this.address = address; } }
import static org.junit.Assert.*; import org.junit.Test; /* * Header * @Author: Aaron Lack, alack * Last edited: 4/29/20 * Class BST_TESTS, for JUNIT tests for all of my methods * Make a bst tree from main in BST.java and do assert equals for the testing. */ public class BST_TEST { @Test public void test() { BST<Integer, Character> bstTree = new BST<>(); bstTree.put((int) 'p','p'); bstTree.put((int) 'g','g'); bstTree.put((int) 'w','w'); bstTree.put((int) 'c','c'); bstTree.put((int) 'k','k'); bstTree.put((int) 's','s'); bstTree.put((int) 'c','c'); bstTree.put((int) 'y','y'); bstTree.put((int) 'a','a'); bstTree.put((int) 'a','a'); bstTree.put((int) 'e','e'); bstTree.put((int) 'i','i'); bstTree.put((int) 'q','q'); bstTree.put((int) 'u','u'); bstTree.put((int) 'q','q'); bstTree.put((int) 'x','x'); BST<Integer, Character> testTree = bstTree; //equals boolean output = bstTree.equals(testTree); assertEquals(output, true); //isBalanced boolean output2 = bstTree.isBalanced(); assertEquals(output2, true); //toString String output3 = bstTree.toString(); assertEquals(output3, "Pre-Order: 112 103 99 97 97 99 101 107 105 119 115 113 113 117 121 120 " + "\n" + "Post-Order: 97 97 101 99 99 105 107 103 113 113 117 115 120 121 119 112 " + "\n" + "In-Order: 97 97 99 99 101 103 105 107 112 113 113 115 117 119 120 121 "); //countLeafNode int output4 = bstTree.countLeafNodes(); assertEquals(output4, 6); //getOneChildNodes int output5 = bstTree.getOneChildNodes(); assertEquals(output5, 5); //getTwoChildrenNodes int output6 = bstTree.getTwoChildrenNodes(); assertEquals(output6, 5); //removeDuplicates BST<Integer, Character> removeTree = bstTree.removeDuplicates(); String output7 = removeTree.toString(); assertEquals(output7, "Pre-Order: 97 99 101 103 105 107 112 113 115 117 119 120 121 " + "\n" + "Post-Order: 121 120 119 117 115 113 112 107 105 103 101 99 97 " + "\n" + "In-Order: 97 99 101 103 105 107 112 113 115 117 119 120 121 "); //sumLeft int output8 = bstTree.sumLeft((int) 'p'); assertEquals(output8, 808); //sumRight int output9 = bstTree.sumRight((int) 'p'); assertEquals(output9, 818); //getUpperHalf BST<Integer, Character> upperTree = bstTree.getUpperHalf(); String output10 = upperTree.toString(); assertEquals(output10, "Pre-Order: 112 103 119 " + "\n" + "Post-Order: 103 119 112 " + "\n" + "In-Order: 103 112 119 "); } }
package org.sunshinelibrary.turtle.utils; import java.text.SimpleDateFormat; /** * User: fxp * Date: 10/21/13 * Time: 1:39 PM */ public class DateFormater { public static String format(long time) { SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm:ss"); return sdf.format(time); } }
/* * Copyright 2014 Chris Banes * * 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.forman.lib.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; /** * 收藏相关工具类 */ @SuppressWarnings("JavaDoc") public class CollectionsUtils { /** * 判断是否为空 * * @param collection * @return */ public static boolean isEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } /** * 获取size * * @param collection * @return */ public static int size(Collection<?> collection) { return collection != null ? collection.size() : 0; } /** * 取出两个列表中,相同的数据 * * @param list1 * @param l2 * @param <T> * @return */ public static <T> List<T> distinct(List<T> list1, List<T> l2) { HashSet<T> set = new HashSet<>(); List<T> result = new ArrayList<>(); set.addAll(list1); for (T t : l2) { boolean b = set.add(t); if (!b) { result.add(t); } } return result; } /** * 取出第二个列表中,不存在于第一个列表的数据,即第二个列表中的新数据 * * @param list1 * @param l2 * @param <T> * @return */ public static <T> List<T> getNewList(List<T> list1, List<T> l2) { List<T> result = new ArrayList<>(); for (T t : l2) { if (list1.contains(t)) continue; result.add(t); } return result; } }
package dbAssignment.opti_home_shop.data.model; import java.util.Objects; import javax.persistence.*; import com.sun.istack.NotNull; import org.hibernate.annotations.CreationTimestamp; @javax.persistence.Entity @Table(name = "inquiry") public class Inquiry { @Id @Column(name = "I_Id") @NotNull @GeneratedValue(strategy = GenerationType.IDENTITY) private int I_Id; public int getI_Id() { return this.I_Id; } @Column @NotNull private String I_Description; public String getI_Description() { return this.I_Description; } public void setI_Description(String value) { this.I_Description = value; } @Column @NotNull @CreationTimestamp private java.sql.Timestamp I_CreateDate; public java.sql.Timestamp getI_CreateDate() { return this.I_CreateDate; } @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinColumn(name = "CART_Id") @NotNull private Cart cart; public Cart getCart() { return cart; } public void setCart(Cart cart) { this.cart = cart; } public Inquiry(String I_Description_, Cart cart) { this.I_Description = I_Description_; this.cart = cart; } public Inquiry() { } @Override public String toString() { return I_Description; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Inquiry inquiry = (Inquiry) o; return Objects.equals(I_Id, inquiry.I_Id); } @Override public int hashCode() { return Objects.hash(I_Id, I_Description, I_CreateDate); } }
package be.openclinic.api; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import be.mxs.common.model.vo.healthrecord.TransactionVO; import be.mxs.common.util.db.MedwanQuery; import be.openclinic.finance.PatientInvoice; import be.openclinic.medical.ImagingOrder; import be.openclinic.system.SH; public class InvoiceList extends API { public InvoiceList(HttpServletRequest request) { super(request); } @Override public String get() { String s ="<invoicelist>"; if(exists("patientinvoiceid")) { PatientInvoice invoice = PatientInvoice.get(value("patientinvoiceid").split("\\.")[0]+"."+value("patientinvoiceid").split("\\.")[1]); if(invoice!=null) { s+=invoice.toXml(value("detail","extended").equalsIgnoreCase("extended")); } } else if(exists("personid")) { Vector<PatientInvoice> invoices = PatientInvoice.getPatientInvoices(value("personid")); for(int n=0;n<invoices.size();n++) { PatientInvoice invoice = PatientInvoice.get(invoices.elementAt(n).getUid()); if(exists("begindate") && invoice.getDate().before(SH.parseDate(value("begindate"),new SimpleDateFormat("yyyyMMddHHmmssSSS")))) { continue; } if(exists("enddate") && invoice.getDate().after(SH.parseDate(value("enddate"),new SimpleDateFormat("yyyyMMddHHmmssSSS")))) { continue; } if(exists("status") && !invoice.getStatus().equalsIgnoreCase(value("status"))) { continue; } if(exists("class") && !invoice.hasPrestationClass(value("class"))) { continue; } if(exists("family") && !invoice.hasPrestationFamily(value("family"))) { continue; } if(exists("invoicegroup") && !invoice.hasPrestationInvoiceGroup(value("invoicegroup"))) { continue; } if(exists("type") && !invoice.hasPrestationType(value("type"))) { continue; } if(exists("costcenter") && !invoice.hasPrestationCostCenter(value("costcenter"))) { continue; } s+=invoice.toXml(value("detail","extended").equalsIgnoreCase("extended")); } } s+="</invoicelist>"; return format(s); } @Override public String set() { String s= "<response error='0'>set operation not implemented</response>"; return format(s); } }
/** Program that creates a Question object which stores a question's attributes (i.e., answer, etc.) for playing a trivia game. @author Hiram Raulerson @version 1.0 E-mail Address: hhr3@students.uwf.edu. Last Changed: October 20, 2015. COP5007 Project #: 4 File Name: Question.java */ public class Question { /** Stores the question */ private String question; /** Stores the answer to the question */ private String answer; /** Stores the point value for the question */ private int points; /** Stores the ID for the question */ private int questionID; /** Stores the next ID for a question */ private static int nextID = 1; /** Constructs a Question object with the all instance variables set to default values */ public Question() { setQuestion(null); setAnswer(null); setPoints(1); setQuestionID(-1); } /** Constructs a Question object with the question set to the first parameter, the answer set to the second parameter, and question's point value set to the third parameter @param theQuestion the question @param theAnswer the answer to the question @param pts the points for answering the question correctly */ public Question(String theQuestion, String theAnswer, int pts) { setQuestion(theQuestion); setAnswer(theAnswer); setPoints(pts); setQuestionID(-1); } /** Constructs a Question object with the question set to the first parameter, the answer set to the second parameter, the question's point value set to the third parameter, and the question's ID set to the fourth parameter value. @param theQuestion the question @param theAnswer the answer to the question @param pts the points for answering the question correctly @param ID the question's ID */ public Question(String theQuestion, String theAnswer, int pts, int ID) { setQuestion(theQuestion); setAnswer(theAnswer); setPoints(pts); setQuestionID(ID); } /** Sets the question to the first parameter @param theQuestion the question */ public void setQuestion(String theQuestion) { if (theQuestion == null || theQuestion.equals("")) { question = "Who was the second U.S. President?"; setAnswer("John Adams"); } else { question = theQuestion; } } /** Sets the answer to the first parameter @param theAnswer the question's answer */ public void setAnswer(String theAnswer) { if (theAnswer == null || theAnswer.equals("")) { answer = "John Adams"; } else { answer = theAnswer; } } /** Sets the points for a question to the first parameter (if the parameter is between 1-5) @param pts the point value for the question */ public void setPoints(int pts) { try { if (pts < 1 || pts > 5) { points = 3; throw new QuestionIncorrectDataException("Question's point value out of range. Points set to 3 by default.\n"); } else { points = pts; } } catch (QuestionIncorrectDataException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println("\nProblems with setting the Question's points. Points set to 3 by default.\n"); } } /** Sets the ID for a question to the using the instance variable nextID @param i the question's ID (if -1 - use nextID to set the ID) */ public void setQuestionID(int i) { if (i == -1) { questionID = getNextID(); updateNextID(); } else { questionID = i; } } /** Increments the next ID for a question ID */ private void updateNextID() { ++nextID; } /** Returns the question @return the question */ public String getQuestion() { return question; } /** Returns the answer to the question @return the question's answer */ public String getAnswer() { return answer; } /** Returns the points for the question @return the question's points */ public int getPoints() { return points; } /** Returns the ID for the question @return the question's ID */ public int getQuestionID() { return questionID; } /** Returns the next ID for a question @return the next ID for a question */ private static int getNextID() { return nextID; } /** Returns a nicely formatted String composed of all of the question object's details @return the details of a question object */ public String toString() { return ("Question:\t\t" + getQuestion() + "\nQuestion's Answer:\t" + getAnswer() + "\nQuestions Point Value:\t" + getPoints() + "\nQuestion ID:\t\t" + getQuestionID() + "\n"); } }
package com.whl.datafiles.customize.entity; import com.whl.datafiles.customize.annotation.WElement; import com.whl.datafiles.customize.annotation.WTable; @WTable("uuser") public class User{ @WElement("fid") private String id; @WElement("12") private String age; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package com.flyusoft.apps.jointoil.service; import java.util.Date; import java.util.List; import com.flyusoft.apps.jointoil.entity.OneIntegratedMachine; import com.flyusoft.apps.jointoil.entity.TwoScrewMachine; import com.flyusoft.common.orm.Page; public interface TwoScrewMachineService { public void save(TwoScrewMachine twoScrewMachine); public TwoScrewMachine searchMonitorDataByLastTime(String compressorCode); /** * 根据压缩机编码 查找最后几分种的数据 * @param _compressorCode 压缩机编码 * @param _timeInterval 分钟 * @return */ public List<TwoScrewMachine> getDataByCompressorCodeAndTimeInterval(String _compressorCode,int _timeInterval); public List<TwoScrewMachine> getDataByCompressor(String _compressorCode, Date datetime); /** * 获取时间数据 * @param pageMonitor * @param wellNo * @param start_date * @param end_date * @return */ public Page<TwoScrewMachine> getTwoScrewMsg(Page<TwoScrewMachine> pageMonitor, String compressorCode, Date start_date, Date end_date); }
package io.gtrain.util.verifier.base; /** * @author William Gentry */ interface EndpointVerifier { boolean isOk(); boolean isForbidden(); }
/* * Copyright 2016 Florian Spieß (Minn). * * 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 minn.music.commands; import minn.music.MusicBot; import net.dv8tion.jda.JDA; import net.dv8tion.jda.entities.Guild; import net.dv8tion.jda.entities.Message; import net.dv8tion.jda.entities.MessageChannel; import net.dv8tion.jda.entities.User; import net.dv8tion.jda.events.message.MessageReceivedEvent; import net.dv8tion.jda.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.utils.SimpleLog; import java.util.function.Consumer; public abstract class GenericCommand { /** * Returns true if the command is allowed in private channels. * * @return boolean * Default true. */ public boolean isPrivate() { return true; } /** * Used to find commands. * * @return alias */ public abstract String getAlias(); /** * Used to get info about the command. * * @return Info */ public String getInfo() { return getAlias() + " " + getAttributes(); } /** * Must be implemented by sub-class. * * @param event A CommandEvent implementation. */ public abstract void invoke(CommandEvent event); /** * Attributes this command requires. * * @return String */ public String getAttributes() { return ""; } /** * Wrapper to allow shortcuts. */ public static class CommandEvent { private final static SimpleLog LOG = SimpleLog.getLog("CommandSender"); /** * Used if it allows private and guild invokes. */ public MessageReceivedEvent messageEvent; /** * Used if it doesn't allow private invokes. */ public GuildMessageReceivedEvent guildEvent; public final boolean isPrivate; public final MessageChannel channel; public final Guild guild; public final JDA api; public final User author; public final Message message; public final String allArgs; public final String[] args; public CommandEvent(MessageReceivedEvent event, String trimmed) { channel = event.getChannel(); guild = event.getGuild(); api = event.getJDA(); author = event.getAuthor(); message = event.getMessage(); isPrivate = event.isPrivate(); String[] parts = trimmed.split("\\s+", 2); if (parts.length > 1) { this.allArgs = parts[1]; this.args = allArgs.split("\\s+"); } else { this.allArgs = ""; this.args = new String[0]; } messageEvent = event; } public CommandEvent(GuildMessageReceivedEvent event, String trimmed) { channel = event.getChannel(); guild = event.getGuild(); api = event.getJDA(); author = event.getAuthor(); message = event.getMessage(); isPrivate = false; String[] parts = trimmed.split("\\s+", 2); if (parts.length > 1) { this.allArgs = parts[1]; this.args = allArgs.split("\\s+"); } else { this.allArgs = ""; this.args = new String[0]; } guildEvent = event; } public void send(String message) { send(message, null); } public void send(String message, Consumer<Message> callback) { try { message = message.replace(MusicBot.config.token, "<place token here>").replace("@everyone", "@\u0001everyone").replace("@here", "@\u0001here"); // no mass mentions or token channel.sendMessageAsync(message, msg -> { if (callback != null) new Thread(() -> { try { callback.accept(msg); } catch (Exception e) { SimpleLog.getLog("SenderThread").fatal(e); } }, "Async Callback Accept").start(); }); // async } catch (Exception e) { LOG.warn("A message was not sent due to " + e.getClass().getSimpleName() + ": " + e.getMessage()); if (callback != null) new Thread(() -> callback.accept(null), "Async Callback Accept").start(); } } } public String toString() { return getAlias() + "(" + getAttributes() + ")"; } }
import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { // 地址(主页-西洋) private static final String URL = "http://x771112.com/bbs/thread.php?fid=54"; // 域名 private static final String DOMAIN = "http://x771112.com/bbs/read.php?tid="; // 获取主页中分页地址的正则 private static final String ADDRURL_REG = "<a href=.*?subject_t f14"; // 获取img标签正则 src="(.+?\.jpg)" border private static final String IMGURL_REG = "src=.http(.*?)jpg(.*?)border"; // 获取src路径的正则 http:(.*?)\\.jpg private static final String IMGSRC_REG = "[a-zA-z]+://[^\\s]*"; public static void main(String[] args) { try { Main cm = new Main(); // 获得主页html文本内容 String HTML = cm.getHtml(URL); // 判断主页源代码打开是否取得成功 if (HTML.substring(0, 11).equals("请刷新页面或按键盘F5")) { System.out.println("主页源代码取得失败|NG"); System.out.println("失败URL:" + URL); return; } else { System.out.println("主页源代码取得成功|OK"); } // 获取分页标签 List<String> addressUrl = cm.getAddressUrl(HTML); // debug:: // System.out.println(addressUrl); // 循环打开分页地址下载图片 for (String address : addressUrl) { // 拼接完整的分页地址 String addressStr = DOMAIN + address.substring(22, 29); // debug::打印分页地址 System.out.println(addressStr); // 获得分页html文本内容 String ADDRHTML = cm.getHtml(addressStr); // 判断分页源代码打开是否取得成功 if (ADDRHTML.substring(0, 11).equals("请刷新页面或按键盘F5")) { // System.out.println("分页源代码取得失败|NG"); continue; // 其中一个分页打开失败调到下一个分页 } else { System.out.println("分页源代码取得成功|OK"); } // 获取图片标签 List<String> imgUrl = cm.getImageUrl(ADDRHTML); // debug:: System.out.println(imgUrl); // 获取图片src地址 List<String> imgSrc = cm.getImageSrc(imgUrl); // debug:: System.out.println(imgSrc); // 下载图片 cm.Download(imgSrc); } System.out.println("图片下载完成|Finish"); } catch (Exception e) { System.out.println("发生错误"); } } // 获取HTML内容 private String getHtml(String url) throws Exception { URL url1 = new URL(url); URLConnection connection = url1.openConnection(); InputStream in = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line, 0, line.length()); sb.append('\n'); } br.close(); isr.close(); in.close(); return sb.toString(); } // 获取AddressUrl地址 private List<String> getAddressUrl(String html) { Matcher matcher = Pattern.compile(ADDRURL_REG).matcher(html); List<String> listaddressurl = new ArrayList<String>(); while (matcher.find()) { listaddressurl.add(matcher.group()); } return listaddressurl; } // 获取ImageUrl地址 private List<String> getImageUrl(String html) { Matcher matcher = Pattern.compile(IMGURL_REG).matcher(html); List<String> listimgurl = new ArrayList<String>(); while (matcher.find()) { listimgurl.add(matcher.group()); } return listimgurl; } // 获取ImageSrc地址 private List<String> getImageSrc(List<String> listimageurl) { List<String> listImageSrc = new ArrayList<String>(); for (String image : listimageurl) { Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image); while (matcher.find()) { listImageSrc.add(matcher.group().substring(0, matcher.group().length() - 1)); } } return listImageSrc; } // 下载图片 private void Download(List<String> listImgSrc) { try { // 开始时间 Date begindate = new Date(); for (String url : listImgSrc) { // 开始时间 Date begindate2 = new Date(); String imageName = url.substring(url.lastIndexOf("/") + 1, url.length()); URL uri = new URL(url); InputStream in = uri.openStream(); FileOutputStream fo = new FileOutputStream(new File("src/res/" + imageName)); byte[] buf = new byte[1024]; int length = 0; System.out.println("开始下载:" + url); while ((length = in.read(buf, 0, buf.length)) != -1) { fo.write(buf, 0, length); } in.close(); fo.close(); System.out.println(imageName + "下载完成"); // 结束时间 Date overdate2 = new Date(); double time = overdate2.getTime() - begindate2.getTime(); System.out.println("耗时:" + time / 1000 + "s"); } Date overdate = new Date(); double time = overdate.getTime() - begindate.getTime(); System.out.println("总耗时:" + time / 1000 + "s"); } catch (Exception e) { System.out.println("下载失败"); } } }
package io.chark.food.app.administrate.article.category; import io.chark.food.domain.article.category.ArticleCategory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping(value = "/administrate") public class ArticleCategoryAdministrationController { private final ArticleCategoryAdministrationService administrationService; @Autowired public ArticleCategoryAdministrationController(ArticleCategoryAdministrationService administrationService) { this.administrationService = administrationService; } /** * Article category administration page. * * @return template for administrating article categories. */ @RequestMapping(value = "/articles/categories", method = RequestMethod.GET) public String articleCategoryAdministration() { return "administrate/article_categories"; } /** * Get a single article category administration page, if negative id is provided, a empty article category template is returned. * * @return single article category administration template. */ @RequestMapping(value = "/articles/categories/{id}", method = RequestMethod.GET) public String getCategory(@PathVariable long id, Model model) { ArticleCategory category; if (id <= 0) { // Id below or equals to zero means this is a new article cagegory. category = new ArticleCategory(); } else { // Id is above zero, existing account. category = administrationService.getCategory(id); } model.addAttribute("category", category); return "administrate/article_category"; } /** * Create a new user article category or update an existing one based on provided id. * * @return article category administration page or the same page if an error occurred. */ @RequestMapping(value = "/articles/categories/{id}", method = RequestMethod.POST) public String saveCategory(@PathVariable long id, ArticleCategory category, Model model) { if (!administrationService.saveCategory(id, category).isPresent()) { model.addAttribute("error", "Failed to create article category," + " please double check the details you've entered."); model.addAttribute("category", category); return "administrate/article_category"; } return "redirect:/administrate/articles/categories"; } /** * Get list of article categories. * * @return list of article categories. */ @ResponseBody @RequestMapping(value = "/api/articles/categories", method = RequestMethod.GET) public List<ArticleCategory> getCategories() { return administrationService.getCategories(); } /** * Delete specified article category by id. */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/api/articles/categories/{id}", method = RequestMethod.DELETE) public void delete(@PathVariable long id) { administrationService.delete(id); } }
package com.atguigu.java3; /* 类的成员之 : 代码块 作用 : 对Java类或对象进行初始化 格式: {} 注意:代码块只能被static修饰 静态代码块: 1.静态代码块是随着类的加载而加载的,且只加载一次。 2.静态代码块的执行优先于非静态代码块。 3.静态代码块可以有多个,执行顺序是从上到下依次执行。 4.静态代码块中不能调用实例变量和非静态方法 非静态代码块 1.非静态代码块是随着对象的创建而加载的 2.非静态代码块优先构造器的执行 3.非静态代码块可以有多个,执行顺序是从上到下依次执行。 4.非静态代码块中可以调用类变量和静态方法。 注意: 使用静态代码块初始化的特点 : 类加载的时候只加载(初始化)一次。 (如果是构造器初始化,每创建一个对象就会初始化一次。 如果是静态方法进行初始化,那么每调用一次方法初始化一次) */ public class BlockTest { public static void main(String[] args) { new Dog(); new Dog(); new Dog(); // Dog.show(); } } class Dog{ int age; static int sex; //非静态代码块 { System.out.println("非静态代码块1" + age + " " + sex); show(); } /* { System.out.println("非静态代码块2"); } { System.out.println("非静态代码块3"); } */ //静态代码块 - 不能调用实例变量和非静态方法 static { System.out.println("静态代码块1" + " " + sex); // info(); show(); } /* static { System.out.println("静态代码块2"); } static { System.out.println("静态代码块3"); } */ public Dog(){ System.out.println(" Dog()"); } public void info(){ //局部代码块 - 好处是不用等到方法结束再让局部变量出栈。 { int a = 10; } int b = 10; while(true){ System.out.println("cccccc"); } } public static void show(){ System.out.println("show static"); } }
package com.xwj.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.xwj.service.AsyncService; /** * 异步调用 * * @author xwj */ @RestController @RequestMapping("async") public class AsyncController { @Autowired private AsyncService asyncService; @RequestMapping("/test") public String async() { System.out.println("####AsyncController#### 1"); asyncService.doAsync1(); // asyncService.doAsync2(); System.out.println("####AsyncController#### 2"); return "success"; } }
class DemoArray { public static void main(String[]args) { int add_month[] = new int[12]; int month_day [] = {31,28,31,30,31,30,31,31,30,31,30,31}; String month_name[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; for(int i=0;i<12;i++) { add_month[i] =month_day[i]; } for(int i=0;i<12;i++) System.out.println(month_name[i]+" "+add_month[i]); } }
package com.jinglangtech.teamchat; import android.app.ActivityManager; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.Vibrator; import android.support.multidex.MultiDexApplication; import android.text.TextUtils; import android.util.Log; import android.widget.RemoteViews; import com.alibaba.fastjson.JSON; import com.jinglangtech.teamchat.activity.ChatGroupActivity; import com.jinglangtech.teamchat.dbmanager.DbMigration; import com.jinglangtech.teamchat.model.PushData; import com.jinglangtech.teamchat.network.RetrofitUtil; import com.jinglangtech.teamchat.util.ConfigUtil; import com.jinglangtech.teamchat.util.Key; import com.jinglangtech.teamchat.util.ToastUtil; import com.umeng.commonsdk.UMConfigure; import com.umeng.message.IUmengCallback; import com.umeng.message.IUmengRegisterCallback; import com.umeng.message.MsgConstant; import com.umeng.message.PushAgent; import com.umeng.message.UTrack; import com.umeng.message.UmengMessageHandler; import com.umeng.message.UmengNotificationClickHandler; import com.umeng.message.entity.UMessage; import org.android.agoo.huawei.HuaWeiRegister; import org.android.agoo.mezu.MeizuRegister; import org.android.agoo.xiaomi.MiPushRegistar; import java.util.List; import cn.jpush.android.api.JPushInterface; import io.realm.Realm; import io.realm.RealmConfiguration; //import cn.jpush.android.api.JPushInterface; public class App extends MultiDexApplication{ public static String mJPushRegId = ""; public String mUmengToken = null; public static boolean mIsChatPage = false; public PushAgent mPushAgent= null; @Override public void onCreate() { super.onCreate(); RetrofitUtil.initRetrofit();//Retrofit 初始化 ToastUtil.setContext(this); //JPushInterface.setDebugMode(false); //JPushInterface.init(this); /** * 初始化common库 * 参数1:上下文,不能为空 * 参数2:友盟 AppKey * 参数3:友盟 Channel * 参数4:设备类型,UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子,默认为手机 * 参数5:Push推送业务的secret */ UMConfigure.init(this, "5ac9b6e1f43e480965000041", "jlt_umeng_push", UMConfigure.DEVICE_TYPE_PHONE, "e0381b79c7fcea26bad99c531e0b7140"); registerUmengPushService(); initRealm(); } private void initRealm(){ Realm.init(this); RealmConfiguration config = new RealmConfiguration.Builder() .schemaVersion(1) .migration(new DbMigration()) .build(); Realm.setDefaultConfiguration(config); } //注册友盟推送服务 public void registerUmengPushService(){ mPushAgent = PushAgent.getInstance(this); //设置冷却时间为3秒 mPushAgent.setMuteDurationSeconds(3); //关闭免打扰模式:即24小都开启 mPushAgent.setNoDisturbMode(0, 0, 0, 0); mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE); //声音 mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);//呼吸灯 mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);//振动 //应用在前台时否显示通知 mPushAgent.setNotificaitonOnForeground(false); //注册推送服务,每次调用register方法都会回调该接口 mPushAgent.register(new IUmengRegisterCallback() { @Override public void onSuccess(String deviceToken) { //注册成功会返回device token mUmengToken = deviceToken; } @Override public void onFailure(String s, String s1) { Log.e("", "registerUmengPushService failed: " + s +", "+ s1); } }); umengNotifyProcess(); HuaWeiRegister.register(this); MiPushRegistar.register(this, "2882303761517763828", "5101776331828"); MeizuRegister.register(this, "1000103", "e1bd9a94a46d4cffbfe288a1204a0c87"); } private UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() { @Override public void dealWithCustomAction(Context context, UMessage msg) { Log.e("############ Notify: ", "############ Notify:" + msg.custom); } }; private UmengMessageHandler messageHandler = new UmengMessageHandler(){ /** * 通知的回调方法(通知送达时会回调) */ @Override public void dealWithNotificationMessage(Context context, UMessage msg) { //调用super,会展示通知,不调用super,则不展示通知。 super.dealWithNotificationMessage(context, msg); Log.e("############ Notify:", "############ dealWithNotificationMessage:" + msg.toString()); } /** * 自定义消息的回调方法 */ @Override public void dealWithCustomMessage(final Context context, final UMessage msg) { new Handler(getMainLooper()).post(new Runnable() { @Override public void run() { // 对于自定义消息,PushSDK默认只统计送达。若开发者需要统计点击和忽略,则需手动调用统计方法。 boolean isClickOrDismissed = true; if(isClickOrDismissed) { //自定义消息的点击统计 UTrack.getInstance(getApplicationContext()).trackMsgClick(msg); } else { //自定义消息的忽略统计 UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg); } Log.e("############ Notify:", "############ Message:" + msg.custom); processExtra(context, msg.custom); } }); } //自定义通知栏样式 @Override public Notification getNotification(Context context, UMessage msg) { switch (msg.builder_id) { case 1: Notification.Builder builder = new Notification.Builder(context); RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notify_layout); myNotificationView.setTextViewText(R.id.title, msg.title); myNotificationView.setTextViewText(R.id.text, msg.text); myNotificationView.setImageViewResource(R.id.image, getSmallIconId(context, msg)); builder.setContent(myNotificationView) .setSmallIcon(getSmallIconId(context, msg)) .setTicker(msg.ticker) .setAutoCancel(true); builder.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.DEFAULT_LIGHTS); return builder.getNotification(); default: //默认为0,若填写的builder_id并不存在,也使用默认。 return super.getNotification(context, msg); } } }; public void umengNotifyProcess(){ mPushAgent.setNotificationClickHandler(notificationClickHandler); mPushAgent.setMessageHandler(messageHandler); } private void processExtra(Context ctx, String extraMsg){ //if (!isAppForceground(ctx)){ // return; //} //if (!App.mIsChatPage){ // return; //} PushData dateInfo = null; if (!TextUtils.isEmpty(extraMsg)) { try { dateInfo = JSON.parseObject(extraMsg, PushData.class); if (dateInfo != null){ if (App.mIsChatPage){ notificationOper(); } Intent intent = new Intent(ChatGroupActivity.RECEIVE_MSG_CUSTOM_ACTION); intent.putExtra("jpushRoomId", dateInfo.roomid); ctx.sendBroadcast(intent); } } catch (Exception e) { } } } private void notificationOper(){ boolean issNoticeVoiceOpen = ConfigUtil.getInstance(this).get(Key.NOTICE_VOICE_OPEN, true); boolean issNoticeVibrateOpen = ConfigUtil.getInstance(this).get(Key.NOTICE_VIBRATE_OPEN, true); if (issNoticeVoiceOpen && issNoticeVibrateOpen) { sendNotificationVoice(); sendNotificationVibrate(); }else if(issNoticeVoiceOpen){ sendNotificationVoice(); }else if (issNoticeVibrateOpen){ sendNotificationVibrate(); } } private void sendNotificationVoice(){ Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(this.getApplicationContext(), notification); r.play(); } private void sendNotificationVibrate(){ Vibrator vibrator; vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(260); } public void setNotifyEnable(boolean value){ if (value){ mPushAgent.enable(new IUmengCallback() { @Override public void onSuccess() { } @Override public void onFailure(String s, String s1) { } }); }else{ mPushAgent.disable(new IUmengCallback() { @Override public void onSuccess() { } @Override public void onFailure(String s, String s1) { } }); } } private boolean isAppForceground(Context ctx){ boolean ret = false; ActivityManager am = (ActivityManager) ctx.getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> runnings = am.getRunningAppProcesses(); for(ActivityManager.RunningAppProcessInfo running : runnings){ if(running.processName.equals(ctx.getPackageName())){ if(running.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND || running.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE){ //前台显示... 8 ret = true; }else{ //后台显示...10 ret = false; } break; } } return ret ; } }
package com.example.ttc.fkphotogallery; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by ttc on 2017/3/9. */ public class PhotoGalleryFragment extends Fragment{ private RecyclerView mPhotoRecyclerView; private static final String TAG="TweetFetchFragment"; private List<Tweet> mItems = new ArrayList<>(); private ThumbnailDownloader<PhotoHolder> mPhotoHolderThumbnailDownloader; public static PhotoGalleryFragment newInstance() { return new PhotoGalleryFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true);//need to learn more new FetchItemsTask().execute(); Handler responseHandler=new Handler(); mPhotoHolderThumbnailDownloader=new ThumbnailDownloader<>(responseHandler); mPhotoHolderThumbnailDownloader.setThumbnailDownloadListener( new ThumbnailDownloader.ThumbnailDownloadListener<PhotoHolder>() { @Override public void onThumbnailDownloaded(PhotoHolder photoHolder, Bitmap thumbnail) { Drawable drawable=new BitmapDrawable(getResources(),thumbnail); photoHolder.bindDrawable(drawable); } } ); mPhotoHolderThumbnailDownloader.start(); mPhotoHolderThumbnailDownloader.getLooper(); Log.i(TAG,"Background thread started"); } /** * @param inflater * @param container * @param savedInstanceState * 实例View ,实例RecyclerView,使用layoutManager,设置类型,访问网站,获取数据,设置adapter */ @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v=inflater.inflate(R.layout.fragment_photo_gallery,container,false); mPhotoRecyclerView=(RecyclerView) v.findViewById(R.id.fragment_photo_gallery_recycler_view); mPhotoRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); // new FetchItemsTask().execute(); setupAdapter(); return v; } @Override public void onDestroyView() { super.onDestroyView(); mPhotoHolderThumbnailDownloader.clearQueue(); } @Override public void onDestroy() { super.onDestroy(); mPhotoHolderThumbnailDownloader.quit(); Log.i(TAG,"Backeground thread destroyed"); } //it is Void ,not void /** * doInBackground启用后台线程来获取数据,当后台完成任务后用onPostExecute更新UI */ private class FetchItemsTask extends AsyncTask<Void,Void,List<Tweet>> { @Override protected List<Tweet> doInBackground(Void... voids) { // return new TweetFetch().fetchItems("test"); } /** *当后台完成任务后用onPostExecute更新UI */ @Override protected void onPostExecute(List<Tweet> items) { mItems = items; setupAdapter(); } } //set view private class PhotoHolder extends RecyclerView.ViewHolder { //VH 里放 View组件 private ImageView mTweetPortraitImageView; private TextView mAuthorTextView; private TextView mTweetBodyTextView; public PhotoHolder(View itemView) { super(itemView); mTweetPortraitImageView = (ImageView) itemView .findViewById(R.id.tweet_portrait_image_view); mAuthorTextView= (TextView) itemView.findViewById(R.id.tweet_author_text_view); mTweetBodyTextView= (TextView) itemView.findViewById(R.id.tweet_body_text_view); } public void bindDrawable(Drawable drawable) { // mTweetPortraitImageView.setImageDrawable(drawable); } public void bindTweetOthers(Tweet tweet){ mAuthorTextView.setText(tweet.getAuthor().toString()); mTweetBodyTextView.setText(tweet.getTweetBody().toString()); } } private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder> { //Adapter里放模型 private List<Tweet> mTweets; public PhotoAdapter(List<Tweet> tweets) { mTweets = tweets; } /** * @param viewGroup * @param viewType * 这个函数是搞啥嘞???????????? */ @Override public PhotoHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.gallery_item, viewGroup, false); return new PhotoHolder(view); } @Override public void onBindViewHolder(PhotoHolder photoHolder, int position) { Tweet tweet = mTweets.get(position); // Drawable placeholder = getResources().getDrawable(R.drawable.bill_up_close); // photoHolder.bindDrawable(tweet.getPortraitUrl().); mPhotoHolderThumbnailDownloader.queueThumbanail(photoHolder, tweet.getPortraitUrl()); photoHolder.bindTweetOthers(tweet); } @Override public int getItemCount() { return mTweets.size(); } } //关联adapter private void setupAdapter() { if (isAdded()) { // 判断该Fragment是否已经与Activity关联 mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems)); } } }
package ch11.exam08; import java.util.Date; public class Board { private int bno; private String tilte; private String content; private String writer; private Date writeDate; public int getBno() { return bno; } public void setBno(int bno) { this.bno = bno; } public String getTilte() { return tilte; } public void setTilte(String tilte) { this.tilte = tilte; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public Date getWriteDate() { return writeDate; } public void setWriteDate(Date writeDate) { this.writeDate = writeDate; } }
package com.lenovohit.hwe.mobile.core.web.rest; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hwe.mobile.core.model.Classification; import com.lenovohit.hwe.mobile.core.model.Laboratory; /** * 工具---化验单解读 * @author redstar * */ @RestController @RequestMapping("hwe/app/laboratory") public class LaboratoryRestController extends MobileBaseRestController { @Autowired private GenericManager<Laboratory, String> laboratoryManager; @Autowired private GenericManager<Classification, String> classificationManager; //查找化验单父分类 @RequestMapping(value = "/listFirstLevelTest", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listFirstLevelTest(@RequestParam(value = "data", defaultValue = "") String data) { String jql="from Classification where classType = 3 and parentNode = ' ' "; List<Classification> dicts=classificationManager.find(jql); return ResultUtils.renderSuccessResult(dicts); } //查找化验单子分类 @RequestMapping(value = "/listSecondLevelTest", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listCommonDisease(@RequestParam(value = "data", defaultValue = "") String data) { Classification model = JSONUtils.deserialize(data, Classification.class); List<Object> values=new ArrayList<Object>(); values.add(model.getParentNode()); String jql="from Classification where classType = 3 and parentNode = ? "; List<Classification> dicts=classificationManager.find(jql,values.toArray()); return ResultUtils.renderSuccessResult(dicts); } //根据关键字搜索化验 @RequestMapping(value = "/listByKeyWords", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listByKeyWords(@RequestParam(value = "data", defaultValue = "") String data) { Laboratory model = JSONUtils.deserialize(data, Laboratory.class); List<Object> values=new ArrayList<Object>(); String jql="from Laboratory where laboratoryName like ? "; values.add("%" + model.getLaboratoryName() + "%"); List<Laboratory> laboratory=(List<Laboratory>) laboratoryManager.findByJql(jql, values.toArray()); return ResultUtils.renderSuccessResult(laboratory); } //根据化验单类型搜索化验单明细 @RequestMapping(value = "/listLaboratoryByType", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listEmergencyByType(@RequestParam(value = "data", defaultValue = "") String data) { Classification model = JSONUtils.deserialize(data, Classification.class); String jql="from Laboratory where classificationId = ? "; List<Object> values=new ArrayList<Object>(); values.add(model.getParentNode().trim()); //c=emergencyManager.findByProp("classificationId", model.getClassificationId()); List<Laboratory> laboratory=(List<Laboratory>) laboratoryManager.findByJql(jql, values.toArray()); return ResultUtils.renderSuccessResult(laboratory); } }
package co.uk.apcoa.pages; public class AccessResponse { String access_token; }
package edu.banking.hollingsworth.james; import edu.jenks.dist.banking.AbstractBanking; import edu.jenks.dist.banking.AbstractCheckingAccount; import edu.jenks.dist.banking.AbstractCustomer; import edu.jenks.dist.banking.AbstractSavingsAccount; public class Banking extends AbstractBanking { @Override public void addCustomer(String name, AbstractCheckingAccount checkingAccount, AbstractSavingsAccount savingsAccount) { this.getCustomers().add(new Customer(name, checkingAccount, savingsAccount)); } @Override public void performMaintenance(int days) { for(AbstractCustomer c : this.getCustomers()) { AbstractCheckingAccount checking = c.getCheckingAccount(); AbstractSavingsAccount savings = c.getSavingsAccount(); if(checking != null) { if(savings != null && checking.getBalance() < 0) savings.transfer(checking, (checking.getBalance())); checking.setBalance(checking.getBalance() - checking.getNumberOverdrafts() * checking.getOverdraftFee()); if(savings != null && checking.getBalance() + savings.getBalance() < this.getMinNoFeeCombinedBalance()) checking.setBalance(checking.getBalance() - this.getBankingFee()); checking.payInterest(days); checking.setNumberOverdrafts(0); } if(savings != null) { savings.payInterest(days); savings.setNumTransactions(0); } } } @Override public boolean removeCustomer(String name) { boolean contains = false; for(AbstractCustomer c : this.getCustomers()) { if(c.getName().equals(name)) { contains = true; this.getCustomers().remove(c); break; } } return contains; } }
package com.github.venkat.writables.example; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.VersionedProtocol; import java.io.IOException; public class HadoopServer { public static final String SERVER_ADDRESS = "localhost"; public static final int SERVER_PORT = 20000; public static void main(String[] args) throws IOException { final RPC.Server server= RPC.getServer(new HadoopService(),SERVER_ADDRESS,SERVER_PORT,new Configuration()); server.start(); } }
package com.shop.mapper; import com.shop.model.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface UserMapper { /** * 登录校验查询user * @return */ @Select("select * from user where userName=#{userName} and userPassword=#{userPassword}") public User loginselect(User user); @Select("select * from user where userId = #{userId}") User getById(Long userId); @Update("update user set userPassword = #{newPwd} where userId = #{userId}") Integer changePwd(@Param(value = "userId") Long userId,@Param("newPwd") String newPwd); }
package com.example.mdt; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class Camera extends AppCompatActivity { ImageView iv24, iv25; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); iv24 = (ImageView)findViewById(R.id.iv24); iv24.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i23 = new Intent(Camera.this, Backcamera.class); startActivity(i23); } }); } }
import presentation.Menu; import java.io.FileNotFoundException; import java.text.ParseException; public class Main { public static void main(String[] args) throws FileNotFoundException, ParseException { Menu mainMenu = new Menu(); mainMenu.mainLoop(); } }
package gov.nist.hit.core.service; import java.util.List; import java.util.Set; import gov.nist.hit.core.domain.TestArtifact; import gov.nist.hit.core.domain.TestPlan; import gov.nist.hit.core.domain.TestScope; import gov.nist.hit.core.domain.TestingStage; public interface TestPlanService { public TestPlan findOne(Long testPlanId); public List<TestArtifact> findAllTestPackages(TestingStage stage); public List<TestPlan> findShortAllByStage(TestingStage stage); public List<TestPlan> findShortAllByStageAndScope(TestingStage stage, TestScope scope); public List<TestPlan> findShortAllByStageAndAuthor(TestingStage stage, String authorUsername); public List<TestPlan> findShortAllByStageAndScopeAndAuthor(TestingStage stage, TestScope scope, String authorUsername); public Set<String> findAllCategoriesByStageAndScope(TestingStage stage, TestScope scope); public Set<String> findAllCategoriesByStageAndScopeAndUser(TestingStage stage, TestScope scope, String username); void delete(TestPlan testPlan); public TestPlan save(TestPlan testPlan); public List<TestPlan> findAllShortByStageAndUsernameAndScope(TestingStage stage, String authorUsername, TestScope scope); }
/** http://lightoj.com/volume_showproblem.php?problem=1041 #prim */ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Scanner; class RoadConstruction { public static boolean Prim(ArrayList<ArrayList<Node>> graph, int[] costArr, int src) { int sz = graph.size(); boolean[] visitedArr = new boolean[sz]; Arrays.fill(visitedArr, false); costArr[src] = 0; PriorityQueue<Node> pq = new PriorityQueue<>(); pq.add(new Node(src, 0)); int id, w; Node node; while (!pq.isEmpty()) { node = pq.poll(); id = node.id; visitedArr[id] = true; for (Node neighbour : graph.get(id)) { w = neighbour.cost; if (!visitedArr[neighbour.id] && w < costArr[neighbour.id]) { costArr[neighbour.id] = w; pq.add(new Node(neighbour.id, w)); } } } for (boolean flg : visitedArr) { if (!flg) return false; } return true; } public static int getCostRepair(int[] costArr) { int ans = 0; for (int cost : costArr) { ans += cost; } return ans; } public static int getIdxInput( String str, HashMap<String, Integer> hashMap, ArrayList<String> stringArr, ArrayList<ArrayList<Node>> graph) { if (!hashMap.containsKey(str)) { stringArr.add(str); int id = stringArr.size() - 1; hashMap.put(str, id); graph.add(new ArrayList<>()); } return hashMap.get(str); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testcases = sc.nextInt(); for (int t = 1; t <= testcases; t++) { int m = sc.nextInt(); HashMap<String, Integer> hashMap = new HashMap<>(); ArrayList<String> stringArr = new ArrayList<>(); ArrayList<ArrayList<Node>> graph = new ArrayList<>(); String str1, str2; int cost, id1, id2; for (int i = 0; i < m; i++) { str1 = sc.next(); str2 = sc.next(); cost = sc.nextInt(); id1 = getIdxInput(str1, hashMap, stringArr, graph); id2 = getIdxInput(str2, hashMap, stringArr, graph); graph.get(id1).add(new Node(id2, cost)); graph.get(id2).add(new Node(id1, cost)); } int sz = graph.size(); int[] costArr = new int[sz]; Arrays.fill(costArr, Integer.MAX_VALUE); if (Prim(graph, costArr, 0)) { System.out.println("Case " + t + ": " + getCostRepair(costArr)); } else { System.out.println("Case " + t + ": Impossible"); } } } } class Node implements Comparable<Node> { int id, cost; public Node(int id, int cost) { this.id = id; this.cost = cost; } public int compareTo(Node other) { return this.cost - other.cost; } }
package com.distributie.enums; public enum EnumOperatiiEvenimente { SAVE_NEW_EVENT("saveNewEvent"), GET_DOC_EVENTS("getDocEvents"), CHECK_BORD_STARTED("getStartBorderou"), SAVE_NEW_STOP("saveStop"), CHECK_STOP( "getEvenimentStop"), SAVE_ARCHIVED_OBJECTS("saveArchivedObjects"), SET_SFARSIT_INC("saveEvenimentStopIncarcare"), GET_SFARSIT_INC( "getEvenimentStopIncarcare"), CANCEL_EVENT("cancelEvent"), GET_POZITIE("getPozitieCurenta"); private String numeComanda; EnumOperatiiEvenimente(String numeComanda) { this.numeComanda = numeComanda; } public String getNumeComanda() { return numeComanda; } public String toString() { return numeComanda; } }
package cc.yuerblog; import cc.yuerblog.dag.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import java.io.IOException; // https://spark.apache.org/docs/latest/rdd-programming-guide.html // yarn线上提交:spark-submit --master yarn --deploy-mode cluster --executor-memory 1G --num-executors 10 ./spark-demo-1.0-SNAPSHOT.jar // yarn线下调试:将driver(AM)跑在本地,可以看到action的结果,命令:spark-submit --master yarn --deploy-mode client --executor-memory 1G --num-executors 10 ./spark-demo-1.0-SNAPSHOT.jar public class Main { public static void main(String []args) { try { FileSystem dfs = FileSystem.get(new Configuration()); // hdfs连接 SparkConf conf = new SparkConf().setAppName("spark-demo"); // 配置 JavaSparkContext sc = new JavaSparkContext(conf); // Spark连接 // JAVA数组转RDD Collection2Text collection2Text = new Collection2Text(); collection2Text.run(dfs, sc); // HDFS Text文件转RDD,RDD转sequenceFile文件 Text2Seq text2Seq = new Text2Seq(); text2Seq.run(dfs, sc); // Hdfs SequenceFile转RDD,简单RDD计算 Seq2RDD seq2RDD = new Seq2RDD(); seq2RDD.run(dfs, sc); // RDD transformers示例 RDDTrans rddTrans = new RDDTrans(); rddTrans.run(dfs, sc); // 广播与计数器 BrodAndAccu brodAndAccu = new BrodAndAccu(); brodAndAccu.run(dfs, sc); } catch (IOException e) { e.printStackTrace(); } } }
package proxy4; public class Student { public void study(){ System.out.println("我是学生,我正在教室里上课..."); } public void doHomework(){ System.out.println("我是学生,我每天晚上都回家之后都有写不完的作业..."); } }
package com.baoxu.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.baoxu.model.User; @Controller @RequestMapping("/user") public class UserListController { @RequestMapping("/userList.do") public ModelAndView userList(HttpServletRequest request, HttpServletResponse response) throws Exception { List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("张三"); user1.setAge(18); user1.setSex(1); User user2 = new User(); user2.setUserName("李四"); user2.setAge(19); user2.setSex(2); userList.add(user1); userList.add(user2); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("userList", userList); modelAndView.setViewName("userList"); return modelAndView; } }
package ticket.modernland.co.id; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; public class AssigmentAdapter extends RecyclerView.Adapter<AssigmentViewHolder> { public ArrayList<Assigment> data; @NonNull @Override public AssigmentViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View x = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.card_assigment, viewGroup, false); AssigmentViewHolder r = new AssigmentViewHolder(x); return r; } @Override public void onBindViewHolder(@NonNull AssigmentViewHolder assigmentViewHolder, int i) { Assigment r = data.get(i); assigmentViewHolder.et_reported.setText(r.reported); assigmentViewHolder.et_prosummary.setText(r.problem_summary); assigmentViewHolder.et_iduser.setText(r.id_user); assigmentViewHolder.et_idticket.setText(r.id_ticket+ ""); } @Override public int getItemCount() { return data.size(); } }
package nl.esciencecenter.newsreader.hbase; import cascading.flow.FlowProcess; import cascading.operation.BaseOperation; import cascading.operation.Function; import cascading.operation.FunctionCall; import cascading.tuple.Fields; import cascading.tuple.Tuple; import cascading.tuple.TupleEntry; public class SizerFunction extends BaseOperation implements Function { public SizerFunction(Fields fieldDeclaration ) { super(2, fieldDeclaration); } @Override public void operate(FlowProcess flowProcess, FunctionCall functionCall) { TupleEntry argument = functionCall.getArguments(); String docName = argument.getString(0); String docContent = argument.getString(1); if (docContent == null) { docContent = ""; } Tuple result = new Tuple(); result.add(docName); result.add(docContent.length()); functionCall.getOutputCollector().add(result); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.aot; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.RegisteredBean; import org.springframework.lang.Nullable; /** * AOT processor that makes bean registration contributions by processing * {@link RegisteredBean} instances. * * <p>{@code BeanRegistrationAotProcessor} implementations may be registered in * a {@value AotServices#FACTORIES_RESOURCE_LOCATION} resource or as a bean. * * <p>Using this interface on a registered bean will cause the bean <em>and</em> * all of its dependencies to be initialized during AOT processing. We generally * recommend that this interface is only used with infrastructure beans such as * {@link BeanPostProcessor} which have limited dependencies and are already * initialized early in the bean factory lifecycle. If such a bean is registered * using a factory method, make sure to make it {@code static} so that its * enclosing class does not have to be initialized. * * <p>An AOT processor replaces its usual runtime behavior by an optimized * arrangement, usually in generated code. For that reason, a component that * implements this interface is not contributed by default. If a component that * implements this interface still needs to be invoked at runtime, * {@link #isBeanExcludedFromAotProcessing} can be overridden. * * @author Phillip Webb * @author Stephane Nicoll * @since 6.0 * @see BeanRegistrationAotContribution */ @FunctionalInterface public interface BeanRegistrationAotProcessor { /** * Process the given {@link RegisteredBean} instance ahead-of-time and * return a contribution or {@code null}. * <p> * Processors are free to use any techniques they like to analyze the given * instance. Most typically use reflection to find fields or methods to use * in the contribution. Contributions typically generate source code or * resource files that can be used when the AOT optimized application runs. * <p> * If the given instance isn't relevant to the processor, it should return a * {@code null} contribution. * @param registeredBean the registered bean to process * @return a {@link BeanRegistrationAotContribution} or {@code null} */ @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean); /** * Return if the bean instance associated with this processor should be * excluded from AOT processing itself. By default, this method returns * {@code true} to automatically exclude the bean, if the definition should * be written then this method may be overridden to return {@code true}. * @return if the bean should be excluded from AOT processing * @see BeanRegistrationExcludeFilter */ default boolean isBeanExcludedFromAotProcessing() { return true; } }
import java.util.Scanner; public class sum { public static void main(String[] args) { Scanner sr = new Scanner(System.in); int n = sr.nextInt(); int x = sr.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++) { a[i] = sr.nextInt(); } int temp=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { for(int k=j+1;k<n;k++) { if( a[i] + a[j] + a[k] < x) temp++; } } } if(temp==0) System.out.println("no such triplet present"); else System.out.println(temp); } }
package com.wizinno.shuhao.user.userServiceImpl; import com.wizinno.shuhao.condition.LogCondition; import com.wizinno.shuhao.condition.UserCondition; import com.wizinno.shuhao.device.data.DeviceDto; import com.wizinno.shuhao.exception.CustomException; import com.wizinno.shuhao.exception.CustomExceptionCode; import com.wizinno.shuhao.user.data.*; import com.wizinno.shuhao.user.domain.*; import com.wizinno.shuhao.user.domain.model.*; import com.wizinno.shuhao.user.util.DtoTranUser; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import com.wizinno.shuhao.userService.UserService; import java.awt.event.FocusEvent; import java.util.ArrayList; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private UserFriendsMapper userFriendsMapper; @Autowired private AppVerMapper appVerMapper; @Autowired private AuthoCodeMapper authoCodeMapper; @Autowired private LogMapper logMapper; @Override public int updateUser(UserDto userDto) { User user=new User(); BeanUtils.copyProperties(userDto,user); int a= userMapper.updateByPrimaryKey(user); return a; } @Override public void insert(UserDto userDto) { User user1= userMapper.selectByPhone(userDto.getPhone()); if(user1!=null){ throw new CustomException(CustomExceptionCode.PhoneIsRegister); } User user=new User(); BeanUtils.copyProperties(userDto,user); userMapper.insert(user); } @Override public UserDto findByPhone(String phone) { User user=userMapper.selectByPhone(phone); UserDto userDto=new UserDto(); if(user==null){ throw new CustomException(CustomExceptionCode.UserNoExit); } BeanUtils.copyProperties(user,userDto); return userDto; } @Override public UserDto findById(Long userId) { User user= userMapper.selectByPrimaryKey(userId); UserDto userDto=new UserDto(); if(user==null){ throw new CustomException(CustomExceptionCode.UserNoExit); } BeanUtils.copyProperties(user,userDto); return userDto; } @Override public void insertFriend(UserFriendsDto userFriendsDto) { UserFriends userFriends=new UserFriends(); BeanUtils.copyProperties(userFriendsDto,userFriends); userFriendsMapper.insert(userFriends); } @Override public List<UserDto> getFriends(Long userId) { UserDto userDto; List<UserDto>list=new ArrayList<>(); List<User>users=userMapper.getFriends(userId); list= DtoTranUser.dtoTranUser(users); return list; } @Override public void deleteFriend(Long userId, Long friendId) { userFriendsMapper.deleteByPrimaryKey(userId,friendId); } @Override public AppVerDto newAppVer(Integer platform) { AppVer appVer=new AppVer(); AppVerDto appVerDto=new AppVerDto(); List<AppVer> appVers= appVerMapper.getNewApp(platform); if(appVers!=null&&appVers.size()>0){ appVer=appVers.get(0); BeanUtils.copyProperties(appVer,appVerDto); }else{ throw new CustomException(CustomExceptionCode.NoAppVer); } return appVerDto; } @Override public void saveApp(AppVerDto appVerDto) { if(appVerDto==null){ throw new CustomException(CustomExceptionCode.NoAppVer); } AppVer appVer=new AppVer(); BeanUtils.copyProperties(appVerDto,appVer); appVerMapper.insert(appVer); } @Override public AuthoCodeDto selectByPhone(String phone) { AuthoCodeDto authoCodeDto=new AuthoCodeDto(); AuthoCode authoCode= authoCodeMapper.selectByPhone(phone); if(authoCode!=null){ BeanUtils.copyProperties(authoCode,authoCodeDto); } return authoCodeDto; } @Override public void saveAuthoCode(AuthoCodeDto authoCodeDto) { AuthoCode authoCode=new AuthoCode(); BeanUtils.copyProperties(authoCodeDto,authoCode); authoCodeMapper.insert(authoCode); } @Override public void updateByPhone(AuthoCodeDto authoCodeDto) { AuthoCode authoCode=new AuthoCode(); BeanUtils.copyProperties(authoCodeDto,authoCode); authoCodeMapper.updateByPhone(authoCode); } @Override public List<UserDto> getUsers(UserCondition con) { List<User> users = userMapper.getUsers(con); List<UserDto> lists = new ArrayList(); UserDto userDto; for (User user:users){ userDto = new UserDto(); BeanUtils.copyProperties(user,userDto); lists.add(userDto); } return lists; } @Override public Long getUsersTotal(UserCondition con) { return userMapper.getUsersTotal(con); } @Override public List<DeviceDto> getDevicesByUserId(UserCondition con) { List<DeviceDto> dtos = userMapper.getDevicesByUserId(con); for (DeviceDto dto:dtos){ if (dto.getIsOnline() == 0){ dto.setIsOnlineDesc("离线"); }else { dto.setIsOnlineDesc("在线"); } } return dtos; } @Override public Long getDevicesByUserIdTotal(UserCondition con) { return userMapper.getDevicesByUserIdTotal(con); } @Override public List<UserDto> getFriendsByUserId(UserCondition con) { List<User> users=userMapper.getFriendsByUserId(con); List<UserDto> userDtos = DtoTranUser.dtoTranUser(users); for (UserDto dto:userDtos){ List<Long> userShares=userMapper.getUserShares(con.getUserId(),dto.getUserId()); if (userShares.size() > 0){ dto.setUserShares(userShares); } List<Long> friendShares=userMapper.getFriendShares(dto.getUserId(),con.getUserId()); if (friendShares.size() > 0){ dto.setFriendShares(friendShares); } } return userDtos; } @Override public Long getFriendsByUserIdTotal(UserCondition con) { return userMapper.getFriendsByUserIdTotal(con); } @Override public List<DeviceDto> getFriendDevicesShares(UserCondition con) { List<DeviceDto> dtos= userMapper.getFriendDevicesShares(con); for(DeviceDto dto:dtos){ if (dto.getIsOnline() != null){ if (dto.getIsOnline() == 0){ dto.setIsOnlineDesc("离线"); }else { dto.setIsOnlineDesc("在线"); } } } return dtos; } @Override public Long getFriendDevicesSharesTotal(UserCondition con) { return userMapper.getFriendDevicesSharesTotal(con); } @Override public List<AppVerDto> getAppVers() { List<AppVer> appVers = appVerMapper.getAppVers(); List<AppVerDto> lists = new ArrayList(); AppVerDto appVerDto =null; for (AppVer appVer:appVers){ appVerDto = new AppVerDto(); BeanUtils.copyProperties(appVer,appVerDto); lists.add(appVerDto); } return lists; } @Override public void saveLog(LogDto logDto) { Log log=new Log(); BeanUtils.copyProperties(logDto,log); logMapper.insert(log); } @Override public List<LogDto> queryByCondition(LogCondition logCondition) { List<Log> logs=logMapper.queryByCondition(logCondition); List<LogDto>logDtos=new ArrayList<>(); LogDto logDto; if(logs.size()>0){ for(Log log:logs){ logDto=new LogDto(); BeanUtils.copyProperties(log,logDto); logDtos.add(logDto); } } return logDtos; } @Override public List<LogDto> queryAllLogs(LogCondition logCondition) { List<Log>logs= logMapper.selectAll(logCondition); List<LogDto>logDtos=new ArrayList<>(); LogDto logDto; if(logs.size()>0){ for(Log log:logs){ logDto=new LogDto(); BeanUtils.copyProperties(log,logDto); logDtos.add(logDto); } } return logDtos; } @Override public AppVerDto updateAppVers(AppVerDto dto) { AppVer appVer = new AppVer(); BeanUtils.copyProperties(dto,appVer); appVerMapper.updateByPrimaryKey(appVer); AppVer appVer1 = appVerMapper.selectByPrimaryKey(dto.getId()); AppVerDto appVerDto = new AppVerDto(); BeanUtils.copyProperties(appVer1,appVerDto); return appVerDto; } @Override public void saveAppVers(AppVerDto dto) { AppVer appVer = new AppVer(); BeanUtils.copyProperties(dto,appVer); appVerMapper.insert(appVer); } }
package com.example.medsearch; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import java.util.Objects; public class adminLog extends AppCompatActivity { private EditText et1, et2; private Button login; private TextView reg; private FirebaseAuth fbAuth; private String ID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_log); et1 = findViewById(R.id.editText1); et2 = findViewById(R.id.editText2); login = findViewById(R.id.button1); reg = findViewById(R.id.textView6); fbAuth = FirebaseAuth.getInstance(); /*if(fbAuth.getCurrentUser() !=null){ startActivity(new Intent(getApplicationContext(),adminData.class)); finish(); }*/ login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = et1.getText().toString(); String pwd = et2.getText().toString(); fbAuth.signInWithEmailAndPassword(email, pwd) .addOnCompleteListener(adminLog.this, new OnCompleteListener<AuthResult>() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { ID = Objects.requireNonNull(fbAuth.getCurrentUser()).getUid(); Intent it = new Intent(adminLog.this, adminData.class); it.putExtra("adminid", ID); startActivity(it); } else { Toast.makeText(adminLog.this, "login failed", Toast.LENGTH_LONG).show(); } } }); } }); reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(adminLog.this, adminRegis.class); startActivity(it); } }); } }
/* * 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 PA165.language_school_manager.mvc.controllers; import PA165.language_school_manager.DTO.PersonAuthenticateDTO; import PA165.language_school_manager.DTO.PersonDTO; import PA165.language_school_manager.Facade.PersonFacade; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.hibernate.validator.internal.metadata.raw.ExecutableElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.util.UriComponentsBuilder; /** * * @author Matúš */ @Controller @RequestMapping("/auth") public class AuthenticationController { private final static Logger log = LoggerFactory.getLogger(AuthenticationController.class); @Autowired private PersonFacade personFacade; @RequestMapping(value = "", method = RequestMethod.GET) public String loginUser(Model model, HttpServletRequest request) { if (request.getSession().getAttribute("person") != null) { return "redirect:" + request.getHeader("Referer"); } log.debug("[AUTH] login"); model.addAttribute("personLogin", new PersonAuthenticateDTO()); return "/auth/login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(@Valid @ModelAttribute("personLogin") PersonAuthenticateDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder, HttpServletRequest request) { if (bindingResult.hasErrors()) { for (ObjectError ge : bindingResult.getGlobalErrors()) { log.debug("ObjectError: {}", ge); } for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); log.debug("FieldError: {}", fe); } model.addAttribute("personLogin", new PersonAuthenticateDTO()); return "/auth/login"; } PersonDTO matchingP = personFacade.findPersonByUserName(formBean.getUserName()); if (matchingP == null) { log.warn("no person with userName {}", formBean.getUserName()); redirectAttributes.addFlashAttribute("alert_warning", "No person with userName: " + formBean.getUserName()); return "redirect:" + uriBuilder.path("/auth").build().toUriString(); } if (!personFacade.authenticate(formBean)) { log.warn("wrong credentials: person={} password={}", formBean.getUserName(), formBean.getPassword()); redirectAttributes.addFlashAttribute("alert_warning", "Login " + formBean.getUserName() + " failed "); return "redirect:" + uriBuilder.path("/auth").build().toUriString(); } if (!personFacade.isAdmin(matchingP)) { request.getSession().setAttribute("person", matchingP); redirectAttributes.addFlashAttribute("alert_success", "Log " + formBean.getUserName() + " successful"); return "home"; } else { request.getSession().setAttribute("admin", matchingP); redirectAttributes.addFlashAttribute("alert_success", "Log " + formBean.getUserName() + " successful"); return "home"; } } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logoutUser(Model model, HttpServletRequest request) { log.debug("[AUTH] Logout"); if (request.getSession().getAttribute("person") == null) { if (request.getSession().getAttribute("admin") == null) { return "home"; } else { request.getSession().removeAttribute("admin"); } } request.getSession().removeAttribute("person"); return "home"; } }
package com.xianzaishi.wms.tmscore.vo; import com.xianzaishi.wms.tmscore.vo.WavePoolDetailVO; public class WavePoolDetailDO extends WavePoolDetailVO { }
package net.tanpeng.database.jdbc; import java.sql.*; public class JDBCDemo { public static void main(String[] args) { try { Connection connection = getConnection(); Statement statement = connection.createStatement(); // 查询city表中所有的数据 try (ResultSet resultSet = statement.executeQuery("select * from gzs_shop_a")) { while (resultSet.next()) { // 依次打印出查询结果中Name的字符串 System.out.println(resultSet.getString("id")); } } connection.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } private static Connection getConnection() throws ClassNotFoundException, SQLException { String serverName = ""; String database = ""; String url = "jdbc:mysql://" + serverName + "/" + database; // 数据配置用户和密码 String user = ""; String password = ""; return DriverManager.getConnection(url, user, password); } }
package hu.lamsoft.hms.androidclient.restapi.nutritionist.async; import org.springframework.core.ParameterizedTypeReference; import hu.lamsoft.hms.androidclient.restapi.common.async.AsyncCallback; import hu.lamsoft.hms.androidclient.restapi.common.async.DTOPagerAsyncTask; import hu.lamsoft.hms.androidclient.restapi.common.dto.Page; import hu.lamsoft.hms.androidclient.restapi.food.dto.FoodDTO; import hu.lamsoft.hms.androidclient.restapi.nutritionist.dto.BlogEntryDTO; /** * Created by admin on 2017. 04. 13.. */ public class BlogEntriesAsyncTask extends DTOPagerAsyncTask<BlogEntryDTO> { public BlogEntriesAsyncTask(AsyncCallback<Page<BlogEntryDTO>> callback) { super(callback); } public BlogEntriesAsyncTask(int page, AsyncCallback<Page<BlogEntryDTO>> callback) { super(page, callback); } public BlogEntriesAsyncTask(int page, int size, AsyncCallback<Page<BlogEntryDTO>> callback) { super(page, size, callback); } @Override protected String getPath() { return "/nutritionist/blog-entries"; } @Override protected ParameterizedTypeReference<Page<BlogEntryDTO>> getParameterizedTypeReference() { return new ParameterizedTypeReference<Page<BlogEntryDTO>>(){}; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class bj11724 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); int node = Integer.parseInt(st.nextToken()); int edge = Integer.parseInt(st.nextToken()); ArrayList<ArrayList<Integer>> graph = new ArrayList<>(node + 1); for (int i = 1; i < node + 2; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < edge; i++) { st = new StringTokenizer(br.readLine(), " "); int u = Integer.parseInt(st.nextToken()); int v = Integer.parseInt(st.nextToken()); graph.get(u).add(v); graph.get(v).add(u); } boolean visited[] = new boolean[node + 1]; Queue<Integer> que = new LinkedList<>(); int count = 0; for (int now = 1; now < node + 1; now++) { if (visited[now]) continue; que.add(now); visited[now] = true; while (!que.isEmpty()) { int poll = que.poll(); for (int i = 0; i < graph.get(poll).size(); i++) { int temp = graph.get(poll).get(i); if (!visited[temp]) { que.add(temp); visited[temp] = true; } } } count += 1; } System.out.println(count); } }