text
stringlengths
10
2.72M
public class telusku { public static void main(String[] args) { int i,j,k; i=5; j=7; k=i+j; System.out.println("The value of k is "+k); System.out.println("The addition of "+i+" and "+j+" is "+k); System.out.printf("The addition of %d and %d is %d \n",i,j,k); } }
package com.example.testo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.testo.onAppDestroyed.AppStatesHandling; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import id.zelory.compressor.Compressor; public class ProfileActivity extends AppCompatActivity { private static final String TAG = "ProfileActivity"; EditText name; ImageView image; Button updateProfile; ProgressBar progressBar; ProgressBar progressBarUploadingImage; final int TAKE_IMAGE_CODE=10012; final int PICK_IMAGE_FROM_GALLERY=121; FirebaseUser user; int STORAGE_PERMISSION_CODE=1; int CAMERA_PERMISSION_CODE=2; DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference("users"); AppStatesHandling appStatesHandling; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); appStatesHandling=new AppStatesHandling(); user=FirebaseAuth.getInstance().getCurrentUser(); name=findViewById(R.id.user_name); image=findViewById(R.id.profile_image); updateProfile=findViewById(R.id.updateprofile_btn); progressBar=findViewById(R.id.progressBar_profile); progressBarUploadingImage=findViewById(R.id.progressBarUploadingImage); if(user==null){ startActivity(new Intent(this,MainActivity.class)); finish(); } if(user.getDisplayName()!=null){ name.setText(user.getDisplayName()); name.setSelection(user.getDisplayName().length()); } if(user.getPhotoUrl()!=null){ Glide.with(this) .load(user.getPhotoUrl()) .into(image); }else { image.setImageResource(R.drawable.profile_avatar); } } public void handleImageClick(View view) { AlertDialog.Builder alertDialog=new AlertDialog.Builder(this); alertDialog.setTitle("Choose a method"); String []list=new String[]{"From Gallery","Take a photo","View picture"}; alertDialog.setItems(list, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: if(ContextCompat.checkSelfPermission(ProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ fireStorageRequest(1); Log.d(TAG, "onClick: "+"Asking for Gallery permission"); }else { Intent intent1=new Intent(Intent.ACTION_PICK); intent1.setType("image/*"); startActivityForResult(intent1,PICK_IMAGE_FROM_GALLERY); } break; case 1: if(ContextCompat.checkSelfPermission(ProfileActivity.this,Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){ fireStorageRequest(2); }else { Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(intent.resolveActivity(getPackageManager())!=null){ startActivityForResult(intent,TAKE_IMAGE_CODE); } } break; case 2: } } }); alertDialog.create().show(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==TAKE_IMAGE_CODE){ if(resultCode==RESULT_OK){ Bitmap bitmap= (Bitmap) data.getExtras().get("data"); image.setImageBitmap(bitmap); handleUploadImage(bitmap); } } else if(requestCode==PICK_IMAGE_FROM_GALLERY){ if(resultCode==RESULT_OK){ Uri uri=data.getData(); handleUploadImageGallery(uri); Glide.with(this) .load(uri) .into(image); } } } private void handleUploadImageGallery( Uri uri){ progressBarUploadingImage.setVisibility(View.VISIBLE); String realPath = ImageFilePath.getPath(ProfileActivity.this, uri); File actualImage=new File(realPath); try { Bitmap compressedImage=new Compressor(this) .setMaxHeight(250) .setMaxWidth(250) .setQuality(50) .compressToBitmap(actualImage); ByteArrayOutputStream baos=new ByteArrayOutputStream(); compressedImage.compress(Bitmap.CompressFormat.JPEG,90,baos); byte[] finalImage=baos.toByteArray(); String uid=FirebaseAuth.getInstance().getCurrentUser().getUid(); final StorageReference reference=FirebaseStorage.getInstance().getReference() .child("profileImages") .child(uid+".jpeg"); UploadTask uploadTask=reference.putBytes(finalImage); uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { getDownloadURL(reference); } }); } catch (IOException e) { Toast.makeText(this, "Error uploading", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } private void handleUploadImage(Bitmap bitmap){ progressBarUploadingImage.setVisibility(View.VISIBLE); ByteArrayOutputStream baos=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos); String uid=FirebaseAuth.getInstance().getCurrentUser().getUid(); final StorageReference reference=FirebaseStorage.getInstance().getReference() .child("profileImages") .child(uid+".jpeg"); reference.putBytes(baos.toByteArray()).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { progressBarUploadingImage.setVisibility(View.GONE); getDownloadURL(reference); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(),"Failed to upload image",Toast.LENGTH_LONG).show(); } }); } private void getDownloadURL(StorageReference reference){ reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { setUserImage(uri); } }); } private void setUserImage(final Uri uri){ UserProfileChangeRequest request=new UserProfileChangeRequest.Builder() .setPhotoUri(uri) .build(); user.updateProfile(request).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(ProfileActivity.this, "Image successfully updated", Toast.LENGTH_SHORT).show(); progressBarUploadingImage.setVisibility(View.GONE); databaseReference .child(user.getUid()) .child("information") .child("uriPath").setValue(uri.toString()); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(ProfileActivity.this, "Image failed to update", Toast.LENGTH_SHORT).show(); progressBarUploadingImage.setVisibility(View.GONE); } }); } public void handleUpdateProfile(View view) { progressBar.setVisibility(View.VISIBLE); updateProfile.setEnabled(false); UserProfileChangeRequest request=new UserProfileChangeRequest.Builder() .setDisplayName(name.getText().toString()) .build(); user.updateProfile(request).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(ProfileActivity.this,"Successfully updated",Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.INVISIBLE); updateProfile.setEnabled(true); databaseReference .child(user.getUid()) .child("information") .child("name").setValue(user.getDisplayName()); databaseReference.child(user.getUid()) .child("search").setValue(user.getDisplayName().toLowerCase()); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(ProfileActivity.this,"Failed to update",Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.INVISIBLE); updateProfile.setEnabled(true); } }); } private void fireStorageRequest(int i){ if(i==1) ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE); else if(i==2){ ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},CAMERA_PERMISSION_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(requestCode==STORAGE_PERMISSION_CODE){ if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){ Intent intent1=new Intent(Intent.ACTION_PICK); intent1.setType("image/*"); startActivityForResult(intent1,PICK_IMAGE_FROM_GALLERY); } }else if(requestCode==CAMERA_PERMISSION_CODE){ if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){ Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(intent.resolveActivity(getPackageManager())!=null){ startActivityForResult(intent,TAKE_IMAGE_CODE); } } } } @Override protected void onPause() { super.onPause(); appStatesHandling.incrementPaused(); } @Override protected void onStart() { super.onStart(); appStatesHandling.incrementStarted(); } @Override protected void onStop() { super.onStop(); appStatesHandling.incrementStopped(); } @Override protected void onResume() { super.onResume(); appStatesHandling.incrementResumed(); } }
package com.example.administrator.halachavtech.Motzar; import android.graphics.Bitmap; import java.io.Serializable; /** * This class represents motzar that we get from the server * It implements {@link Serializable} interface in order to be able * to pass through activities * Note that private transient Bitmap bitmap is used to hold * a reference to the Bitmap image of the motzar and it transient * * @author Admin */ public class Motzar implements Serializable{ /* Id of motzar from the DB*/ private int id_motzar; /* Name of the motzar*/ private String name_motzar; /* Price per one*/ private Double price_motzar; /* Description*/ private String description; /* Instruction*/ private String instruction; /* URL path to the photo */ private String url_photo; /* URL path to the youtube */ private String url_youtube; /* How much we have in stock after 'tashlum ushar': stock_after_payment = (stock - all_where_tashlum_ushar)*/ private int stock_after_payment; /* private transient Bitmap bitmap is used to hold * a reference to the Bitmap image of the motzar and it transient*/ private transient Bitmap bitmap; // getters / setters public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public int getId_motzar() { return id_motzar; } public int getStock_after_payment() { return stock_after_payment; } public String getName() { return name_motzar; } public void setName(String name_motzar) { this.name_motzar = name_motzar; } public Double getPrice_motzar() { return price_motzar; } public String getDescription() { return description; } public String getInstruction() { return instruction; } public String getUrl_photo() { return url_photo; } public String getUrl_youtube() { return url_youtube; } @Override public String toString() { return "Motzar{" + "id_motzar=" + id_motzar + ", name_motzar='" + name_motzar + '\'' + ", price_motzar=" + price_motzar + ", description='" + description + '\'' + ", instruction='" + instruction + '\'' + ", url_photo='" + url_photo + '\'' + ", url_youtube='" + url_youtube + '\'' + ", stock_after_payment=" + stock_after_payment + '}'; } }
package com.family.Repository; import com.family.model.Family; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface Familyrepo extends MongoRepository<Family,String> { }
package isden.mois.magellanlauncher.pages; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import isden.mois.magellanlauncher.IsdenTools; import isden.mois.magellanlauncher.Metadata; import isden.mois.magellanlauncher.Onyx; import isden.mois.magellanlauncher.R; import isden.mois.magellanlauncher.helpers.Scroller; import isden.mois.magellanlauncher.models.KeyDownFragment; import isden.mois.magellanlauncher.models.KeyDownListener; import isden.mois.magellanlauncher.utils.ListAdapter; import isden.mois.magellanlauncher.utils.ListTask; import isden.mois.magellanlauncher.utils.ListTaskAdapter; import isden.mois.magellanlauncher.utils.ViewHolder; public class HomeFragment extends KeyDownFragment implements AdapterView.OnItemClickListener { private GridView grid; private AddedBooksAdapter adapter = new AddedBooksAdapter(null); private Scroller scroller = new Scroller(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.page_main, container, false); } @Override public void onResume() { super.onResume(); grid = (GridView) getActivity().findViewById(R.id.addedGrid); adapter.setContext(getContext()); grid.setAdapter(adapter); grid.setOnItemClickListener(this); grid.setOnScrollListener(scroller); new HomeBooksTask(getActivity(), adapter).execute(); } @Override public void onDestroy() { super.onDestroy(); grid = null; adapter = null; } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); File f = new File(((BookViewHolder) view.getTag()).path); intent.setDataAndType(Uri.fromFile(f), IsdenTools.get_mime_by_filename(f.getName().toLowerCase())); try { getActivity().startActivity(intent); } catch (Exception e) { Toast.makeText(getActivity(), /*"Can't start application"*/f.getName().toLowerCase(), Toast.LENGTH_SHORT).show(); } } @Override public void onKeyDown(int keyCode) { if (grid == null) return; if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) { grid.setSelection(scroller.getPrevPageItem()); } else { grid.setSelection(scroller.getNextPageItem()); } grid.invalidate(); } } class HomeBooksTask extends ListTask<Metadata> { private Metadata lastRead; HomeBooksTask(Activity activity, ListTaskAdapter<Metadata> adapter) { super(activity, adapter); } @Override protected void action() { lastRead = Onyx.getCurrentBook(activity); list = Onyx.getLastDownloaded(activity, 20); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); setLastReading(); } private void setLastReading() { if (lastRead == null) return; TextView twTitle = (TextView) activity.findViewById(R.id.txtTitle); TextView twAuthor = (TextView) activity.findViewById(R.id.txtAuthor); if (lastRead.getTitle() != null) { twTitle.setText(lastRead.getTitle()); twAuthor.setText(lastRead.getAuthor()); } else { twTitle.setText(lastRead.getName()); twAuthor.setHeight(0); } ImageView imgBook = (ImageView) activity.findViewById(R.id.imgBook); Bitmap image = lastRead.getThumbnail(); if (image == null) { imgBook.setImageResource(R.drawable.book_img); } else { imgBook.setImageBitmap(image); } TextView progressText = (TextView) activity.findViewById(R.id.twProgress); progressText.setText(lastRead.getProgress()); TextView TimeReadText = (TextView) activity.findViewById(R.id.twReadTime); TimeReadText.setText(lastRead.formatTimeProgress()); TextView speedTW = (TextView) activity.findViewById(R.id.twSpeed); speedTW.setText(lastRead.getSpeed()); } } class AddedBooksAdapter extends ListAdapter<Metadata, BookViewHolder> { AddedBooksAdapter(Context context) { super(context, R.layout.item_book); } @Override protected void fillHolder(Metadata item, BookViewHolder holder) { holder.tv.setText(item.title); holder.path = item.filePath; Bitmap thumbnail = item.getThumbnail(); if (thumbnail != null) { holder.iv.setImageBitmap(thumbnail); } else { holder.iv.setImageResource(R.drawable.book_down); } } @Override protected BookViewHolder getHolder(View v) { return new BookViewHolder(v); } } class BookViewHolder extends ViewHolder { TextView tv; ImageView iv; String path; BookViewHolder(View v) { tv = (TextView) v.findViewById(R.id.book_name); iv = (ImageView) v.findViewById(R.id.book_image); } }
package com.test.db.dao; import java.util.ArrayList; import com.test.db.dto.MemberDto; public interface MemberDao { public ArrayList<MemberDto> memberList(); public void memberJoin(String mName, String mPhone, String mAddr, String mJob); public MemberDto view(int mIdx); public void remove(int mIdx); }
package com.techlab.lskov; public class MallardDuck extends Bird { @Override public void fly() { System.out.println("I can fly at small distance"); } }
package com.serenskye.flickrpaper.model; /** * Created by IntelliJ IDEA. * User: seren * Date: 08/09/12 * Time: 16:17 */ public class PhotoVO { private final String mUrl; private final String mDescription; private final String mAuthor; private final String mTags; private final long uid; public PhotoVO(String url, String description, String author, String tags) { mUrl = url; mDescription = description; mAuthor = author; mTags = tags; uid = System.currentTimeMillis(); } public String getUrl() { return mUrl; } public String getDescription() { return mDescription; } public String getAuthor() { return mAuthor; } public String getTags() { return mTags; } public long getUid() { return uid; } public String toString(){ return mUrl; } }
/* 子父类中的构造函数: 1.为什么子类一定要访问父类中的空参数的构造函数? 答:因为父类中的数据,子类可以直接获取;所以子类对象在建立时, 需要先查看父类是如何对这些数据进行初始化的,所以子类在对象初始化时, 要先访问一下父类中的构造函数; 如果要访问父类中指定的构造函数,可以通过手动定义super的方式来指定。 当父类中重写了构造函数,没有空参数的构造函数了,那么子类一定要显示的调用父类中改写的构造函数 注意:super也应该放在构造函数的第一行。如果子类中将this放在了第一行,那么就会调用this中的 super,本函数不用再写super。 结论: 子类中所有的构造函数,默认都会访问父类中空参数的构造函数 因为子类中每一个构造函数的第一行都有一个空参数的隐式的super() 当父类中没有空参数的构造函数时,子类必须通过手动super或者 this语句形式来指定访问一个父类中的构造函数。 当然,子类中的函数第一行也可以手动指定this来访问本类中的构造函数, 子类中至少有一个构造函数会访问父类中的构造函数 2.为啥this、super不能放在同一行? 答:他俩都得放在第一行,因为初始化动作要先做 */ class InheritConstuctor { public static void main(String[] args){ Zi z1 = new Zi(); Zi z2 = new Zi(3); Student s = new Student("lili"); s.method(); // 主动调用 s.show(); //没有向上找 } } class Fu{ Fu(){ System.out.println("fu init"); } Fu(int num){ MyUtil.println("fu init DIY,num = " + num); } } class Zi extends Fu{ Zi(){ // super(); 子类构造函数默认有条隐式的语句, // 它会访问父类中空参数的构造函数,而且子类中所有的构造函数默认第一行都有该隐式的super() System.out.println("zi init"); } Zi(int x){ super(x); System.out.println("zi..." + x); } } class Person{ private String name; Person(String name){ this.name = name; } void show(){ MyUtil.println("Person class " + this.name); } } class Student extends Person{ private String name; Student(String name){ // 调用父类含参数的构造函数 super(name); this.name = name + " Student"; } void method(){ super.show(); MyUtil.println(name); } }
package task4; import java.util.Date; public class SpecialOffer { Product product; String offerDescription; String startDate; String endDate; double discount; SpecialOffer(Product offerForProduct, String specialOfferDescription, String offerStartDate, String offerEndDate, double offerDiscount){ product = offerForProduct; offerDescription = specialOfferDescription; startDate = offerStartDate; endDate = offerEndDate; discount = offerForProduct.price*offerDiscount/100; } }
package testCode.ch9.question; import java.util.Scanner; /** * Created by flyboy on 1/2/2017. */ public class ChoiceQuestionTester { public static void main(String[] args) { ChoiceQuestion cq1 = new ChoiceQuestion(); cq1.setText("What's the first name of Java"); cq1.setChoice("7", false); cq1.setChoice("Duke", false); cq1.setChoice("Oak", true); cq1.setChoice("Gosling", false); ChoiceQuestion cq2 = new ChoiceQuestion(); cq2.setText("In which country was the inventor of Java born?"); cq2.setChoice("Japan", false); cq2.setChoice("Canada", true); cq2.setChoice("America", false); cq2.setChoice("France", false); /* use an instance method */ cq1.presentQuestion(); cq2.presentQuestion(); /* through a static method presentQuestion(cq1); System.out.println(""); presentQuestion(cq2); */ } /** * a static function to present question to user * @param cq */ public static void presentQuestion(ChoiceQuestion cq){ cq.display(); System.out.println("your answer is: "); Scanner in = new Scanner(System.in); String response = in.nextLine(); System.out.println(cq.checkAnswer(response)); } }
package ve.com.mastercircuito.objects; public class Caliber { private Integer id; private Integer caliber; public Caliber() { super(); } public Caliber(Integer id, Integer caliber) { super(); this.id = id; this.caliber = caliber; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCaliber() { return caliber; } public void setCaliber(Integer caliber) { this.caliber = caliber; } }
package com.developers.quickjob.quick_job; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.developers.quickjob.quick_job.dialog.DateDialog; import com.developers.quickjob.quick_job.modelo.Empresa; import com.developers.quickjob.quick_job.restapi.VolleySingleton; import com.developers.quickjob.quick_job.sqlite.Operacionesbd; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by jhonn_aj on 24/11/2016. */ public class RegistersEmpActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { Operacionesbd db; @BindView(R.id.edit_ruc) EditText ruc; @BindView(R.id.edit_nomb_comerc) EditText nombre; @BindView(R.id.edit_email_emp) EditText email; @BindView(R.id.edit_pass_emp) EditText pass; @BindView(R.id.edit_passconf_emp) EditText pass_conf; @BindView(R.id.edit_tipo_emp) EditText tipo; @BindView(R.id.edit_sector) EditText sector; @BindView(R.id.edit_nro_jobs) EditText nrojobs; @BindView(R.id.edit_anho) EditText anho; @BindView(R.id.edit_tefl_emp) EditText telefemp; @BindView(R.id.edit_dpto) EditText dpto; @BindView(R.id.edit_prov) EditText prov; @BindView(R.id.edit_distrt) EditText distr; @BindView(R.id.btn_cuenta_emp) Button btn_crear_cuenta; @BindView(R.id.show_date) ImageButton showDate; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registers_emp); this.setTitle("Crea tu cuenta"); if (this.getSupportActionBar() != null) { this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); } ButterKnife.bind(this); db = Operacionesbd.getInstancia(getApplicationContext()); } @OnClick(R.id.btn_cuenta_emp) public void handleCuentaEmpresa() { if (pass.getText().toString().equals(pass_conf.getText().toString())) { Empresa empresa = new Empresa(); empresa.setRuc(ruc.getText().toString()); empresa.setNombre_comercial(nombre.getText().toString()); empresa.setCorreo(email.getText().toString()); empresa.setContrasenha(pass.getText().toString()); empresa.setTipo_empresa(tipo.getText().toString()); empresa.setSector(sector.getText().toString()); empresa.setNro_trabajadores(Integer.parseInt(nrojobs.getText().toString())); empresa.setFundacion_anho(anho.getText().toString()); empresa.setTelef_referencia(Integer.parseInt(telefemp.getText().toString())); empresa.setUbic_dprt(dpto.getText().toString()); empresa.setUbic_provincia(prov.getText().toString()); empresa.setUbic_direccion(distr.getText().toString()); registrarEmpresa(empresa); /*if (db.registrarEmpresa(empresa) == true) { ///db.obtenerEmpresa(); //String id = db.verficaremprs(empresa.getCorreo(), empresa.getContrasenha()); //Intent intent = new Intent(getApplicationContext(), MainActivityEmp.class); //intent.putExtra(MainActivityEmp.ID, id); //Log.d(RegistersEmpActivity.class.getName(), " Registrado + " + id); //startActivity(intent); } else { Toast.makeText(getApplicationContext(), " Completar campos requeridos ", Toast.LENGTH_SHORT).show(); }*/ } } public void registrarEmpresa(Empresa empresa){ String url="http://unmsmquickjob.pe.hu/quickjob/registrar_empresa.php"; final String ruc=empresa.getRuc(); final String nomb=empresa.getNombre_comercial(); final String correo=empresa.getCorreo(); final String pass=empresa.getContrasenha(); final String tipo=empresa.getTipo_empresa(); final String sector=empresa.getSector(); final String nro=String.valueOf(empresa.getNro_trabajadores()); final String fund=String.valueOf(empresa.getFundacion_anho()); final String telef=String.valueOf(empresa.getTelef_referencia()); final String dpto=empresa.getUbic_dprt(); final String prov=empresa.getUbic_provincia(); final String distrit=empresa.getUbic_direccion(); final String direc=empresa.getUbic_direccion(); HashMap<String,String> map = new HashMap<>(); map.put("ruc",ruc); map.put("nomb",nomb); map.put("correo",correo); map.put("pass",pass); map.put("tipo",tipo); map.put("sector",sector); map.put("num",nro); map.put("anio",fund); map.put("telf",telef); map.put("dpto",dpto); map.put("provincia",prov); map.put("distrito",distrit); map.put("direccion",direc); JSONObject jsonObject= new JSONObject(map); Log.d(RegistersEmpActivity.class.getName(),jsonObject.toString()); VolleySingleton.getInstance(getApplicationContext()).addRequestQueue( new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { procesarRespuesta(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(RegistersEmpActivity.class.getName(), "Error Volley: " + error.getMessage()); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String ,String> headers= new HashMap<String, String>(); headers.put("Content-Type","application/json; charset=utf-8"); headers.put("Accept","application/json"); return headers; } @Override public String getBodyContentType() { return "application/json; charset=utf-8" + getParamsEncoding(); } }); } private void procesarRespuesta(JSONObject response){ try { String estado=response.getString("estado"); String mensaje= response.getString("mensaje"); switch (estado){ case "1": Toast.makeText(getApplicationContext(),mensaje,Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); startActivity(intent); break; case "2": Toast.makeText(getApplicationContext(),mensaje,Toast.LENGTH_LONG).show(); break; } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { anho.setText("" + i + "-" + (i1+1) + "-" + i2); } @OnClick(R.id.show_date) public void onClick() { DateDialog dateDialog =new DateDialog(); dateDialog.show(getSupportFragmentManager(), "datepicker"); } }
package chc; public class TestClean { private static Hypothesis[] hypo = new Hypothesis[10]; private static int[] iii = {1,1,1,1,1,1,1,1}; private static Hypothesis h = new Hypothesis(0, iii); public static void main(String[] args) { hypo[0] = h; for (int i = 1; i < hypo.length; i++) { hypo[i] = null; } hypo = CHC.cleanHypo(hypo); System.out.println(hypo.length); for (int i = 0; i < hypo.length; i++) { hypo[i].displayHypothesis(); } } }
package edu.action.evaluation; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.db.dao.evaluation.LoginDao; import edu.servlet.HttpRequestUtil; public class LoginCheck { public static String getId(final HttpServletRequest req) throws Exception { final LoginDao loginDao = LoginDao.getInstance(); final HttpSession session = req.getSession(false); if (session == null) { req.setAttribute("errorMessage", "Please Login"); return null; } final String id = (String) session.getAttribute("id"); final String password = (String) session.getAttribute("password"); if (id == null) { req.setAttribute("errorMessage", "Please Login"); return null; } final Map<String, String> map = loginDao.getMap(); final String aPassword = map.get(id); if (aPassword == null || !aPassword.equals(password)) { req.setAttribute("errorMessage", "ID/PASSWORD is incorrect"); return null; } return id; } public static boolean createSession(final HttpServletRequest req) throws Exception { final String id = HttpRequestUtil.getString(req, "id"); final String password = HttpRequestUtil.getString(req, "password"); final LoginDao loginDao = LoginDao.getInstance(); final Map<String, String> loginMap = loginDao.getMap(); final String aPassword = loginMap.get(id); if (aPassword == null || !aPassword.equals(password)) { req.setAttribute("errorMessage", "ID/PASSWORD is incorrect"); return false; } final HttpSession session = req.getSession(false); session.setAttribute("id", id); session.setAttribute("password", password); return true; } }
package com.m3.training.inventoryproject; public class Item { private int ID; private String itemName; private int quantity; public Item() { } public Item(String itemName, int quantity) { this.itemName = itemName; this.quantity = quantity; } public Item(int ID, String itemName, int quantity) { this.ID = ID; this.itemName = itemName; this.quantity = quantity; } public int getID() { return ID; } public void setID(int iD) { ID = iD; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public boolean equals(Item item) { if( this.ID == item.ID && this.itemName.equals(item.itemName) && this.quantity == item.quantity) { return true; } else return false; } }
package com.tencent.mm.plugin.appbrand.jsapi.j; import com.tencent.mm.plugin.appbrand.jsapi.j.e.b; class e$b$2 implements Runnable { final /* synthetic */ b fXl; e$b$2(b bVar) { this.fXl = bVar; } public final void run() { b.a(this.fXl); } }
package com.tencent.mm.plugin.facedetect.c; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; class c$2 implements OnClickListener { final /* synthetic */ int bFq; final /* synthetic */ int bFr; final /* synthetic */ String dJG; final /* synthetic */ c iMZ; final /* synthetic */ boolean iNa; final /* synthetic */ Bundle iNb; c$2(c cVar, boolean z, int i, int i2, String str, Bundle bundle) { this.iMZ = cVar; this.iNa = z; this.bFq = i; this.bFr = i2; this.dJG = str; this.iNb = bundle; } public final void onClick(View view) { if (this.iNa) { c cVar = this.iMZ; cVar.aJv(); cVar.hUE = true; return; } this.iMZ.a(this.bFq, this.bFr, this.dJG, this.iNb); } }
package org.basic.comp.abst; import com.global.App; import com.global.util.Load; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ODocument; import org.basic.comp.adapter.TableModelAdapter; import org.basic.dao.adapter.DaoInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class TableModelAbs extends TableModelAdapter implements TableModel { protected String[] nameColumn; protected List models; protected List<ODocument> modelDocs = new ArrayList<>(); protected Paging paging; protected ListWidget listWidget; protected DaoInterface dao; protected String textSearch; protected HashMap<String, String> mapSearch; public TableModelAbs() { super(); init(); } public void init() { models=new ArrayList<>(); } public String[] getNameColumn() { return nameColumn; } public void setNameColumn(String[] nameColumn) { this.nameColumn = nameColumn; } public List getModels() { return models; } public void setModels(List models) { this.models = models; } public Paging getPaging() { return paging; } public void setPaging(Paging paging) { this.paging = paging; } public ListWidget getListWidget() { return listWidget; } public void setListWidget(ListWidget listWidget) { this.listWidget = listWidget; } @Override public int getRowCount() { return models.size(); } @Override public int getColumnCount() { return nameColumn.length; } @Override public String getColumnName(int i) { return nameColumn[i]; } @Override public void load(ODatabaseDocumentTx db) { modelDocs=Load.load(db, paging, dao, modelDocs); convertDocsToObjects(); fireTableDataChanged(); } public void convertDocsToObjects() { } public void loadSearchLike(ODatabaseDocumentTx db, String col, String value) { Load.loadSimpleSearchLikePersenValuePersen(db, paging, dao, modelDocs, col, value); convertDocsToObjects(); fireTableDataChanged(); } public void loadCollectionSearchLike(ODatabaseDocumentTx db, String col, String col2, String value) { Load.loadCollectionSimpleSearchLikePersenValuePersen(db, paging, dao, modelDocs, col, col2, value); convertDocsToObjects(); fireTableDataChanged(); } @Override public void reload() { ODatabaseDocumentTx db = App.getDbdLocal(); if ((textSearch == null || textSearch.trim().equals("")) && (mapSearch == null || mapSearch.size() == 0)) { load(db); } else if (mapSearch != null && mapSearch.size() > 0) { } else if (textSearch != null && !textSearch.trim().equals("")) { } fireTableDataChanged(); } public int getNo(int rowIndex){ int no = rowIndex + 1; if (paging != null) { no +=paging.getCountStart(); } return no; } @Override public void editModel(Object model, int index) { fireTableDataChanged(); } @Override public void addModel(Object model) { models.add(model); fireTableDataChanged(); } public String getTextSearch() { return textSearch; } public void setTextSearch(String textSearch) { this.textSearch = textSearch; } public HashMap<String, String> getMapSearch() { return mapSearch; } public void setMapSearch(HashMap<String, String> mapSearch) { this.mapSearch = mapSearch; } @Override public void setBind(Object o) { // TODO Auto-generated method stub } @Override public void delModel(ODatabaseDocumentTx db, int i) { ODocument o=modelDocs.get(i); dao.delete(db, o); modelDocs.remove(i); models.remove(i); fireTableDataChanged(); } @Override public void addObj(Object model) { models.add(model); fireTableDataChanged(); } }
package com.example.screeningapplication; /** * Created by tpf on 2018-08-17. */ public class Category { public static final int CHAIRMAN = 0; //是主席 public static final int NON_CHAIRMAN = 1; //是非主席 public static final int SAME_NAME = 2; //用户名重复 public static final int DIFFERENT_NAME = 3; //用户名不重复 public static final int USERS_INFO = 4; //用户信息 public static final int BEGIN_CAST = 5; //开始投屏 public static final int STOP_CAST = 6; //停止投屏 public static final int GET_OFF = 7; //用户下线 public static final int ROLE_TRANSFER = 8; //角色转移 public static final int FAILED_TO_CONNECT = 9; //socket连接失败 }
package com.tenant.dal; import java.util.List; import java.util.Map; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import com.google.common.collect.Maps; import com.tenant.framework.CurrentTenant; import com.tenant.framework.NoCurrentTenantException; import com.tenant.framework.TenantIdsResolver; public class TenantRoutingDataSource extends AbstractRoutingDataSource { private CurrentTenant currentTenant; private TenantIdsResolver tenantIdsResolver; @Override protected Object determineCurrentLookupKey() { String tenantId = currentTenant.get(); if (tenantId == null) { throw new NoCurrentTenantException( "current tenant id isn't set, unable to proceed. hint: do u want to use " + CurrentTenant.class + ".set method?"); } return tenantId; } public void setCurrentTenant(CurrentTenant currentTenant) { this.currentTenant = currentTenant; } public void setTenantIdsResolver(TenantIdsResolver tenantIdsResolver) { this.tenantIdsResolver = tenantIdsResolver; } @Override public void afterPropertiesSet() { List<String> tenantIds = tenantIdsResolver.getIds(); if (!tenantIds.isEmpty()) { currentTenant.set(tenantIds.get(0)); } Map<Object, Object> targetDataSources = Maps.newHashMap(); for (String tenantId : tenantIds) { targetDataSources.put(tenantId, tenantId);// ds lookup will resolve to DataSource } super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } }
package de.uni_luebeck.itm.itp2017.gruppe2.PiLib; import org.kohsuke.args4j.CmdLineParser; import de.uni_luebeck.itm.itp2017.gruppe2.PiLib.tasks.FaceTask; import de.uni_luebeck.itm.itp2017.gruppe2.PiLib.tasks.SoundTask; import de.uni_luebeck.itm.itp2017.gruppe2.PiLib.util.Configuration; /** * Start-Point */ public class App { public static void main(String[] args) throws Throwable { Configuration config = new Configuration(); CmdLineParser cmdLineParser = new CmdLineParser(config); System.out.println("Possible Arguments:"); cmdLineParser.printUsage(System.out); cmdLineParser.parseArgument(args); System.out.println("starting..."); // decide whether to start the face or sound task. if ("face".equals(config.getMODE())) { new FaceTask().run(config); } else { new SoundTask().run(config); } } }
package ch.fhnw.edu.cpib.cst; import ch.fhnw.edu.cpib.cst.interfaces.ICastOpr; import ch.fhnw.edu.cpib.cst.interfaces.IFactor; // factor ::= castOpr factor public class FactorCastOpr extends Production implements IFactor { protected final ICastOpr N_castOpr; protected final IFactor N_mfactor; public FactorCastOpr(final ICastOpr n_castOpr, final IFactor n_mfactor) { N_castOpr = n_castOpr; N_mfactor = n_mfactor; } @Override public ch.fhnw.edu.cpib.ast.interfaces.IFactor toAbsSyntax() { return new ch.fhnw.edu.cpib.ast.CastFactor(N_castOpr.toAbsSyntax(), N_mfactor.toAbsSyntax()); } }
package com.philippe.app.service.avro; import org.apache.avro.specific.SpecificRecord; import java.io.IOException; public interface AvroCodecService<T extends SpecificRecord> { /** * Encodes an Avro object to a byte[]. * * @param message - Avro object which needs to be encoded. * @return byte[] - serialized byte array. */ byte[] encode(T message) throws IOException; /** * Decodes a byte[] to an Avro object. */ T decode(byte[] byteArray) throws InstantiationException, IllegalAccessException, IOException; }
package it.unical.asd.group6.computerSparePartsCompany.core.services; import it.unical.asd.group6.computerSparePartsCompany.data.dto.PurchaseNoticeDTO; import it.unical.asd.group6.computerSparePartsCompany.data.entities.Customer; import it.unical.asd.group6.computerSparePartsCompany.data.entities.PurchaseNotice; import java.time.LocalDate; import java.util.List; public interface PurchaseNoticeService { List<PurchaseNoticeDTO> getView(); Boolean add(PurchaseNotice p); List<PurchaseNoticeDTO> getAll(); List<PurchaseNoticeDTO> getAllByCustomer(Customer c); List<PurchaseNoticeDTO>getAllPurchaseNoticeByFilters(String username, LocalDate l); }
package org.switchyard.quickstarts.publish.as.webservice; import org.switchyard.component.bean.Service; @Service(value = HelloWorldPubService.class, componentName = "ESBServiceSample") public class ESBWSListenerAction implements HelloWorldPubService { public String displayMessage(String message) { if (message.contains("Error")) { final String detail = "<say:sayFault xmlns:say=\"http://www.jboss.org/sayHi\"><say:code>" + "myErrorCode" + "</say:code><say:faultString>" + "myDescription" + "</say:faultString></say:sayFault>"; //@formatter:off return "<env:Fault xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<faultcode xmlns:say=\"http://www.jboss.org/sayHi\">say:myErrorCode</faultcode>" + "<faultstring>myDescription</faultstring>" + "<detail>" + detail + "</detail>" + "</env:Fault>"; //@formatter:on } System.out.println("Received request: " + message); final String responseMsg = "<say:sayHiResponse xmlns:say=\"http://www.jboss.org/sayHi\"><say:arg0>" + "Response from ESB Service" + "</say:arg0></say:sayHiResponse>"; return responseMsg; } }
package com.tencent.mm.plugin.mmsight.ui; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; class MMSightRecordButton$2 extends AnimatorListenerAdapter { final /* synthetic */ MMSightRecordButton loJ; final /* synthetic */ AnimatorListenerAdapter loL = null; MMSightRecordButton$2(MMSightRecordButton mMSightRecordButton) { this.loJ = mMSightRecordButton; } public final void onAnimationStart(Animator animator) { MMSightRecordButton.a(this.loJ, true); if (this.loL != null) { this.loL.onAnimationStart(animator); } } public final void onAnimationEnd(Animator animator) { MMSightRecordButton.a(this.loJ, false); if (this.loL != null) { this.loL.onAnimationEnd(animator); } } }
import java.util.ArrayList; public class Student { private String lastName; private String firstName; private int studentID; private final ArrayList<Course> registeredCourses = new ArrayList<Course>(); public Student() { } public Student(String lastName, String firstName, int studentID) { this.lastName = lastName; this.firstName = firstName; this.studentID = studentID; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getStudentID() { return studentID; } public void setStudentID(int studentID) { this.studentID = studentID; } /* * Add course to students list of registered courses */ public void registerForCourse(Course course) { if (!registeredCourses.contains(course)) { registeredCourses.add(course); } else { System.out.println("Student already registered for course!"); } } /* * Remove course from students list of registered courses */ public void unregisterForCourse(Course course) { if (registeredCourses.contains(course)) { registeredCourses.remove(course); } } public void showRegisteredCourses() { for (int i = 0; i < registeredCourses.size(); i++) { System.out.println(registeredCourses.get(i).toString()); } } public String toString() { return "Last Name:" + lastName + ", First Name:" + firstName + ", ID:" + studentID; } }
package LightProcessing.common.item; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Direction; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.World; import LightProcessing.common.lib.*; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemLightPickaxe extends ItemPickaxe { public ItemLightPickaxe(EnumToolMaterial EnumToolMaterial) { super(par2EnumToolMaterial); this.setUnlocalizedName("LightPickaxe"); this.setCreativeTab(ItemTab.itemTab); } public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean bool) { if (itemstack.stackTagCompound == null) { itemstack.stackTagCompound = new NBTTagCompound(); itemstack.getTagCompound().setString("color", "white"); itemstack.getTagCompound().setInteger("mode", 1); } } public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player) { if(!world.isRemote) { if(player.isSneaking()) { int mode = itemstack.getTagCompound().getInteger("mode"); mode++; if(mode > 3) mode = 1; switch(mode) { case 1: itemstack.getTagCompound().setString("color", "white"); break; case 2: itemstack.getTagCompound().setString("color", "gold"); break; case 3: itemstack.getTagCompound().setString("color", "purple"); break; } if(world.isRemote) getColorFromItemStack(itemstack, 0); itemstack.getTagCompound().setInteger("mode", mode); } } return itemstack; } @SideOnly(Side.CLIENT) public int getColorFromItemStack(ItemStack itemstack, int par2){ if (itemstack.stackTagCompound != null) { String color = itemstack.getTagCompound().getString("color"); if(color == "white") return 0xffffff; else if(color == "gold") return 0xffed97; else if(color == "purple") return 0xbb63ff; } return 0xffffff; } public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int par4, int par5, int par6, int par7, float par8, float par9, float par10) { if(player.isSneaking()) return false; int mode = itemstack.getTagCompound().getInteger("mode"); switch(mode) { case 1: return mode1(player, world, par4, par5, par6, par7, itemstack); case 2: return mode2(player, world, par4, par5, par6); case 3: return mode3(player, world); default: return false; } } public boolean mode1(EntityPlayer player, World world, int par4, int par5, int par6, int par7, ItemStack itemstack) { int i = 0, j = 0, k = 0, isizeNS = 0, isizeEW = 0, jsizeNS = 0, jsizeEW = 0, ksizeNS = 0, ksizeEW = 0; Block id = world.getBlock(par4, par5, par6); if(world.getWorldTime() < 12500) { if(Methods.lightCheck(world, par4, par5, par6, 7)) { if(Methods.hasItem(player, IDRef.LIGHT_BALL_IDD)) { switch(par7) { case 5: isizeNS = -2; isizeEW = 0; jsizeNS = -1; jsizeEW = 1; ksizeNS = -1; ksizeEW = 1; break; case 4: isizeNS = 0; isizeEW = 2; jsizeNS = -1; jsizeEW = 1; ksizeNS = -1; ksizeEW = 1; break; case 3: isizeNS = -1; isizeEW = 1; jsizeNS = -1; jsizeEW = 1; ksizeNS = -2; ksizeEW = 0; break; case 2: isizeNS = -1; isizeEW = 1; jsizeNS = -1; jsizeEW = 1; ksizeNS = 0; ksizeEW = 2; break; case 1: isizeNS = -1; isizeEW = 1; jsizeNS = -2; jsizeEW = 0; ksizeNS = -1; ksizeEW = 1; break; case 0: isizeNS = -1; isizeEW = 1; jsizeNS = 0; jsizeEW = 2; ksizeNS = -1; ksizeEW = 1; break; } if (player instanceof EntityPlayerMP) { ((EntityPlayerMP)player).theItemInWorldManager.setBlockReachDistance(6.0D); } if((id == Blocks.cobblestone || id == Blocks.stone || id == Blocks.sandStone) && id != Blocks.air) { for(i = isizeNS; i <= isizeEW; i++) { for(j = jsizeNS; j <= jsizeEW; j++) { for(k = ksizeNS; k <= ksizeEW; k++) { id = world.getBlock(par4 + i, par5 + j, par6 + k); if((id == Blocks.cobblestone || id == Blocks.stone || id == Blocks.sandstone) && id != Blocks.air) { Block block = Block.blocksList[id]; ArrayList<ItemStack> item = block.getBlockDropped(world, par4 + i, par5 + j, par6 + k, 0, 0); if(item.isEmpty()) continue; ItemStack itemBlock = item.get(0); EntityItem entityBlock = new EntityItem(world, par4 + i, par5 + j, par6 + k, itemBlock); if (!world.isRemote) world.spawnEntityInWorld(entityBlock); world.setBlockToAir(par4 + i, par5 + j, par6 + k); } } } } Methods.useItem(player, IDRef.LIGHT_BALL_ID); } else return false; } } } return true; } public boolean mode2(EntityPlayer player, World world, int par4, int par5, int par6) { if(world.getWorldTime() < 12500) { if(Methods.lightCheck(world, par4, par5, par6, 7)) { if(Methods.useItem(player, IDRef.LIGHT_BALL_IDD)) { Block id = world.getBlock(par4, par5, par6); if(id == Blocks.bedrock) return false; Block block = Block.blocksList[id]; ItemStack item = new ItemStack(block, 1); EntityItem entityBlock = new EntityItem(world, par4, par5, par6, item); if (!world.isRemote) world.spawnEntityInWorld(entityBlock); world.setBlockToAir(par4, par5, par6); return true; } } } return false; } public boolean mode3(EntityPlayer player, World world) { if(!world.isRemote) player.addChatMessage("Twilight Sparkle is best Pony"); return true; } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { itemIcon = iconRegister.registerIcon(Methods.textureName(this.getUnlocalizedName())); } }
package herencia; import java.util.Scanner; /** * * @author OHMASTER */ public class Dog { String name; double weight; String colour; void LlenarDatosPerro() { Scanner sc = new Scanner(System.in); System.out.println("Ingresa el nombre del perro"); name = sc.nextLine(); System.out.println("Ingresa el color del perro"); colour = sc.nextLine(); System.out.println("Ingresa el peso del perro"); weight = sc.nextDouble(); } void VerSalida() { System.out.println("Los datos del perro son: "); System.out.println("Nombre del perro: " + name); System.out.println("Color del perro: " + colour); System.out.println("Peso: " + weight); } }
package com.ibm.ive.tools.japt; import java.io.*; /** * Represents a resource found on the classpath, or a resource yet to be created */ public abstract class Resource { protected Resource() {} /** * @return the time of the last modification to this resource in milliseconds since the epoch */ public abstract long getTime(); /** * @return the name */ public abstract String getName(); /** * @return the byte contents as an input stream */ public abstract InputStream getInputStream() throws IOException; /** * @return null or the location (class/zip/jar file) from where this resource originates */ public abstract String loadedFrom(); }
/** * ファイル名 : VSM16010XService.java * 作成者 : nv-manh * 作成日時 : 2018/05/31 * Copyright © 2017-2018 TAU Corporation. All Rights Reserved. */ package jp.co.tau.web7.admin.supplier.services; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.persistence.RollbackException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import jp.co.tau.web7.admin.supplier.common.CommonConstants; import jp.co.tau.web7.admin.supplier.common.NumberingConstants; import jp.co.tau.web7.admin.supplier.common.UnivMstConstants; import jp.co.tau.web7.admin.supplier.dto.SelectItemDTO; import jp.co.tau.web7.admin.supplier.dto.VSM16010XDTO; import jp.co.tau.web7.admin.supplier.entity.MUnivMstEntity; import jp.co.tau.web7.admin.supplier.entity.TVsmNewsInfoDispDivEntity; import jp.co.tau.web7.admin.supplier.entity.TVsmNewsInfoEntity; import jp.co.tau.web7.admin.supplier.forms.VSM16010XForm; import jp.co.tau.web7.admin.supplier.mappers.TVsmNewsInfoDispDivMapper; import jp.co.tau.web7.admin.supplier.mappers.TVsmNewsInfoMapper; import jp.co.tau.web7.admin.supplier.mappers.TVsmRoleMapper; /** * <p> * クラス名 : VSM16010XService * </p> * <p> * 説明 : お知らせ登録サービス * </p> * * @author nv-manh * @since 2018/05/31 */ @Service public class VSM16010XService extends BaseService { @Autowired private TVsmRoleMapper tVsmRoleMapper; @Autowired private TVsmNewsInfoMapper tVsmNewsInfoMapper; @Autowired private TVsmNewsInfoDispDivMapper tVsmNewsInfoDispDivMapper; @Autowired private CommonService commonService; /** * <p> * 説明 : FIXME: init priority list * </p> * * @author luantx * @since 2018/05/31 * @param mav ModelAndView * @return vsm15010XForm */ public List<SelectItemDTO> initPriorityList() { List<MUnivMstEntity> lsUnivMstEntity = commonService.initMasterData(new VSM16010XForm().getPriorityCd()); List<SelectItemDTO> priorityList = lsUnivMstEntity.stream().map(x -> new SelectItemDTO(x.getUnivMstCd(), x.getUnivMstCdNm())) .collect(Collectors.toList()); return priorityList; } /** * <p> * 説明 : FIXME: registerNotice * </p> * * @author luantx * @since 2018/05/31 * @param VSM16010XDTO vsm16010XDTO */ @Transactional(rollbackFor = Exception.class) public int registerNotice(VSM16010XDTO vsm16010XDTO) { vsm16010XDTO.setNewsInfoNo(String.valueOf(tVsmNewsInfoMapper.getMaxNewsInfoNo(vsm16010XDTO.getAucTypeCd()))); TVsmNewsInfoEntity tVsmNewsInfoEntity = vsm16010XDTO.getTVsmNewsInfoEntity(); tVsmNewsInfoEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoEntity); List<TVsmNewsInfoDispDivEntity> tVsmNewsInfoDispDivEntityList = new ArrayList<TVsmNewsInfoDispDivEntity>(); /* オリックス自動車表示区分 */ if (!vsm16010XDTO.getOptionOA().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_01.getCode(), CommonConstants.newsDispDivCd.CODE_01.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } /* オリックス環境表示区分 */ if (!vsm16010XDTO.getOptionOE().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_02.getCode(), CommonConstants.newsDispDivCd.CODE_02.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } /* TAU表示区分 */ if (!vsm16010XDTO.getOptionTAU().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_03.getCode(), CommonConstants.newsDispDivCd.CODE_03.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } /* フロント表示区分 */ if (!vsm16010XDTO.getOptionFront().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_04.getCode(), CommonConstants.newsDispDivCd.CODE_04.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } if (tVsmNewsInfoMapper.insert(tVsmNewsInfoEntity) <= 0) return 0; if (tVsmNewsInfoDispDivEntityList.size() >= 0) if (tVsmNewsInfoDispDivMapper.insertList(tVsmNewsInfoDispDivEntityList) <= 0) return 0; return 1; } /** * <p> * 説明 : FIXME: update Notice * </p> * * @author luantx * @since 2018/05/31 * @param VSM16010XDTO vsm16010XDTO * @throws Exception */ @Transactional(rollbackFor = Exception.class) public void updateNotice(VSM16010XDTO vsm16010XDTO) throws Exception { TVsmNewsInfoEntity tVsmNewsInfoEntity = vsm16010XDTO.getTVsmNewsInfoEntity(); tVsmNewsInfoEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoEntity); List<TVsmNewsInfoDispDivEntity> tVsmNewsInfoDispDivEntityList = new ArrayList<TVsmNewsInfoDispDivEntity>(); /* オリックス自動車表示区分 */ if (!vsm16010XDTO.getOptionOA().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_01.getCode(), CommonConstants.newsDispDivCd.CODE_01.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } /* オリックス環境表示区分 */ if (!vsm16010XDTO.getOptionOE().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_02.getCode(), CommonConstants.newsDispDivCd.CODE_02.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } /* TAU表示区分 */ if (!vsm16010XDTO.getOptionTAU().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_03.getCode(), CommonConstants.newsDispDivCd.CODE_03.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } /* フロント表示区分 */ if (!vsm16010XDTO.getOptionFront().isEmpty()) { TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity = vsm16010XDTO.getTVsmNewsInfoDispDivEntity(vsm16010XDTO, CommonConstants.newsDispDivCd.CODE_04.getCode(), CommonConstants.newsDispDivCd.CODE_04.getText()); tVsmNewsInfoDispDivEntity.setCreateUser(vsm16010XDTO.getCreateUser()); tVsmNewsInfoDispDivEntity.setUpdateUser(vsm16010XDTO.getUpdateUser()); copyCreateInfo(tVsmNewsInfoDispDivEntity); tVsmNewsInfoDispDivEntityList.add(tVsmNewsInfoDispDivEntity); } if (tVsmNewsInfoMapper.updateNotificationInfo(tVsmNewsInfoEntity) <= 0) throw new RollbackException(); /* Get all tVsmNewsInfoDispDivEntityList old */ List<TVsmNewsInfoDispDivEntity> tVsmNewsInfoDispDivEntityListOld = tVsmNewsInfoDispDivMapper.findNewInfoDispDivByInfoNo(vsm16010XDTO.getNewsInfoNo(), vsm16010XDTO.getAucTypeCd(), CommonConstants.DELETE_FLAG_FALSE); tVsmNewsInfoDispDivEntityListOld.stream().forEach(x -> { copyUpdateInfo(x); x.setUpdateUser(vsm16010XDTO.getUpdateUser()); x.setDeleteFlg(CommonConstants.DELETE_FLAG_TRUE); x.setDeleteTime(LocalDateTime.now()); x.setNewsDispFlg(CommonConstants.NEWS_DISP_FLG_OFF); }); /* Delete all tVsmNewsInfoDispDivEntityList old */ if (tVsmNewsInfoDispDivEntityListOld.size() > 0) if (tVsmNewsInfoDispDivMapper.deleteNotificationInfoDispByInfoNo(tVsmNewsInfoDispDivEntityListOld) <= 0) throw new RollbackException(); List<String> newsDispDivCdListOld = tVsmNewsInfoDispDivEntityListOld.stream().map(x -> x.getNewsDispDivCd()).collect(Collectors.toList()); /* Insert or update tVsmNewsInfoDispDivEntityList new */ for (TVsmNewsInfoDispDivEntity tVsmNewsInfoDispDivEntity : tVsmNewsInfoDispDivEntityList) { if (newsDispDivCdListOld.indexOf(tVsmNewsInfoDispDivEntity.getNewsDispDivCd()) != -1) { if (tVsmNewsInfoMapper.updateNotificationInfoDisp(tVsmNewsInfoDispDivEntity) <= 0) throw new RollbackException(); } else { if (tVsmNewsInfoDispDivMapper.insert(tVsmNewsInfoDispDivEntity) <= 0) throw new RollbackException(); } } } /** * <p> * 説明 : FIXME: get detail notice * </p> * * @author luantx * @since 2018/05/31 * @param String Id * @return VSM16010XDTO */ public VSM16010XDTO getDetailNewNotice(String Id) { VSM16010XDTO vsm16010XDTO = tVsmNewsInfoMapper.getDetailNewNotice(NumberingConstants.MEM_TYPE_CD_VSM, Id, CommonConstants.DELETE_FLAG_FALSE, CommonConstants.newsDispDivCd.CODE_01.getCode(), CommonConstants.newsDispDivCd.CODE_02.getCode(), CommonConstants.newsDispDivCd.CODE_03.getCode(), CommonConstants.newsDispDivCd.CODE_04.getCode(), UnivMstConstants.B300); return vsm16010XDTO; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.javanile.me.chess.engines; /** * * @author cicciodarkast */ public class Node { private char[][] board; private int turn = 0; private Square focus_square; public Node() { this(Constants.START_POSITION); } public Node(String fen) { parse_fen(fen); } public void set(Node node) { try { turn = node.getTurn(); char[][] temp = node.getBoard(); for(int r=0;r<12;r++) { for(int c=0;c<12;c++) { board[r][c] = temp[r][c]; } } } catch (Exception e) { e.printStackTrace(); } } public void setFocusSquare(Square s) { focus_square = s; } public void doMove(Move m) { switch(m.getKind()) { case Constants.MK_SIMPLE: default: setBoard(m.getTo(),getBoard(m.getFrom())); setBoard(m.getFrom(),'.'); break; } changeTurn(); } public void unMove(Move m) { switch(m.getKind()) { case Constants.MK_SIMPLE: default: setBoard(m.getTo(),m.getCaptured()); setBoard(m.getFrom(),m.getPiece()); break; } changeTurn(); } public void setBoard(Square s,char p) { board[s.getRank()+2][s.getFile()+2] = p; } public char getBoard(Square s) { return board[s.getRank()+2][s.getFile()+2]; } public char getBoard(int r, int f) { return board[r+2][f+2]; } public boolean isWhiteTurn() { return turn==1; } public boolean isBlackTurn() { return turn==-1; } public boolean isBlackPawn() { return getBoard(focus_square)=='p'; } public boolean isWhitePawn() { return getBoard(focus_square)=='P'; } public boolean isBlackPawnRank() { return focus_square.getRank()==1; } public boolean isWhitePawnRank() { return focus_square.getRank()==6; } public boolean isFileH() { return focus_square.getFile()==7; } public boolean isFileA() { return focus_square.getFile()==0; } public boolean isWhitePiece() { char p = getBoard(focus_square); if ((p=='P')||(p=='N')||(p=='B')||(p=='R')||(p=='Q')||(p=='K')) return true; return false; } public boolean isBlackPiece() { char p = getBoard(focus_square); if ((p=='p')||(p=='n')||(p=='b')||(p=='r')||(p=='q')||(p=='k')) return true; return false; } private void changeTurn() { turn = -turn; } public int getTurn() { return turn; } public char[][] getBoard() { return board; } public Move getMove(Square from, Square to) { return new Move(getBoard(from),from,to,getBoard(to),Constants.MK_SIMPLE); } public Move getMove(int mk) { Square from = focus_square; Square to = from.shift(Constants.DELTA(getBoard(from), mk)); return new Move(getBoard(from),from,to,getBoard(to),mk); } public Move getMove(String s) { Move m = new Move(s); m.setPiece(getBoard(m.getFrom())); m.setCaptured(getBoard(m.getTo())); return m; } public Move getMove(Square to, int mk) { Square from = focus_square; return new Move(getBoard(from),from,to,getBoard(to),mk); } public boolean isFreeOrOpponentSquare(Square s) { char p = getBoard(s); if (turn == -1) { if ((p=='.')||(p=='P')||(p=='N')||(p=='B')||(p=='R')||(p=='Q')||(p=='K')) return true; } else { if ((p=='.')||(p=='p')||(p=='n')||(p=='b')||(p=='r')||(p=='q')||(p=='k')) return true; } return false; } public boolean haveOpponentPieceIn(Square to) { if (getBoard(to)!='.') { return (getPieceColor(focus_square)!=getPieceColor(to)); } return false; } public int getPieceColor(Square s) { char p = getBoard(s); if ((p=='p')||(p=='n')||(p=='b')||(p=='r')||(p=='q')||(p=='k')) return -1; if ((p=='P')||(p=='N')||(p=='B')||(p=='R')||(p=='Q')||(p=='K')) return 1; return 0; } public boolean isFreeSquare(Square s) { return getBoard(s)=='.'; } private void parse_fen(String fen) { board = new char[12][12]; for(int r=0;r<12;r++) {for(int c=0;c<12;c++) {board[r][c] = '#';}} for(int r=2;r<10;r++) {for(int c=2;c<10;c++) {board[r][c] = '.';}} int s = 0; int i = 0; int r = 0; int c = 0; char l; while(i<fen.length()) { l = fen.charAt(i); if (s==0) { if (l=='/') { r++; c=0; } else if ((l>='a')&&(l<='z')) { board[r+2][c+2] = l; c++; } else if ((l>='A')&&(l<='Z')) { board[r+2][c+2] = l; c++; } else if ((l>='1')&&(l<='8')) { c = c + Integer.parseInt(""+l); } else { s++; } } else if (s==1) { turn = 1; } i++; } } public String toString() { String output = ""; for(int r=0;r<12;r++) { for(int c=0;c<12;c++) { output+=board[r][c]; } output+="\n"; } return output; } }
package com.tencent.mm.plugin.scanner.util; import android.content.Intent; import android.widget.Toast; import com.tencent.mm.g.a.op; import com.tencent.mm.plugin.scanner.b; import com.tencent.mm.pluginsdk.wallet.h; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class e$5 implements Runnable { final /* synthetic */ int bzZ; final /* synthetic */ op hUN; final /* synthetic */ e mMX; e$5(e eVar, op opVar, int i) { this.mMX = eVar; this.hUN = opVar; this.bzZ = i; } public final void run() { if (!bi.oW(this.hUN.bZy.Yy)) { Toast.makeText(this.mMX.getContext(), this.hUN.bZy.Yy, 1).show(); } else if (bi.oW(this.hUN.bZy.bZA)) { x.w("MicroMsg.QBarStringHandler", "resp url is null!"); } else if (this.hUN.bZy.actionType == 1) { h.a(this.mMX.getContext(), 1, this.hUN.bZy.bZA, this.bzZ, null); } else { Intent intent = new Intent(); intent.putExtra("rawUrl", this.hUN.bZy.bZA); b.ezn.j(intent, this.mMX.getContext()); } if (this.mMX.mMU != null) { this.mMX.mMU.o(3, null); } } }
package Domain; /** * @author Samuel */ public class Fee{ private long fee; private String carDescription; public Fee() { } public Fee(long fee, String description) { this.fee = fee; this.carDescription = description; } public long getFee() { return fee; } public void setFee(long fee) { this.fee = fee; } public String getDescription() { return carDescription; } public void setDescription(String description) { this.carDescription = description; } }
package org.rebioma.client; import java.util.List; import org.rebioma.client.bean.AscModel; import com.google.gwt.user.client.rpc.IsSerializable; public class AscModelResult implements IsSerializable { private List<AscModel> results; private int count; public AscModelResult() { } public AscModelResult(List<AscModel> results, int count) { super(); this.results = results; this.count = count; } /** * @return the count */ public int getCount() { return count; } /** * @return the results */ public List<AscModel> getResults() { return results; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } /** * @param results the results to set */ public void setResults(List<AscModel> results) { this.results = results; } }
package odeSolver; import Exceptions.WrongInputException; public class EulerExplicitRK extends RangeKutta { public EulerExplicitRK (DifferentialEquation diff) throws WrongInputException { super (diff, "EulerExplicitRK", "explicit", "1", 1); } @Override /** * 0 | 0 * --|-- * | 1 */ protected void tableInitialize() { // Range-Kutta Matrix First Row this.A[0][0] = 0.0; // Weights Array this.b[0] = 1.0; // Nodes Array this.c[0] = 0.0; } }
/** * Copyright 2012 Marin Solutions */ package pl.finsys.controlerAdvice; import org.springframework.stereotype.Component; @Component public class UserDao { public User readUserName() { return new User("John", "Doe"); } }
/* * Copyright (c) 2009-2011 by Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.osd.operations; import java.io.IOException; import java.util.List; import org.xtreemfs.common.Capability; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.xloc.InvalidXLocationsException; import org.xtreemfs.common.xloc.Replica; import org.xtreemfs.common.xloc.XLocations; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.client.RPCResponse; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse; import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils; import org.xtreemfs.osd.OSDRequest; import org.xtreemfs.osd.OSDRequestDispatcher; import org.xtreemfs.osd.OpenFileTable.OpenFileTableEntry; import org.xtreemfs.osd.operations.EventCloseFile.EventCloseCallback; import org.xtreemfs.osd.stages.DeletionStage.DeleteObjectsCallback; import org.xtreemfs.osd.stages.PreprocStage.CloseCallback; import org.xtreemfs.osd.stages.PreprocStage.DeleteOnCloseCallback; import org.xtreemfs.pbrpc.generatedinterfaces.OSD.unlink_osd_Request; import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceConstants; public final class DeleteOperation extends OSDOperation { final String sharedSecret; final ServiceUUID localUUID; public DeleteOperation(OSDRequestDispatcher master) { super(master); sharedSecret = master.getConfig().getCapabilitySecret(); localUUID = master.getConfig().getUUID(); } @Override public int getProcedureId() { return OSDServiceConstants.PROC_ID_UNLINK; } @Override public void startRequest(final OSDRequest rq) { final unlink_osd_Request args = (unlink_osd_Request) rq.getRequestArgs(); // If the file is open, the deleteOnClose flag will be set. master.getPreprocStage().checkDeleteOnClose(args.getFileId(), new DeleteOnCloseCallback() { @Override public void deleteOnCloseResult(boolean isDeleteOnClose, ErrorResponse error) { closeFileIfNecessary(rq, isDeleteOnClose, args, error); } }); } public void closeFileIfNecessary(final OSDRequest rq, final boolean isDeleteOnClose, final unlink_osd_Request args, final ErrorResponse error) { if (error != null) { rq.sendError(error); return; } if (!isDeleteOnClose) { // File is not open and can be deleted immediately. // Cancel replication of file if (rq.getLocationList().getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) master.getReplicationStage().cancelReplicationForFile(args.getFileId()); master.getDeletionStage().deleteObjects(args.getFileId(), null, rq.getCowPolicy().cowEnabled(), rq, new DeleteObjectsCallback() { @Override public void deleteComplete(ErrorResponse error) { disseminateDeletesIfNecessary(rq, args, error); } }); } else { // Close the file explicitly. master.getPreprocStage().close(args.getFileId(), new CloseCallback() { @Override public void closeResult(OpenFileTableEntry entry, ErrorResponse error) { // Send close event. // This will create new versions if necessary and delete objects (because deleteOnClose is set). OSDOperation closeEvent = master.getInternalEvent(EventCloseFile.class); closeEvent.startInternalEvent(new Object[] { entry.getFileId(), true, entry.getCowPolicy().cowEnabled(), entry.isWrite(), new EventCloseCallback() { @Override public void closeEventResult(ErrorResponse error) { disseminateDeletesIfNecessary(rq, args, error); } } }); } }); } } public void disseminateDeletesIfNecessary(final OSDRequest rq, final unlink_osd_Request args, final ErrorResponse error) { if (error != null) { rq.sendError(error); return; } final Replica localReplica = rq.getLocationList().getLocalReplica(); if (localReplica.isStriped() && localReplica.getHeadOsd().equals(localUUID)) { // striped replica, dissmeninate unlink requests try { final List<ServiceUUID> osds = rq.getLocationList().getLocalReplica().getOSDs(); final RPCResponse[] gmaxRPCs = new RPCResponse[osds.size() - 1]; int cnt = 0; for (ServiceUUID osd : osds) { if (!osd.equals(localUUID)) { gmaxRPCs[cnt++] = master.getOSDClient().unlink(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService, args.getFileCredentials(), args.getFileId()); } } this.waitForResponses(gmaxRPCs, new ResponsesListener() { @Override public void responsesAvailable() { analyzeUnlinkReponses(rq, gmaxRPCs); } }); } catch (IOException ex) { rq.sendInternalServerError(ex); return; } } else { // non striped replica, fini sendResponse(rq); } } public void analyzeUnlinkReponses(final OSDRequest rq, RPCResponse[] gmaxRPCs) { // analyze results try { for (int i = 0; i < gmaxRPCs.length; i++) { gmaxRPCs[i].get(); } sendResponse(rq); } catch (Exception ex) { rq.sendInternalServerError(ex); } finally { for (RPCResponse r : gmaxRPCs) r.freeBuffers(); } } public void sendResponse(OSDRequest rq) { rq.sendSuccess(null, null); } @Override public ErrorResponse parseRPCMessage(OSDRequest rq) { try { unlink_osd_Request rpcrq = (unlink_osd_Request) rq.getRequestArgs(); rq.setFileId(rpcrq.getFileId()); rq.setCapability(new Capability(rpcrq.getFileCredentials().getXcap(), sharedSecret)); rq.setLocationList(new XLocations(rpcrq.getFileCredentials().getXlocs(), localUUID)); return null; } catch (InvalidXLocationsException ex) { return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, ex.toString()); } catch (Throwable ex) { return ErrorUtils.getInternalServerError(ex); } } @Override public boolean requiresCapability() { return true; } @Override public void startInternalEvent(Object[] args) { throw new UnsupportedOperationException("Not supported yet."); } }
package com.argentinatecno.checkmanager.main.fragment_add; import android.content.Context; import com.argentinatecno.checkmanager.db.DataBaseController; import com.argentinatecno.checkmanager.entities.Check; import com.argentinatecno.checkmanager.lib.base.EventBus; import com.argentinatecno.checkmanager.main.fragment_add.events.FragmentAddEvent; public class FragmentAddRepositoryImpl implements FragmentAddRepository { EventBus eventBus; DataBaseController dataBaseController; public FragmentAddRepositoryImpl(EventBus eventBus) { this.eventBus = eventBus; } @Override public void saveCheck(Check check, Context context) { if (check == null) { post("Error. Cierre la App y vuelva a intentarlo."); } else if (check.getNumber() == null || check.getNumber().isEmpty()) { post("Ingrese el numero de cheque."); } else if (check.getAmount() == null || check.getAmount().isEmpty()) { post("Ingrese el monto del cheque."); } else if (check.getExpiration() == null || check.getExpiration().equals("")) { post("Ingrese una fecha de vencimiento valida."); } else if ((check.getOrigin() == null || check.getOrigin().equals("")) && check.getType() == 0) { post("Ingrese el origen del cheque."); } else if ((check.getDestiny() == null || check.getDestiny().equals("")) && check.getType() == 1) { post("Ingrese el destino del cheque."); } else { try { instanceController(context); if (dataBaseController.insertCheck(check)) post(); else post("Error al guardar el cheque."); } catch (Exception e) { post(e.getMessage()); } } } @Override public void updateCheck(Check check, Context context) { if (check == null) { post("Error. Cierre la App y vuelva a intentarlo."); } else if (check.getNumber() == null || check.getNumber().isEmpty()) { post("Ingrese el numero de cheque."); } else if (check.getAmount() == null || check.getAmount().isEmpty()) { post("Ingrese el monto del cheque."); } else if (check.getExpiration() == null || check.getExpiration().equals("")) { post("Ingrese una fecha de vencimiento valida."); } else if (check.getOrigin() == null || check.getOrigin().equals("")) { post("Ingrese el origen del cheque."); } else { instanceController(context); if (dataBaseController.updateCheck(check)) post(); else post("Error al actualizar el cheque."); } } private void post() { FragmentAddEvent addEvent = new FragmentAddEvent(); addEvent.setType(FragmentAddEvent.COMPLETE_EVENT); eventBus.post(addEvent); } private void post(String errorMessage) { FragmentAddEvent addEvent = new FragmentAddEvent(); addEvent.setError(errorMessage); eventBus.post(addEvent); } public void instanceController(Context context) { dataBaseController = new DataBaseController(context); } }
import java.util.*; class ClosetKPoints { class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } } public List<Point> findClosetKPoints(Point[] points, int k) { quickSelect(points, 0, points.length - 1, k); List<Point> result = new LinkedList<>(); for (int i = points.length - 1; i >= points.length - k; i--) { result.add(points[i]); } return result; } private void quickSelect(Point[] points, int start, int end, int k) { int index = partition(points, start, end); if (index == points.length - k) { return; } if (index < points.length - k) { quickSelect(points, index + 1, end, k); } else { quickSelect(points, start, index - 1, k); } } private int partition(Point[] points, int start, int end) { int pivot = distance(points[end]); int i = start; int j = end - 1; while (i <= j) { if (distance(points[i]) > pivot) { swap(points, i, j--); } else { i++; } } swap(points, i, end); return i; } private int distance(Point point) { return point.x * point.x + point.y * point.y; } private void swap (Point[] points, int i, int j) { Point point = points[i]; points[i] = points[j]; points[j] = point; } }
package com.example.mayank.rock_paper_scissor; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.IOException; import java.util.List; import java.util.Locale; public class MainActivityGps extends AppCompatActivity { Button button,button2,button3,button5; int RPS; EditText editText; AppLocationService appLocationService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maingps); if(ContextCompat.checkSelfPermission(MainActivityGps.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivityGps.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET},RPS); } appLocationService=new AppLocationService(MainActivityGps.this); button=(Button) findViewById(R.id.bpedicure); button2=(Button) findViewById(R.id.button2); button3=(Button) findViewById(R.id.button3); button5=(Button) findViewById(R.id.button5); editText=(EditText) findViewById(R.id.editText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Location gpsLocation=appLocationService.getLocationService(LocationManager.GPS_PROVIDER); if(gpsLocation!=null) { double latitude=gpsLocation.getLatitude(); double longitude=gpsLocation.getLongitude(); Toast.makeText(getApplicationContext(), "Mobile Location (GPS): \n latitude :" + latitude +"\n longitude :" + longitude, Toast.LENGTH_LONG).show(); } else { showSettingsAlert("GPS"); } } }); button5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(MainActivityGps.this,MainActivity.class); startActivity(i); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Location nwLocation=appLocationService.getLocationService(LocationManager.NETWORK_PROVIDER); if(nwLocation!=null) { double latitude=nwLocation.getLatitude(); double longitude=nwLocation.getLongitude(); Toast.makeText(getApplicationContext(), "Mobile Location (Nw): \n latitude :" + latitude +"\n longitude :" + longitude, Toast.LENGTH_LONG).show(); } else { showSettingsAlert("NETWORK"); } } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Geocoder gc; gc=new Geocoder(getApplicationContext(), Locale.getDefault()); List<Address> addresses; Location gpsLocation=appLocationService.getLocationService(LocationManager.GPS_PROVIDER); Location nwLocation=appLocationService.getLocationService(LocationManager.NETWORK_PROVIDER); if(nwLocation!=null || gpsLocation!=null) { double lol=nwLocation.getLatitude(); double lom=nwLocation.getLongitude(); try { addresses=gc.getFromLocation(lol,lom,1); String address=addresses.get(0).getAddressLine(0); String city=addresses.get(0).getLocality(); String state=addresses.get(0).getAdminArea(); String country= addresses.get(0).getCountryName(); String postalcode=addresses.get(0).getPostalCode(); String knownName=addresses.get(0).getFeatureName(); editText.setText(""+knownName +"," + address +"," + city + " " + postalcode + "," + state + "" + "," + country ); }catch (IOException e) { e.printStackTrace(); } } else { showSettingsAlert("GPS"); } } }); } public void showSettingsAlert(String provider) { AlertDialog.Builder alertDialog=new AlertDialog.Builder(MainActivityGps.this); alertDialog.setTitle(provider + "SETTINGS"); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); MainActivityGps.this.startActivity(intent); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package it.geosolutions.fra2015.server.dao.impl; import it.geosolutions.fra2015.server.dao.SurveyDAO; import it.geosolutions.fra2015.server.model.survey.SurveyInstance; import java.util.Arrays; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.googlecode.genericdao.search.ISearch; import com.googlecode.genericdao.search.Search; import com.googlecode.genericdao.search.Sort; /** * @author marco * @author Tobia Di Pisa at tobia.dipisa@geo-solutions.it * */ @Transactional(value = "fra2015TransactionManager") public class SurveyDAOImpl extends BaseDAO<SurveyInstance, Long> implements SurveyDAO { /* (non-Javadoc) * @see com.googlecode.genericdao.dao.jpa.GenericDAOImpl#search(com.googlecode.genericdao.search.ISearch) */ @Override public List<SurveyInstance> search(ISearch search) { return super.search(search); } /* (non-Javadoc) * @see com.googlecode.genericdao.dao.jpa.GenericDAOImpl#persist(T[]) */ @Override public void persist(SurveyInstance... entities) { super.persist(entities); } /* (non-Javadoc) * @see com.googlecode.genericdao.dao.jpa.GenericDAOImpl#merge(java.lang.Object) */ @Override public SurveyInstance merge(SurveyInstance entity) { return super.merge(entity); } /* (non-Javadoc) * @see com.googlecode.genericdao.dao.jpa.GenericDAOImpl#remove(java.lang.Object) */ @Override public boolean remove(SurveyInstance entity) { return super.remove(entity); } /* (non-Javadoc) * @see com.googlecode.genericdao.dao.jpa.GenericDAOImpl#removeById(java.io.Serializable) */ @Override public boolean removeById(Long id) { return super.removeById(id); } /* (non-Javadoc) * @see it.geosolutions.fra2015.server.dao.SurveyDAO#findByCountry(java.lang.String) */ @Override public SurveyInstance findByCountry(String country) { Search searchCriteria = new Search(SurveyInstance.class); searchCriteria.addFilterEqual("country.iso3", country); List<SurveyInstance> entries = this.search(searchCriteria); if ( entries.size() > 0){ return entries.get(0); } return null; } /* (non-Javadoc) * @see it.geosolutions.fra2015.server.dao.SurveyDAO#findByCountries(java.lang.String[], int, int, java.lang.String) */ @Override public List<SurveyInstance> findByCountries(String[] countries, int page, int entries, String orderBy){ Search searchCriteria = new Search(SurveyInstance.class); if(orderBy != null && !orderBy.isEmpty()){ searchCriteria.addSort(Sort.asc("country." + orderBy)); }else{ searchCriteria.addSort(Sort.asc("country.iso3")); } searchCriteria.setMaxResults(entries); searchCriteria.setPage(page); searchCriteria.addFilterIn("country.iso3", Arrays.asList(countries)); return this.search(searchCriteria); } /* (non-Javadoc) * @see it.geosolutions.fra2015.server.dao.SurveyDAO#findByCountriesTimestamp(java.lang.String[], int, int, java.lang.String) */ @Override public List<SurveyInstance> getSurveysByCountrySortTimestamp(String[] countries, int page, int entries, String orderBy, String sortType) { Search searchCriteria = new Search(SurveyInstance.class); if(orderBy != null && !orderBy.isEmpty() && sortType != null && !sortType.isEmpty()){ if(sortType.equalsIgnoreCase("asc")){ searchCriteria.addSort(Sort.asc("status." + orderBy)); }else{ searchCriteria.addSort(Sort.desc("status." + orderBy)); } }else{ searchCriteria.addSort(Sort.asc("status.lastSurveyReview")); } searchCriteria.setMaxResults(entries); searchCriteria.setPage(page); searchCriteria.addFilterIn("country.iso3", Arrays.asList(countries)); return this.search(searchCriteria); } }
package com.jack.apiest.source; import com.jack.apiest.beans.SensorReading; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.source.SourceFunction; import java.util.HashMap; import java.util.Random; public class sourceTest3_udf { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<SensorReading> dataStream = env.addSource(new MySensorSource()); dataStream.print(); env.execute(); } // 实现自定义数据 public static class MySensorSource implements SourceFunction<SensorReading> { private boolean Running = true; @Override public void run(SourceContext<SensorReading> ctx) throws Exception { // 定义一个随机数发生器 Random random = new Random(); // 设置10个传感器的初始温服 HashMap<String,Double> sensorTempMap = new HashMap<>(); for(int i = 0;i<10;i++){ sensorTempMap.put("sensor_"+(i+1),60+random.nextGaussian()*20); } while (Running){ for(String sensorId:sensorTempMap.keySet()){ Double nexTemp = sensorTempMap.get(sensorId)+random.nextGaussian()*0.5; sensorTempMap.put(sensorId, nexTemp); ctx.collect(new SensorReading(sensorId, System.currentTimeMillis(), nexTemp)); } // 控制台输出等待1S Thread.sleep(500L); } } @Override public void cancel() { Running = false; } } }
package com.ibiscus.myster.service.data; import com.ibiscus.myster.model.company.Country; import com.ibiscus.myster.model.company.State; import com.ibiscus.myster.repository.data.CountryRepository; import com.ibiscus.myster.repository.data.StateRepository; public class ReferenceDataService { private final CountryRepository countryRepository; private final StateRepository stateRepository; public ReferenceDataService(CountryRepository countryRepository, StateRepository stateRepository) { this.countryRepository = countryRepository; this.stateRepository = stateRepository; } public Iterable<Country> getCountries() { return countryRepository.findAll(); } public Iterable<State> getStatesByCountry(Long countryId) { return stateRepository.findByCountryId(countryId); } }
import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * This class holds the VIEW of "class home" for a class, which can also be called the * "summary view" of the class. You can see each category for the class -- categories can be * homework, exams, projects, etc. -- and each student's average grade in each category. * * The CONTENT of the view is created in the ClassHomeTablePanel class. */ public class ClassHome { private JFrame frame; public ClassHome() { // create JFrame frame = new JFrame("Class Home"); // add the navigation buttons to the frame frame.getContentPane().add(new NavigationButtonBanner(frame), BorderLayout.NORTH); // add table JPanel tablePanel = new ClassHomeTablePanel(frame); frame.getContentPane().add(tablePanel); // make the JFrame visible JScrollPane scroll = new JScrollPane(tablePanel); scroll.setColumnHeaderView(((ClassHomeTablePanel) tablePanel).getHeaderPanel()); // freeze the header row so you can see it as you scroll frame.getContentPane().add(scroll); // this line adds the table to the frame (you do not need a separate panel) frame.setSize(800, 400); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // make the JFrame appear in the middle of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2); } }
package cn.rongcloud.im.utils; import android.content.SharedPreferences; /** * Created by nakisaRen * on 16/9/8. */ public class SPUtils { private static SharedPreferences mSp; public static void init(SharedPreferences sharedPreferences) { mSp = sharedPreferences; } public static void updateOrSave(String key, String json) { mSp.edit().putString(key, json).apply(); } public static void updateOrSave(String key, boolean flag) { mSp.edit().putBoolean(key, flag).apply(); } public static boolean findBoolean(String key) { return mSp.getBoolean(key, true); } public static void updateOrSaveInt(String key, int json) { mSp.edit().putInt(key,json).apply(); } public static String find(String key) { return mSp.getString(key, "zh"); } public static int findInt(String key) { return mSp.getInt(key, 0); } public static void delete(String key) { mSp.edit().remove(key).apply(); } public static void clearAll() { mSp.edit().clear().apply(); } }
package com.xuecheng.manage_media.service.impl; import com.xuecheng.framework.domain.media.MediaFile; import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest; import com.xuecheng.framework.model.response.CommonCode; import com.xuecheng.framework.model.response.QueryResponseResult; import com.xuecheng.framework.model.response.QueryResult; import com.xuecheng.manage_media.dao.MediaFileRepository; import com.xuecheng.manage_media.service.IMediaFileService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import java.util.List; @Slf4j @Service public class MediaFileService implements IMediaFileService { @Autowired private MediaFileRepository mediaFileRepository; /** * 查询媒资列表 * * @param page 当前页 * @param size 每页大小 * @param queryMediaFileRequest 查询条件 * @return */ @Override public QueryResponseResult<MediaFile> findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) { if (page <= 0) { page = 1; } if (size <= 0) { size = 10; } if (queryMediaFileRequest == null) { queryMediaFileRequest = new QueryMediaFileRequest(); } MediaFile mediaFile = new MediaFile(); //查询条件对象 if (StringUtils.isNotBlank(queryMediaFileRequest.getFileOriginalName())) { //查询条件 mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName()); } if (StringUtils.isNotBlank(queryMediaFileRequest.getProcessStatus())) { //查询条件 mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus()); } //查询条件匹配器 ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains()) .withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains()); //定义example对象 Example<MediaFile> example = Example.of(mediaFile, exampleMatcher); //定义分页对象 PageRequest pageRequest = PageRequest.of(page-1, size); //执行查询 Page<MediaFile> all = mediaFileRepository.findAll(example, pageRequest); //总记录数 long totalElements = all.getTotalElements(); //总页数 int totalPages = all.getTotalPages(); //查询内容 List<MediaFile> content = all.getContent(); QueryResult<MediaFile> queryResult = new QueryResult<>(); queryResult.setTotal(totalElements); queryResult.setTotalPage(totalPages); queryResult.setList(content); return new QueryResponseResult<>(CommonCode.SUCCESS,queryResult); } }
package io.swagger.service; import org.threeten.bp.OffsetDateTime; import java.util.List; import io.swagger.model.Graphic; public interface GraphicService { public boolean check(Graphic graphic); public Long add(Graphic graphic); public boolean update(Graphic graphic); public Graphic getById(Long id); public boolean deleteById(Long id); public List<Graphic> findByMagnitude(Long magnitude); public Graphic generate(Long magnitude, OffsetDateTime startDate, OffsetDateTime endDate); public byte[] generatePdf(Long id); public byte[] generatePng(Long id); public boolean sendEmail(Long id); }
package com.mj147.tictactoeai.service; import com.mj147.tictactoeai.domain.Board; import com.mj147.tictactoeai.domain.Player; import com.mj147.tictactoeai.domain.Square; public interface PlayerService { Player createPlayer(int squareValue); Player whoseTurn(Square square); Square makeRandomMove(Board board); Square makeMove(Board board, Player player); void updateFactors(Player player, Integer checkIfWon); }
package com.srikanth.functional.Functions; import java.util.function.Function; public class B_LambdaExpression { public static void main(String[] args) { // Define a lambda function as Function<Integer, Integer> doubleUp = (Integer x) -> { // Taking integer return x * 2; // returning integer }; // Can be written as doubleUp = x -> x * 2; System.out.println(doubleUp.apply(3)); } }
package com.cxjd.nvwabao.fragment.findFunctions.OneHundred; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.TextView; import com.cxjd.nvwabao.R; /** * 100种病症不宜食物 -- R */ public class Rr extends Fragment { //网格布局 GridLayout gridLayout1; GridLayout gridLayout2; GridLayout gridLayout3; GridLayout gridLayout4; GridLayout gridLayout5; //定义网格中的数据 String[] r1 = new String[]{ "动物油","动物内脏","肥肉","油炸食品","精细的主食","咸菜","威蛋","咸酱","糖果","巧克力","蜜饯","果脯","辣椒","芥末" }; String[] r2 = new String[]{ "盐","咸鱼","咸菜"," 红薯"," 洋葱","糯米" }; String[] r3 = new String[]{ "羊肉","辣椒","胡椒","葱","烈酒","生鸡蛋","肥肉","咖喱","芥末","榴莲","臭豆腐" }; String[] r4 = new String[]{ "咖啡","油炸食品","肥肉","冷饮","巧克力","浓茶","辣椒","香肠","动物油","辛辣调料" }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one_hundred_r,container,false); //寻找gridLayout布局 gridLayout1 = view.findViewById(R.id.onehundred_r_1); gridLayout2 = view.findViewById(R.id.onehundred_r_2); gridLayout3 = view.findViewById(R.id.onehundred_r_3); gridLayout4 = view.findViewById(R.id.onehundred_r_4); //调用网格初始化方法 initGridLayout(gridLayout1,r1); initGridLayout(gridLayout2,r2); initGridLayout(gridLayout3,r3); initGridLayout(gridLayout4,r4); return view; } /** * 为网格布局初始化 * @param gridLayout 网格布局 * @param strings 网格中的数据 */ private void initGridLayout(GridLayout gridLayout,String[] strings) { //为网格赋值 for(int i=0; i< strings.length; i++){ TextView textView = new TextView(this.getContext()); textView.setText(strings[i]); //设置字体大小 textView.setTextSize(15); textView.setBackground(getResources().getDrawable(R.drawable.one_hundred_gridlayout_backgroud)); //居中显示 textView.setGravity(Gravity.CENTER); //指定该组件所在的行 GridLayout.Spec rowSpec = GridLayout.spec(i / 4); //指定该组件所在的列 GridLayout.Spec columnSpec = GridLayout.spec(i % 4); GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec,columnSpec); //指定该组件占满父组件 params.setGravity(Gravity.FILL); gridLayout.addView(textView,params); } } }
package pubsub; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * @date 2019/9/26 20:57 * @author: <a href=mailto:xuzj@bonree.com>胥智钧</a> * @Description: **/ public class Test { public static void main(String[] args) { JedisPool pool = new JedisPool(new JedisPoolConfig(), "192.168.1.154", 6379, 3000); Jedis jedis = pool.getResource(); jedis.psubscribe(new KeyExpiredListener(), "__keyevent@*__:expired"); JedisCluster jedisPool; pool.close(); } }
package com.cibertec.repositorio; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.cibertec.entidad.Pedido; public interface PedidoRepositorio extends JpaRepository<Pedido, Integer>{ @Query("Select a from Pedido a where idCliente = 9 and estado like :fil") public abstract List<Pedido> listaPedidoPorEstadoLike(@Param("fil") String filtro); }
package com.per.iroha.netty; import com.alibaba.fastjson.JSON; import com.per.iroha.model.User; import com.per.iroha.model.WebSocketMessage; import com.per.iroha.redis.RedisMq; import com.per.iroha.service.MessageService; import com.per.iroha.service.impl.MessageServiceImpl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.handler.codec.http.websocketx.*; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import java.util.Set; @Controller public class WebSocketHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private MessageService messageService = new MessageServiceImpl(); private RedisMq redisMq = new RedisMq(); private WebSocketServerHandshaker handshaker; private User user; private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception { //WebSocket在一次TCP协议握手的基础上实现的 handHttpRequest(channelHandlerContext,request); //异步把用户信息写入缓存 channelHandlerContext.channel().eventLoop().execute(new Runnable() { @Override public void run() { String userJ = redisMq.pop(); user = JSON.parseObject(userJ,User.class); if(user != null){ messageService.bindSession(user,channelHandlerContext.channel()); }else{ Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(request.headers().toString()); for(Cookie cookie : cookies){ if(cookie.name().equals("userId")){ user = messageService.getCookie(cookie.value()); break; } } messageService.bindSession(user,channelHandlerContext.channel()); } WebSocketMessage CountMessage = new WebSocketMessage(); CountMessage.setErr(1); CountMessage.setMessage("本月签到次数:" + messageService.getCheckCount(messageService.getSession(channelHandlerContext.channel()).getUserId())); channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(CountMessage))); } }); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { //当channel连接打开时,加入到总ChannelGroup中 NettyConfig.globalChannels.add(ctx.channel()); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { //断开连接时清除用户Session messageService.unbindSession(ctx.channel()); super.channelInactive(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if(evt instanceof IdleStateEvent){ IdleState state = ((IdleStateEvent) evt).state(); if (state == IdleState.READER_IDLE) { logger.info("在规定时间内没有收到客户端的上行数据, 主动断开连接" ); WebSocketMessage CountMessage = new WebSocketMessage(); CountMessage.setErr(1); CountMessage.setMessage("长时间未进行操作已与服务器断开连接,请刷新~"); ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(CountMessage))); ctx.channel().close(); } }else{ super.userEventTriggered(ctx, evt); } } // 处理 http 请求,WebSocket 初始握手 (opening handshake ) 都始于一个 HTTP 请求 private void handHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request){ if(!request.decoderResult().isSuccess() || !("websocket".equals(request.headers().get("Upgrade")))){ sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); return; } WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory("ws://" + NettyConfig.NETTY_HOST + NettyConfig.NETTY_PORT, null, false); handshaker = factory.newHandshaker(request); if(handshaker == null){ WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), request); } } // 响应非 WebSocket 初始握手请求 private void sendHttpResponse(ChannelHandlerContext ctx, DefaultFullHttpResponse res) { if(res.status().code() != 200){ ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); } ChannelFuture f = ctx.channel().writeAndFlush(res); if(res.status().code() != 200){ f.addListener(ChannelFutureListener.CLOSE); } } }
package task163; /** * @author Igor */ public class Main163 { }
package com.smxknife.proxy.cglib; /** * @author smxknife * 2021/6/22 */ public class CglibMain { public static void main(String[] args) { final HelloService helloService = new HelloServiceMethodInterceptor().getInstance(HelloService.class); helloService.sayHello("你好"); System.out.println(helloService.getWord()); } }
package com.jim.multipos.data.operations; import com.jim.multipos.data.db.model.intosystem.OutcomeWithDetials; import com.jim.multipos.data.db.model.intosystem.StockQueueItem; import com.jim.multipos.data.db.model.inventory.IncomeProduct; import com.jim.multipos.data.db.model.inventory.OutcomeProduct; import com.jim.multipos.data.db.model.inventory.StockQueue; import com.jim.multipos.data.db.model.order.Order; import com.jim.multipos.data.db.model.order.OrderProduct; import com.jim.multipos.ui.inventory.model.InventoryItem; import com.jim.multipos.ui.reports.stock_operations.model.OperationSummaryItem; import com.jim.multipos.ui.reports.stock_state.module.InventoryItemReport; import com.jim.multipos.ui.vendor_products_view.model.ProductState; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import io.reactivex.Single; /** * Created by bakhrom on 10/23/17. */ public interface InventoryOperations { // Single<List<InventoryItem>> getInventoryItems(); // Observable<Long> insertInventoryState(InventoryState inventoryState); // Observable<List<InventoryState>> getInventoryStates(); // Single<Boolean> deleteInventoryState(InventoryState inventoryState); // Observable<List<InventoryState>> getInventoryStatesByProductId(Long productId); // Observable<List<InventoryState>> getInventoryStatesByVendorId(Long vendorId); // Single<Long> insertWarehouseOperation(WarehouseOperations warehouseOperations); // Single<WarehouseOperations> getWarehouseOperationById(Long warehouseId); // Single<Long> replaceWarehouseOperation(WarehouseOperations warehouseOperations); // Single<HistoryInventoryState> insertHistoryInventoryState(HistoryInventoryState state); // Single<List<WarehouseOperations>> getWarehouseOperationsInInterval(Calendar fromDate, Calendar toDate); // Single<List<HistoryInventoryState>> getHistoryInventoryStatesByTillId(Long id); Integer checkProductAvailable(Long productId, double summaryCount, Order ifHaveOldOrder); //+ List<OutcomeProduct> insertAndFillOutcomeProducts(List<OutcomeWithDetials> outcomeWithDetials); //+ OutcomeProduct insertAndFillOutcomeProduct(OutcomeWithDetials outcomeWithDetials); //+ Single<List<ProductState>> getVendorProductsWithStates(Long vendorId); //ORDER EDIT QILINGANI TASDIQLANSA ESKI ORDERNI OUTCOMELARI OTMENA BO'LISHI KERAK Single<Integer> cancelOutcomeProductWhenOrderProductCanceled(List<OrderProduct> orderProducts); //+ Single<List<OutcomeWithDetials>> checkPositionAvailablity(List<OutcomeProduct> outcomeProducts); //+ Single<List<OutcomeWithDetials>> checkPositionAvailablityWithoutSomeOutcomes(List<OutcomeProduct> outcomeProducts, List<OutcomeProduct> withoutOutcomeProducts); //+ Single<OutcomeWithDetials> checkPositionAvailablity(OutcomeProduct outcomeProduct); Single<IncomeProduct> insertIncomeProduct(IncomeProduct incomeProduct); Single<StockQueue> insertStockQueue(StockQueue stockQueue); Single<Double> getProductInvenotry(Long productId); //+ Single<List<InventoryItem>> getProductInventoryStatesForNow(); Single<List<InventoryItemReport>> getInventoryWithSummaryCost(); Single<List<InventoryItemReport>> getInventoryVendorWithSummaryCost(); Single<InventoryItem> setLowStockAlert(InventoryItem inventoryItem, double newAlertCount); Single<List<StockQueue>> getStockQueuesByProductId(Long id); Single<List<StockQueue>> getAllStockQueuesByProductId(Long productId); Single<Double> getAvailableCountForProduct(Long id); Single<List<StockQueueItem>> getStockQueueItemForOutcomeProduct(OutcomeProduct outcomeProduct, List<OutcomeProduct> outcomeProductList, List<OutcomeProduct> exceptionList); Single<List<StockQueue>> getAllStockQueuesByVendorId(Long vendorId); Single<List<StockQueue>> getAllStockQueuesByProductIdInInterval(Long productId, Calendar fromDate, Calendar toDate); Single<List<StockQueue>> getAllStockQueuesByVendorIdInInterval(Long vendorId, Calendar fromDate, Calendar toDate); Single<List<StockQueue>> getExpiredStockQueue(); Single<List<OutcomeProduct>> updateOutcomeProduct(List<OutcomeProduct> outcomeProducts); Single<List<OperationSummaryItem>> getOperationsSummary(Date fromDate, Date toDate); Single<List<OutcomeProduct>> getOutcomeProductsForPeriod(Calendar fromDate, Calendar toDate); Single<List<IncomeProduct>> getIncomeProductsForPeriod(Calendar fromDate, Calendar toDate); Single<List<StockQueue>> getStockQueueForPeriod(Calendar fromDate, Calendar toDate); Single<List<StockQueue>> getStockQueueUsedForPeriod(Calendar fromDate, Calendar toDate); Single<StockQueue> getStockQueueById(Long stockQueueId); }
package cdn.discovery; import cdn.shared.GlobalLogger; /** * Parses the arguments and does some sanity checks on them. * * @author myles * */ public class DiscoveryArgumentParser { private final String[] args; private int portNum; private int refreshInterval; public DiscoveryArgumentParser(String[] args) { this.args = args; } /** * Determins if passed in arguments are valid for the Discovery Node. * * @return true if valid, false otherwise. */ public boolean isValid() { boolean isValid = true; // Do some sanity checks on the arguments int portNum = getPositiveNumber(args[0]); if (portNum < 0) { GlobalLogger.severe(this, "Invalid port number."); return false; } else if (portNum <= 1024) { GlobalLogger.warning(this, "You are running in the restricted port range, this is not recommended."); } this.portNum = portNum; if (args.length > 1) { int refreshInterval = getPositiveNumber(args[1]); if (refreshInterval < 0) { GlobalLogger.warning(this, "Invalid refresh interval."); return false; } this.refreshInterval = refreshInterval; } else { refreshInterval = 120; } return isValid; } public int getRefreshInterval() { return refreshInterval; } public int getPortNum() { return portNum; } /** * Utility method for getting a positive int from a String. * * @param num the string to parse. * @return a negative integer on invalid string, or the parsed positive int. */ private int getPositiveNumber(String num) { int portNum = -1; try { portNum = Integer.parseInt(num); if (portNum < 0) { GlobalLogger.warning(this, "Number must be a positive number"); } } catch (NumberFormatException e) { GlobalLogger.warning(this, "Argument must be a valid integer."); } return portNum; } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.theelm.sewingmachine.base.mixins.Server; import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; import net.theelm.sewingmachine.interfaces.WhitelistedPlayer; import net.theelm.sewingmachine.base.mixins.Interfaces.WhitelistAccessor; import net.minecraft.server.ServerConfigEntry; import net.minecraft.server.WhitelistEntry; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.UUID; @Mixin(WhitelistEntry.class) public abstract class WhitelistEntryMixin extends ServerConfigEntry<GameProfile> implements WhitelistedPlayer, WhitelistAccessor<GameProfile> { //private UUID id; private UUID invitedBy = null; public WhitelistEntryMixin(GameProfile object) { super(object); } @Inject(at = @At("RETURN"), method = "<init>(Lcom/google/gson/JsonObject;)V") public void onInitialize(JsonObject json, CallbackInfo callback) { if (json.has("invitedBy")) this.invitedBy = UUID.fromString(json.get("invitedBy").getAsString()); } @Inject(at = @At("TAIL"), method = "write") public void onSerialize(JsonObject json, CallbackInfo callback) { if (invitedBy != null) json.addProperty("invitedBy",this.invitedBy.toString()); } @Override public void setInvitedBy(UUID uuid) { this.invitedBy = uuid; } @Override public @Nullable String getName() { GameProfile profile = this.getObject(); if (profile == null) return null; return profile.getName(); } @Override public @Nullable UUID getUUID() { GameProfile profile = this.getObject(); if (profile == null) return null; return profile.getId(); } @Override public @Nullable UUID getInvitedBy() { return this.invitedBy; } }
package net.jselby.pc.accounts; /** * A users profile. * * @author j_selby */ public class GameProfile { private String accessToken; private String clientToken; private String username; private String password; private String name; private String uuid; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getClientToken() { return clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public GameProfile clone() { GameProfile profile = new GameProfile(); profile.setClientToken(getClientToken()); profile.setAccessToken(getAccessToken()); profile.setUsername(getUsername()); profile.setPassword(getPassword()); return profile; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
package pm.server.test; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class IntegrationTestConfiguration { @Bean public IntegrationTestStaticData integrationTestStaticData() { return new IntegrationTestStaticData(); } }
package com.xrigau.droidcon.espresso.presentation; import android.test.ActivityInstrumentationTestCase2; import com.xrigau.droidcon.espresso.R; import com.xrigau.droidcon.core.model.Post; import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData; import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView; import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches; import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.*; import static com.xrigau.droidcon.espresso.helper.EspressoTestsMatchers.isEmpty; import static com.xrigau.droidcon.espresso.helper.EspressoTestsMatchers.withChildCount; import static org.hamcrest.Matchers.*; public class PostListActivityTest extends ActivityInstrumentationTestCase2<PostListActivity> { private static final int FIRST = 0; public PostListActivityTest() { super(PostListActivity.class); } public void setUp() throws Exception { super.setUp(); getActivity(); } public void testDisplayPosts() { onData(is(instanceOf(Post.class))).atPosition(0).check(matches(isDisplayed())); onView(withId(R.id.list)).check(matches(withChildCount(is(greaterThan(0))))); // Because the previous instruction makes sure we have data } public void testPostIsDisplayedProperly() { onData(is(instanceOf(Post.class))) .atPosition(FIRST).onChildView(withId(R.id.title)) .check(matches(allOf(isDisplayed(), withText(not(isEmpty()))))); onData(is(instanceOf(Post.class))) .atPosition(FIRST).onChildView(withId(R.id.domain)) .check(matches(allOf(isDisplayed(), withText(not(isEmpty()))))); // Remove this if using real data onData(is(instanceOf(Post.class))) .atPosition(FIRST).onChildView(withId(R.id.time)) .check(matches(allOf(isDisplayed(), withText(not(isEmpty()))))); onData(is(instanceOf(Post.class))) .atPosition(FIRST).onChildView(withId(R.id.comments)) .check(matches(allOf(isDisplayed(), withText(not(isEmpty()))))); // Remove this if using real data onView(withId(R.id.loading)).check(matches(not(isDisplayed()))); } public void testMockItemShowsCorrectData() { // Ignore test if using real data Post post = new Post.Builder() .id("6826660") .title("Why are there so many tunnels under London?") .domain("economist.com") .postedTime("2 hours ago") .commentCount(28) .build(); onData(allOf(is(instanceOf(Post.class)), is(post))) .onChildView(withId(R.id.title)) .check(matches(withText(post.getTitle()))); onData(allOf(is(instanceOf(Post.class)), is(post))) .onChildView(withId(R.id.domain)) .check(matches(withText(post.getDomain()))); onData(allOf(is(instanceOf(Post.class)), is(post))) .onChildView(withId(R.id.time)) .check(matches(withText(post.getTime()))); onData(allOf(is(instanceOf(Post.class)), is(post))) .onChildView(withId(R.id.comments)) .check(matches(withText(containsString(Integer.toString(post.getCommentCount()))))); } }
public class HelloHooli { public static void main(String[] args) { System.out.println("Hello Hooli, Your Git repo is set"); } }
package task41; import common.Utils; /** * @author Igor */ public class Main41 { public static void main(String[] args) { System.out.println(solve(7, 0, 0, new int[7])); } static int solve(int max, int used, int n, int[] numbers) { if (n == max) { int x = 1, candidate = 0; for (int i = 1; i <= max; i++) { candidate += numbers[max - i] * x; x *= 10; } return Utils.isPrime(candidate) ? candidate : -1; } for (int i = 0; i < max; i++) { if ((used & (1 << i)) == 0) { numbers[n] = max - i; int result = solve(max, used | (1 << i), n + 1, numbers); if (result != -1) return result; } } return -1; } }
package sellwin.server; import java.sql.*; import java.rmi.*; import java.util.*; import javax.ejb.*; import javax.sql.*; import javax.naming.*; import sellwin.domain.*; // SellWin http://sourceforge.net/projects/sellwincrm //Contact support@open-app.com for commercial help with SellWin //This software is provided "AS IS", without a warranty of any kind. /** * this class is a stateful session bean that delegates client * calls to the BizServices class which actually implements the * business services we are providing to the outside world (clients) * when they are configured to communicate via EJB technology */ public class SellwinSessionBean extends BizServices implements SessionBean { private SessionContext ctx; private Context environment; private DataSource ds; //some state public SellwinSessionBean() { super(); } /** * set the session context * * @param ctx SessionContext for session */ public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } /** * this method is required by the EJB SessionBean interface * and does nothing special for this implementation */ public void ejbActivate() { System.out.println("ejbActivate called"); } /** * this method is required by the EJB SessionBean interface * and does nothing special for this implementation */ public void ejbPassivate() { System.out.println("ejbPassivate called"); } /** * this method is required by the EJB SessionBean interface * and does nothing special for this implementation */ public void ejbRemove() { System.out.println("ejbRemove called"); } /** * this method corresponds to the create method in the * SellwinSessionHome interface. When the client calls * SellwinSessionHome.create(), the container allocates an * instance of the session bean and calls this method, ejbCreate() * * @exception javax.ejb.CreateException * if there is a problem creating the bean */ public void ejbCreate() throws CreateException { try { InitialContext ic = new InitialContext(); System.out.println("got the initial context"); System.out.println("about to get datasource"); //weblogic uses the next JNDI name for the lookup //ds = (DataSource)ic.lookup("sellwinPool"); //jboss uses the next JNDI name for the lookup //ds = (DataSource)ic.lookup("java:/OracleDB"); ds = (DataSource)ic.lookup("java:/SellwinDS"); System.out.println("got handle to jdbc data source"); } catch (NamingException e) { e.printStackTrace(); throw new CreateException("could not find initial context"); } } /** * get the weblogic initial context used for * jndi lookups (i.e. jdbc datasource) * @return the InitialContext */ public javax.naming.InitialContext getContext() throws javax.naming.NamingException { Hashtable ht = new Hashtable(); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactor"); ht.put(Context.PROVIDER_URL, "t3://localhost:7001"); javax.naming.InitialContext ctx = new InitialContext(ht); return ctx; } /** * get the datasource used to get jdbc connections * by doing a jndi lookup via the EJB container's * context * @param ctx the InitialContext to do the lookup with * @return the DataSource found */ public javax.sql.DataSource getDataSource(InitialContext ctx) throws javax.naming.NamingException { javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("sellwinPool"); return ds; } /** * @see sellwin.server.BizServices updateLead method */ public void updateLead(long campPK, Lead l) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); leadDB.setConnection(con); super.updateLead(campPK, l); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getOpportunityIndex method */ public ArrayList getOpportunityIndex(SalesPerson u) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); return super.getOpportunityIndex(u); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getProductMatrix method */ public ArrayList getProductMatrix() throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); productDB.setConnection(con); return super.getProductMatrix(); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getProductsForLine method */ public ArrayList getProductsForLine(String group, String line) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); productDB.setConnection(con); return super.getProductsForLine(group, line); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getProduct method */ public Product getProduct(String group, String line, String name) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); productDB.setConnection(con); return super.getProduct(group, line, name); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addForecast method */ public long addForecast(long opportunityPK, Forecast forecast) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); forecastDB.setConnection(con); return super.addForecast(opportunityPK, forecast); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateForecast method */ public void updateForecast(long oppPK, Forecast forecast) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); forecastDB.setConnection(con); super.updateForecast(oppPK, forecast); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteForecast method */ public void deleteForecast(long oppPK, long forecastPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); forecastDB.setConnection(con); super.deleteForecast(oppPK, forecastPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addOrder method */ public long addOrder(long oppPK, Order order) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); orderDB.setConnection(con); return super.addOrder(oppPK, order); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateOrder method */ public void updateOrder(long oppPK, Order order) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); orderDB.setConnection(con); super.updateOrder(oppPK, order); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addQuote method */ public long addQuote(long oppPK, Quote quote) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); quoteDB.setConnection(con); return super.addQuote(oppPK, quote); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateQuote method */ public void updateQuote(long oppPK, Quote quote) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); quoteDB.setConnection(con); super.updateQuote(oppPK, quote); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteQuote method */ public void deleteQuote(long oppPK, long quotePK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); quoteDB.setConnection(con); super.deleteQuote(oppPK, quotePK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addQuoteLine method */ public long addQuoteLine(long oppPK, long quotePK, QuoteLine quoteLine) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); quoteLineDB.setConnection(con); return super.addQuoteLine(oppPK, quotePK, quoteLine); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteQuoteLine method */ public void deleteQuoteLine(long oppPK, long quotePK, long quoteLinePK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); quoteLineDB.setConnection(con); super.deleteQuoteLine(oppPK, quotePK, quoteLinePK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getAlarms method */ public ArrayList getAlarms(long salesPersonPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); activityDB.setConnection(con); return super.getAlarms(salesPersonPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addActivity method */ public long addActivity(long opportunityPK, Activity activity) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); activityDB.setConnection(con); return super.addActivity(opportunityPK, activity); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateActivity method */ public void updateActivity(long opportunityPK, Activity activity) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); activityDB.setConnection(con); super.updateActivity(opportunityPK, activity); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteActivity method */ public void deleteActivity(long opportunityPK, long activityPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); activityDB.setConnection(con); super.deleteActivity(opportunityPK, activityPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getAllUserRoles method */ public ArrayList getAllUserRoles(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userRoleDB.setConnection(con); return super.getAllUserRoles(lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addUserRole method */ public void addUserRole(UserRole userRole) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userRoleDB.setConnection(con); super.addUserRole(userRole); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteUserRole method */ public void deleteUserRole(long pk) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userRoleDB.setConnection(con); super.deleteUserRole(pk); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateUserRole method */ public void updateUserRole(UserRole userRole) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userRoleDB.setConnection(con); super.updateUserRole(userRole); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getUserRole method */ public UserRole getUserRole(String userRoleName) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userRoleDB.setConnection(con); return super.getUserRole(userRoleName); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices logon method */ public Login logon(String id, String psw) throws RemoteException, AngError { Connection con=null; try { System.out.println("logon called id=" + id + " psw=" + psw); con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); return super.logon(id, psw); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { if (con != null) con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteCustomer method */ public void deleteCustomer(String customerName) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); customerDB.setConnection(con); super.deleteCustomer(customerName); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteCustomer method */ public void updateCustomer(Customer customer) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); customerDB.setConnection(con); super.updateCustomer(customer); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addCustomer method */ public long addCustomer(Customer customer) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); customerDB.setConnection(con); return super.addCustomer(customer); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getCustomer method */ public Customer getCustomer(String customerName) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); customerDB.setConnection(con); return super.getCustomer(customerName); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getAllCustomerNames method */ public Object[] getAllCustomerNames() throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); customerDB.setConnection(con); return super.getAllCustomerNames(); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getCustomers method */ public ArrayList getCustomers(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); customerDB.setConnection(con); return super.getCustomers(lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getStateTax method */ public ArrayList getStateTax(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); stateTaxDB.setConnection(con); return super.getStateTax(lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addProduct method */ public void addProduct(Product product) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); productDB.setConnection(con); super.addProduct(product); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getProducts method */ public ArrayList getProducts(java.util.Date afterDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); productDB.setConnection(con); return super.getProducts(afterDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getOpportunityNames method */ public ArrayList getOpportunityNames(SalesPerson salesPerson) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); return super.getOpportunityNames(salesPerson); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getOpportunities method */ public ArrayList getOpportunities(SalesPerson salesPerson, java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); return super.getOpportunities(salesPerson, lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getOpportunity method */ public Opportunity getOpportunity(long oppPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); return super.getOpportunity(oppPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteOpportunity method */ public void deleteOpportunity(long oppPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); super.deleteOpportunity(oppPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addOpportunity method */ public long addOpportunity(Opportunity opp) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); return super.addOpportunity(opp); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateOpportunity method */ public void updateOpportunity(Opportunity opp) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); oppDB.setConnection(con); super.updateOpportunity(opp); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteContact method */ public void deleteContact(long oppPK, long contactPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); contactDB.setConnection(con); super.deleteContact(oppPK, contactPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateContact method */ public void updateContact(long oppPK, Contact contact) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); contactDB.setConnection(con); super.updateContact(oppPK, contact); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addContact method */ public long addContact(long oppPK, Contact contact) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); contactDB.setConnection(con); return super.addContact(oppPK, contact); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getSalesPersons method */ public Object[] getSalesPersons(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); return super.getSalesPersons(lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getSalesPerson method */ public SalesPerson getSalesPerson(long pk) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); return super.getSalesPerson(pk); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices updateSalesPerson method */ public void updateSalesPerson(SalesPerson salesPerson) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); super.updateSalesPerson(salesPerson); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteSalesPerson method */ public void deleteSalesPerson(SalesPerson person) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); super.deleteSalesPerson(person); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addSalesPerson method */ public long addSalesPerson(SalesPerson salesPerson) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); return super.addSalesPerson(salesPerson); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getSalesPersonIDs method */ public ArrayList getSalesPersonIDs() throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); return super.getSalesPersonIDs(); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getSalesPersonNames method */ public ArrayList getSalesPersonNames() throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); salesPersonDB.setConnection(con); return super.getSalesPersonNames(); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addUserToGroup method */ public void addUserToGroup(long userPK, UserGroup group) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); ugMemberDB.setConnection(con); super.addUserToGroup(userPK, group); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getUsersInGroup method */ public Object[] getUsersInGroup(String groupName) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userGroupDB.setConnection(con); return super.getUsersInGroup(groupName); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getUserGroup method */ public UserGroup getUserGroup(long pk) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userGroupDB.setConnection(con); return super.getUserGroup(pk); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getUserGroups method */ public Object[] getUserGroups(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userGroupDB.setConnection(con); return super.getUserGroups(lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addUserGroup method */ public void addUserGroup(UserGroup group) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userGroupDB.setConnection(con); super.addUserGroup(group); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteUserGroup method */ public void deleteUserGroup(String groupName) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); userGroupDB.setConnection(con); super.deleteUserGroup(groupName); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteUserInGroup method */ public void deleteUserInGroup(UserGroup group, long userPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); ugMemberDB.setConnection(con); super.deleteUserInGroup(group, userPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getGroupsForUser method */ public ArrayList getGroupsForUser(long userPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); ugMemberDB.setConnection(con); return super.getGroupsForUser(userPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getCampaigns method */ public ArrayList getCampaigns(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); campaignDB.setConnection(con); return super.getCampaigns(lastSyncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getCampaignLeads method */ public ArrayList getCampaignLeads(java.util.Date syncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); leadDB.setConnection(con); return super.getCampaignLeads(syncDate); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getCampaignLeads method */ public ArrayList getCampaignLeads(long campaignPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); leadDB.setConnection(con); return super.getCampaignLeads(campaignPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices uploadDeletes method */ public void uploadDeletes(ArrayList deletes) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); activityDB.setConnection(con); forecastDB.setConnection(con); quoteDB.setConnection(con); quoteLineDB.setConnection(con); contactDB.setConnection(con); oppDB.setConnection(con); super.uploadDeletes(deletes); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices addCustomerInventory method */ public long addCustomerInventory(CustomerInventory ci) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); custInventoryDB.setConnection(con); return super.addCustomerInventory(ci); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices deleteCustomerInventory method */ public void deleteCustomerInventory(CustomerInventory ci) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); custInventoryDB.setConnection(con); super.deleteCustomerInventory(ci); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * @see sellwin.server.BizServices getCustomerInventory method */ public ArrayList getCustomerInventory(long customerPK) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); custInventoryDB.setConnection(con); return super.getCustomerInventory(customerPK); } catch (SQLException s) { throw new AngError(s.getMessage()); } catch (AngError a) { throw a; } catch (RemoteException r) { throw r; } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } /** * get all the UserGroupMembers * @param lastSyncDate a user's last sync date or null, used to * limit the query * @return an ArrayList of UserGroupMember objects */ public final ArrayList getGroupMembers(java.util.Date lastSyncDate) throws RemoteException, AngError { Connection con=null; try { con = ds.getConnection(); con.setAutoCommit(false); ugMemberDB.setConnection(con); return super.getGroupMembers(lastSyncDate); } catch (SQLException e) { e.printStackTrace(); throw new AngError(e.getMessage()); } finally { try { con.close(); } catch (SQLException x) { x.printStackTrace(); } } } }
/* * 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 nuevorobot; /** * * @author miguel */ public class Matriz { //LISTA DE ARGUMENTOS public static String escaneado = "escaneado"; public static String distancia = "distancia"; public static String energiaEnemigo = "energiaEnemigo"; public static String apuntandoAEnemigo = "apuntandoAEnemigo"; public static String golpeoBala = "golpeoBala"; public static String golpeoPared = "golpeoPared"; public static String golpeoEnemigo = "golpeoEnemigo"; public static String energia = "energia"; public static String armaCaliente = "armaCaliente"; public static String X = "X"; public static String Y = "Y"; public static String enMovimiento = "enMovimiento"; public static String armaGirando = "armaGirando"; public static String robotGirando = "robotGirando"; public static String accion = "accion"; //LISTA DE ACCIONES public static final String DISPAROLEVE = "disparoLeve"; public static final String DISPAROMEDIO = "disparoMedio"; public static final String DISPAROFUERTE = "disparoFuerte"; public static final String APUNTAR = "apuntar"; public static final String MOVERARMA = "moverArma"; public static final String MOVER_SE = "moverSE"; public static final String MOVER_NE = "moverNE"; public static final String MOVER_NW = "moverNW"; public static final String MOVER_SW = "moverSW"; public static final String MEDIAVUELTA = "mediaVuelta"; }
package com.example.entity.aircraft; import javax.persistence.*; @Entity @Table(name = "airplane_model") public class AirplaneModel { private Long id; private String code; private String description; private Manufacturer manufacturer; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ManyToOne @JoinColumn(name = "manufacturer_id") public Manufacturer getManufacturer() { return manufacturer; } public void setManufacturer(Manufacturer manufacturer) { this.manufacturer = manufacturer; } }
package app.akexorcist.googlemapsv2; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MenuNGV extends Activity{ Button btndetail; Button btnroute; Button btnnoti1; Button btnnoti2; Button btnNewProduct; Button btnNGV; Button btnlogin; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.menungv); // Buttons btndetail = (Button) findViewById(R.id.btndetail); btnNewProduct = (Button) findViewById(R.id.btnCreateProduct); // btnNewProduct = (Button) findViewById(R.id.btnNGV); btnroute = (Button) findViewById(R.id.btnroute); btnnoti1 = (Button) findViewById(R.id.btnnoti1); btnnoti2 = (Button) findViewById(R.id.btnnoti2); btnNGV = (Button) findViewById(R.id.btnNGV); btnlogin = (Button) findViewById(R.id.btnlogin); // btnlogin = (Button) findViewById(R.id.btndetail); // view products click event Log.e(" Details", Boolean.toString(((MyApplication) this.getApplication()).getstate1()) ); btndetail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //test map Intent i = new Intent(getApplicationContext(), Detail.class); startActivity(i); } }); btnroute.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //test map Intent i = new Intent(getApplicationContext(), Route.class); startActivity(i); } }); btnNewProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //test map Intent i = new Intent(getApplicationContext(), newb.class); startActivity(i); } }); btnNGV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launching NGV location on maps Intent i = new Intent(getApplicationContext(), Getngv.class); startActivity(i); } }); btnnoti1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launching NGV location on maps Intent i = new Intent(getApplicationContext(), Notification1.class); i.putExtra("XX", 1); startActivity(i); } }); btnnoti2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launching NGV location on maps Intent i = new Intent(getApplicationContext(), Notification2.class); i.putExtra("XX", 1); startActivity(i); } }); btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launching login activity Intent i = new Intent(getApplicationContext(), Login.class); startActivity(i); } }); } }
// Title: RecipeStorer // Author: Mark Walker // Date: January 23, 2013 // School: Valencia High School // Computer: Dell with Windows 7 // IDE Used: BlueJ // Purpose: This class facilitates data storage of our needed variables for the Recipe storing program. Each instance of this class represents an individual // recipe during the running of the program. public class Recipe { private String myTitle; // represents the title of the recipe private String[] myIngredients; // represents the ingredients of the recipe private String[] myProcedure; // represents the procedure of the recipe private String oldRecipe; // represents the Recipe prior to any edits public Recipe(String title, String[] ingredients, String[] procedures) // initializes our private variables { myTitle = title; myIngredients = ingredients; myProcedure = procedures; oldRecipe = ""; } public String getTitle() // gives access to the Recipe title { return myTitle; } public String[] getIngredients() // gives access to the Recipe ingredients { return myIngredients; } public String[] getProcedure() // gives access to the Recipe procedures { return myProcedure; } public String getOldRecipe() // allows access to the oldRecipe; if it has not been made yet, an empty String will be returned { return oldRecipe; } public String toString() // used to compile a String to be written to the file, as well as method for representing the Recipe prior to edits { String compiledString = ""; // creating an empty String to add the Recipe parts to compiledString+= "[" + myTitle + "]"; // adds the title of the recipe to our String compiledString+= "["; // prepares the String to have Ingredients added for(int i = 0; i < myIngredients.length; i++) { compiledString+= myIngredients[i] + "|"; // adds the next Ingredient to the String and adds a partition for the next ingredient } compiledString = compiledString.substring(0,compiledString.length()-1); compiledString+= "]["; // closes out our Ingredient adding and preapres the String to have procedures added for (int i = 0; i < myProcedure.length; i++) { compiledString+= myProcedure[i] + "|"; // adds the next Procedure to the String and adds a partition for the next procedure } compiledString = compiledString.substring(0,compiledString.length()-1); compiledString+= "]"; // closes out the final splitting for the Procedures return compiledString; } public void editTitle(String newTitle) // allows editing of the Title { if (oldRecipe.equals("")) oldRecipe = this.toString(); // upon editing, it will be required to have reference to what the recipe was prior to editing; this will // create that copy only if it has not been already made myTitle = newTitle; } public void addIngredient(String newIngredient) // allows adding of an Ingredient { if (oldRecipe.equals("")) oldRecipe = this.toString(); //same reasoning as above String[] newIngredients = new String[myIngredients.length+1]; //creates a new array for the new Ingredient to be copied into for (int i = 0; i < myIngredients.length; i++) { newIngredients[i] = myIngredients[i]; // copying in the old array to the new one } newIngredients[myIngredients.length] = newIngredient; myIngredients = newIngredients; } public void editIngredient(String change, int index) { if (oldRecipe.equals("")) oldRecipe = this.toString(); //same reasoning as above myIngredients[index] = change; //making the desired change } public void addProcedure(String newProc) { if (oldRecipe.equals("")) oldRecipe = this.toString(); //same reasoning as above String[] newProcedure = new String[myProcedure.length + 1]; // creates a new array for the new Procedure to be added into for (int i = 0; i < myProcedure.length; i++) { newProcedure[i] = myProcedure[i]; // copying in the old array to the new one } newProcedure[myProcedure.length] = newProc; myProcedure = newProcedure; } public void editProcedure (String change, int index) { if (oldRecipe.equals("")) oldRecipe = this.toString(); //same reasoning as above myProcedure[index] = change; } }
package ir.nrdc.model.repository; import ir.nrdc.model.entity.Role; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import java.util.List; import java.util.Optional; @org.springframework.stereotype.Repository public interface RoleRepository extends Repository<Role, Integer>, JpaSpecificationExecutor<Integer> { void save(Role role); List<Role> findAll(); @Query("select role.roleName From Role role where not role.roleName ='ADMIN'") List<String> findUserRoles(); Optional<Role> findByRoleName(String roleName); }
package com.quizcore.quizapp.model.network.response.user; import com.quizcore.quizapp.model.other.UserQuizResult; import lombok.Data; import java.util.List; @Data public class UserQuizResponse { List<UserQuizResult> submissions; }
package com.example.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class ReadService { private final Logger logger = LoggerFactory.getLogger("file-logger"); public Object readObjectFromFile(File file) { Object object = null; try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) { object = objectInputStream.readObject(); } catch (IOException | ClassNotFoundException e) { this.logger.error(e.toString()); } return object; } }
package go.nvhieucs.notins.awss3; import com.amazonaws.auth.*; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.PutObjectRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Objects; @Service public class AmazonClient { @Value("${aws.s3.accessKey}") private String accessKey; @Value("${aws.s3.secretKey}") private String secretKey; @Value("${aws.s3.endpointUrl}") private String endpointUrl; @Value("${aws.s3.bucketName}") private String bucketName; @Value("${aws.s3.region}") private String region; private AmazonS3 s3Client; @PostConstruct private void initializeAmazon() { AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); s3Client = AmazonS3Client.builder() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpointUrl, region)) .withPathStyleAccessEnabled(true) .build(); } private File convertMultiPartToFile(MultipartFile multipartFile) throws IOException { File convFile = new File(Objects.requireNonNull(multipartFile.getOriginalFilename())); FileOutputStream fileOutputStream = new FileOutputStream(convFile); fileOutputStream.write(multipartFile.getBytes()); fileOutputStream.close(); return convFile; } private void uploadFileToS3Bucket(String filename, File file) { s3Client.putObject(new PutObjectRequest(bucketName, filename, file).withCannedAcl(CannedAccessControlList.PublicRead)); } public String uploadFile(MultipartFile multipartFile) { String fileUrl = ""; try { File file = convertMultiPartToFile(multipartFile); String filename = generateFilename(multipartFile); fileUrl = endpointUrl + "/" + bucketName + "/" + filename; uploadFileToS3Bucket(filename, file); file.delete(); } catch (IOException e) { e.printStackTrace(); } return fileUrl; } private String generateFilename(MultipartFile multipartFile) { return (Calendar.getInstance().getTime() + "-" + Objects.requireNonNull(multipartFile.getOriginalFilename())).replace(" ", "_"); } }
/* * Copyright (C) 2011-2014 Aestas/IT * * 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.aestasit.markdown.slidery.converters; import static com.aestasit.markdown.Resources.classpath; import static org.apache.commons.io.FileUtils.copyFile; import static org.apache.commons.io.FileUtils.deleteQuietly; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map.Entry; import org.xhtmlrenderer.pdf.ITextRenderer; import com.aestasit.markdown.slidery.configuration.Configuration; import com.lowagie.text.DocumentException; /** * Presentation converter that is based on <a href="http://itextpdf.com/">iText</a> library capable of converting * <i>HTML</i> to <i>PDF</i>. * * @author Andrey Adamovich * */ public class PdfConverter extends TextTemplateConverter { public static final String CONVERTER_ID = "pdf"; protected void beforeStart(final Configuration config) { config .templateFile(classpath("pdf/template.html")) .staticFile("style", classpath("pdf/style/base.css")) .staticFile("style", classpath("pdf/style/code.css")) .staticFile("style", classpath("pdf/style/pdf.css")) .staticFile("style", classpath("pdf/style/reset.css")); } protected void afterConversion(final File joinedInputFile, final Configuration config) { convertToPdf(config.getOutputFile()); if (config.isSplitOutput()) { for (final File inputFile : config.getInputFiles()) { convertToPdf(getSplitOutputFile(config.getOutputFile(), inputFile)); } } deleteStaticFiles(config); } private void convertToPdf(final File outputFile) { File tempFile = null; try { final ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(outputFile); renderer.layout(); tempFile = File.createTempFile("slidery", ".pdf"); final FileOutputStream outputStream = new FileOutputStream(tempFile); try { renderer.createPDF(outputStream, true); } catch (final DocumentException e) { throw new RuntimeException(e); } finally { closeQuietly(outputStream); } copyFile(tempFile, outputFile); } catch (final IOException e) { throw new RuntimeException(e); } finally { deleteQuietly(tempFile); } } private void deleteStaticFiles(final Configuration config) { final File outputDirectory = config.getOutputFile().getParentFile(); for (final Entry<String, File> fileEntry : config.getStaticFiles().entries()) { final String relativePath = fileEntry.getKey(); final String fileName = fileEntry.getValue().getName(); deleteQuietly(new File(new File(outputDirectory, relativePath), fileName)); } } public String getId() { return CONVERTER_ID; } public String getDescription() { return "Basic PDF converter."; } }
package com.ssm.wechatpro.dao; import java.util.List; import java.util.Map; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; public interface WechatProductPackageChooseMapper { /** * * 添加可选套餐分组 */ public void AddWechatProductChooseGroup(Map<String, Object> map) throws Exception; /** * 添加可选套餐 * @param params */ public void AddWechatProductChoosePackage(Map<String, Object> params) throws Exception; /** * 查找所以多选套餐 * @param params */ public List<Map<String, Object>> selectAllPackage(Map<String, Object> map) throws Exception; /** * 查看wechat_product_choose_package表详情 * @param params */ public Map<String, Object> selectOneWechatProductChoosePackage(Map<String, Object> map) throws Exception; /** * 更具多个id查看wechat_product_choose_group表 * @param params */ public List<Map<String, Object>> selectWechatProductChooseGroupByIds(Map<String, Object> map) throws Exception; /** * 更具多个id查看wechat_product表 * @param params */ public List<Map<String, Object>> selectwechatProductByIds(Map<String, Object> map) throws Exception; /** * 删除wechat_product_choose_group * @param params */ public void delectWechatProductChooseGroup(Map<String, Object> map) throws Exception; /** * 删除wechat_product_choose_package * @param params */ public void delectWechatProductChoosePackage(Map<String, Object> map) throws Exception; /** * 修改状态 * @param params */ public void updatePackageState(Map<String, Object> map) throws Exception; /** * * 修改可选套餐分组 */ public void updateWechatProductChooseGroup(Map<String, Object> map) throws Exception; /** * 修改可选套餐 * @param params */ public void updateWechatProductChoosePackage(Map<String, Object> params) throws Exception; /** * 查询价格 * @param params */ public List<Map<String, Object>> selectwechatProductWithProductPrice(Map<String, Object> params) throws Exception; /** * 查询待审核状态的套餐信息 * @param map * @return * @throws Exception */ public List<Map<String,Object>> getCheckPendingList (Map<String, Object> map, PageBounds bounds) throws Exception; public List<Map<String,Object>> getCheckPendingList (Map<String, Object> map) throws Exception; /** * 审核通过的可选套餐 * @param map * @throws Exception */ public void updatePackageStatePass(Map<String,Object> map)throws Exception; /** * 审核不通过的可选套餐 * @param map * @throws Exception */ public void updatePackageStateNotPass(Map<String,Object> map)throws Exception; /** * 提交审核 * @param map * @throws Exception */ public void updateChoosePackageState(Map<String,Object> map)throws Exception; }
package com.tencent.mm.s; import com.tencent.mm.storage.aa.a; public interface a$a { void b(a aVar); void gl(int i); void gm(int i); }
 //------------------------------------ //-------Canvas через View------------ //------------------------------------ //Файл MainActivity.java: package ru.startandroid.develop.p1411canvasview; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new DrawView(this)); } class DrawView extends View { public DrawView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.GREEN); } } } //------------------------------------ //------Canvas через SurfaceView------ //------------------------------------ //Файл MainActivity.java: package ru.startandroid.develop.p1411canvasview; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new DrawView(this)); } class DrawView extends SurfaceView implements SurfaceHolder.Callback { private DrawThread drawThread; public DrawView(Context context) { super(context); getHolder().addCallback(this); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { drawThread = new DrawThread(getHolder()); drawThread.setRunning(true); drawThread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; drawThread.setRunning(false); while (retry) { try { drawThread.join(); retry = false; } catch (InterruptedException e) { } } } class DrawThread extends Thread { private boolean running = false; private SurfaceHolder surfaceHolder; public DrawThread(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; } public void setRunning(boolean running) { this.running = running; } @Override public void run() { Canvas canvas; while (running) { canvas = null; try { canvas = surfaceHolder.lockCanvas(null); if (canvas == null) continue; canvas.drawColor(Color.GREEN); } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } } } } } } //------------------------------------ //------Matrix перемещение------------ //------------------------------------ //Файл MainActivity.java: package ru.startandroid.develop.p1441matrixtransform; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new DrawView(this)); } class DrawView extends View { Paint p; Path path; Matrix matrix; public DrawView(Context context) { super(context); p = new Paint(); p.setStrokeWidth(3); p.setStyle(Paint.Style.STROKE); path = new Path(); matrix = new Matrix(); } @Override protected void onDraw(Canvas canvas) { canvas.drawARGB(80, 102, 204, 255); // создаем крест в path path.reset(); path.addRect(300, 150, 450, 200, Path.Direction.CW); path.addRect(350, 100, 400, 250, Path.Direction.CW); // рисуем path зеленым p.setColor(Color.GREEN); canvas.drawPath(path, p); // настраиваем матрицу на перемещение на 300 вправо и 200 вниз matrix.reset(); matrix.setTranslate(300, 200); // применяем матрицу к path path.transform(matrix); // рисуем path синим p.setColor(Color.BLUE); canvas.drawPath(path, p); } } } //------------------------------------ //------Matrix изменение размера------ //------------------------------------ //Файл MainActivity.java: package ru.startandroid.develop.p1441matrixtransform; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new DrawView(this)); } class DrawView extends View { Paint p; Path path; Matrix matrix; public DrawView(Context context) { super(context); p = new Paint(); p.setStrokeWidth(3); p.setStyle(Paint.Style.STROKE); path = new Path(); matrix = new Matrix(); } @Override protected void onDraw(Canvas canvas) { canvas.drawARGB(80, 102, 204, 255); // создаем крест в path path.reset(); path.addRect(300,150,450,200, Path.Direction.CW); path.addRect(350,100,400,250, Path.Direction.CW); // рисуем path зеленым p.setColor(Color.GREEN); canvas.drawPath(path, p); // настраиваем матрицу на изменение размера: // в 2 раза по горизонтали // в 2,5 по вертикали // относительно точки (375, 100) matrix.reset(); matrix.setScale(2f, 2.5f, 375, 100); // применяем матрицу к path path.transform(matrix); // рисуем path синим p.setColor(Color.BLUE); canvas.drawPath(path, p); // рисуем точку относительно которой было выполнено преобразование p.setColor(Color.BLACK); canvas.drawCircle(375, 100, 5, p); } } //------------------------------------ //---3D Использование GLSurfaceView--- //------------------------------------ import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT; import static android.opengl.GLES20.glClear; import static android.opengl.GLES20.glClearColor; import static android.opengl.GLES20.glViewport; import android.opengl.GLSurfaceView.Renderer; public class OpenGLRenderer implements Renderer { @Override public void onDrawFrame(GL10 arg0) { glClear(GL_COLOR_BUFFER_BIT); } @Override public void onSurfaceChanged(GL10 arg0, int width, int height) { glViewport(0, 0, width, height); } @Override public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) { glClearColor(0f, 1f, 0f, 1f); } } //Файл MainActivity.java import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ConfigurationInfo; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends Activity { private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!supportES2()) { Toast.makeText(this, "OpenGl ES 2.0 is not supported", Toast.LENGTH_LONG).show(); finish(); return; } glSurfaceView = new GLSurfaceView(this); glSurfaceView.setEGLContextClientVersion(2); glSurfaceView.setRenderer(new OpenGLRenderer()); setContentView(glSurfaceView); } @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } private boolean supportES2() { ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); return (configurationInfo.reqGlEsVersion >= 0x20000); } }
// Profiler // Created By : Chris Taylor [C0SM0] // utility modules import java.util.Random; import java.util.Scanner; import java.util.InputMismatchException; // time modules import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; // file editing modules import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.FileNotFoundException; public class Profile { public static void main(String[] args) { // create utility objects Scanner s = new Scanner (System.in); Random r = new Random(); // output files String output_file = "profiles.txt"; // first names array String[] first_name = {"Emma ", "Olivia ", "Ava ", "Isabella ", "Sophia ", "Charlotte ", "Mia ", "Amelia ", "Harper ", "Evelyn ", "Abigail ", "Emily ", "Elizabeth ", "Mila ", "Ella ", "Avery ", "Sofia ", "Camila ", "Aria ", "Scarlett ", "Victoria ", "Madison ", "Luna ", "Grace ", "Chloe ", "Liam ", "Noah ", "William ", "James ", "Oliver ", "Benjamin ", "Elijah ", "Lucas ", "Mason ", "Logan ", "Alexander ", "Ethan ", "Jacob ", "Michael ", "Daniel ", "Henry ", "Jackson ", "Sebastian ", "Aiden ", "Matthew ", "Samuel ", "David ", "Joseph ", "Carter ", "Owen ", "Penelope ", "Layla ", "Riley ", "Zoey ", "Nora ", "Lily ", "Eleanor ", "Hannah ", "Lillian ", "Addison ", "Aubrey ", "Ellie ", "Stella ", "Natalie ", "Zoe ", "Leah ", "Hazel ", "Violet ", "Aurora ", "Savannah ", "Audrey ", "Brooklyn ", "Bella ", "Claire ", "Skylar ", "Wyatt ", "John ", "Jack ", "Luke ", "Jayden ", "Dylan ", "Grayson ", "Levi ", "Isaac ", "Gabriel ", "Julian ", "Mateo ", "Anthony ", "Jaxon ", "Lincoln ", "Joshua ", "Christopher ", "Andrew ", "Theodore ", "Caleb ", "Ryan ", "Asher ", "Nathan ", "Thomas ", "Leo ", "Lucy ", "Paisley ", "Everly ", "Anna ", "Caroline ", "Nova ", "Genesis ", "Emilia ", "Kennedy ", "Samantha ", "Maya ", "Willow ", "Kinsley ", "Naomi ", "Aaliyah ", "Elena ", "Sarah ", "Ariana ", "Allison ", "Gabriella ", "Alice ", "Madelyn ", "Cora ", "Ruby ", "Eva ", "Isaiah ", "Charles ", "Josiah ", "Hudson ", "Christian ", "Hunter ", "Connor ", "Eli ", "Ezra ", "Aaron ", "Landon ", "Adrian ", "Jonathan ", "Nolan ", "Jeremiah ", "Easton ", "Elias ", "Colton ", "Cameron ", "Carson ", "Robert ", "Angel ", "Maverick ", "Nicholas ", "Dominic ", "Serenity ", "Autumn ", "Adeline ", "Hailey ", "Gianna ", "Valentina ", "Isla ", "Eliana ", "Quinn ", "Nevaeh ", "Ivy ", "Sadie ", "Piper ", "Lydia ", "Alexa ", "Josephine ", "Emery ", "Julia ", "Delilah ", "Arianna ", "Vivian ", "Kaylee ", "Sophie ", "Brielle ", "Madeline ", "Jaxson ", "Greyson ", "Adam ", "Ian ", "Austin ", "Santiago ", "Jordan ", "Cooper ", "Brayden ", "Roman ", "Evan ", "Ezekiel ", "Xavier ", "Jose ", "Jace ", "Jameson ", "Leonardo ", "Bryson ", "Axel ", "Everett ", "Parker ", "Kayden ", "Miles ", "Sawyer ", "Jason "}; // middle initial char middle_initial_input = (char) ('A' + r.nextInt(26)); // last names array String[] last_name = {"Dover ", "Smith ", "Johnson ", "Williams ", "Jones ", "Brown ", "Davis ", "Miller ", "Wilson ", "Moore ", "Taylor ", "Anderson ", "Thomas ", "Jackson ", "White ", "Harris ", "Martin ", "Thompson ", "Garcia ", "Martinez ", "Robinson ", "Clark ", "Lewis ", "Lee ", "Walker ", "Hall ", "Allen ", "Young ", "Hernandez ", "King ", "Wright ", "Lopez ", "Hill ", "Scott ", "Green ", "Adams ", "Baker ", "Gonzalez ", "Nelson ", "Carter ", "Mitchell ", "Perez ", "Roberts ", "Turner ", "Phillips ", "Campbell ", "Parker ", "Evans ", "Edwards ", "Collins ", "Stewart ", "Sanchez ", "Morris ", "Rogers ", "Reed ", "Cook ", "Morgan ", "Bell ", "Murphy ", "Bailey ", "Rivera ", "Cooper ", "Richardson ", "Cox ", "Howard ", "Ward ", "Torres ", "Peterson ", "Gray ", "Ramirez ", "James ", "Watson ", "Brooks ", "Kelly ", "Sanders ", "Price ", "Bennett ", "Wood ", "Barnes ", "Ross ", "Henderson ", "Coleman ", "Jenkins ", "Perry ", "Powell ", "Long ", "Patterson ", "Hughes ", "Flores ", "Washington ", "Butler ", "Simmons ", "Foster ", "Gonzales ", "Bryant ", "Alexander ", "Russell ", "Griffin ", "Diaz ", "Hayes "}; // month array String[] month = {"January ", "Febuary ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December "}; // race/ethinc background String[] race = {"White American", "Black American", "American Indian", "Alaska Native", "Asian", "African American", "Native Hawaiian", "Pacific Islander", "Bi-Racial", "Mulatto", "Mestizo", "Itallian American", "French American", "Russian"}; // street [name] array String[] street_name = {"Second ", "Third ", "First ", "Fourth ", "Park ", "Fifth ", "Main ", "Sixth ", "Oak ", "Seventh ", "Pine ", "Maple ", "Cedar ", "Eighth ", "Elm ", "View ", "Washington ", "Ninth ", "Lake ", "Hill ", "Church ", "Liberty ", "Walnut ", "Chestnut ", "Union ", "North ", "South ", "East ", "West ", "River ", "Water ", "Center ", "Broad ", "Market ", "Cherry ", "Highland ", "Mill ", "Franklin ", "School ", "State ", "Front ", "Back ", "Side ", "Prospect ", "Summer ", "Winter ", "Spring ", "Fall ", "Autumn ", "Jefferson ", "Jackson ", "Locust ", "Madison ", "Meadow ", "Spruce ", "Ridge ", "Pearl ", "Dogwood ", "Lincoln ", "Pennsylvania ", "Pleasant ", "Adams ", "Academy ", "Green ", "Brown ", "Hickory ", "Virginia ", "Charles ", "Elizabeth ", "Colonial ", "Monroe ", "Winding ", "Valley ", "Fairway ", "Delaware ", "Sunset ", "Vine ", "Woodland ", "Brookside ", "Hillside ", "College ", "Division ", "Harrison ", "Heather ", "Laurel ", "New ", "Primrose ", "Railroad ", "Willow ", "Berkshire ", "Buckingham ", "Clinton ", "George ", "Hillcrest ", "Hillside ", "Penn ", "Durham ", "Grant ", "Hamilton ", "Holly ", "King ", "Lafayette ", "Linden ", "Popular ", "Cambridge ", "Clark ", "Essex ", "James ", "Magnolia ", "Myrtle ", "Route ", "Shady ", "Surrey ", "Warren ", "Willams ", "Williamson ", "Wood "}; // street [abbreviated] array String[] street_abbreviation = {"ALY, ", "AVE, ", "BCH, ", "BLVD, ", "CTR, ", "CIR, ", "COR, ", "XING, ", "DR, ", "EXPY, ", "FT, ", "GTWY, ", "GLN, ", "GRV, ", "HBR, ", "HWY, ", "LN, ", "MNR, ", "OVAL, ", "PARK, ", "PASS, ", "PIKE, ", "PLZ, ", "RIV, ", "RD, ", "SHR, ", "SQ, ", "ST, ", "TPKE, ", "VLY, ", "VLG, ", "WAY, "}; // states [abbreviated] array String[] state = { "AL ", "AK ", "AZ ", "AR ", "CA ", "CO ", "CT ", "DE ", "FL ", "GA ", "HI ", "ID ", "IL ", "IN ", "IA ", "KS ", "KY ", "LA ", "ME ", "MD ", "MA ", "MI ", "MN ", "MS ", "MO ", "MT ", "NE ", "NV ", "NH ", "NJ ", "NM ", "NY ", "NC ", "ND ", "OH ", "OK ", "OR ", "PA ", "RI ", "SC ", "SD ", "TN ", "TX ", "UT ", "VT ", "VA ", "WA ", "WV ", "WI ", "WY ", "DC "}; // city name array String[] city = {"Washington ", "Springfield ", "Franklin ", "Greenville ", "Bristol ", "Clinton ", "Fairview ", "Salem ", "Madison ", "Georgetown ", "Alexandria", "Maplewood ", "Cedaroak ", "Liberty ", "Union ", "Highland ", "Franklin ", "Prospect ", "Jefferson ", "Jackson ", "Locust ", "Madison ", "Meadow ", "Spruce ", "Dogwood ", "Lincoln ", "Adams ", "Hickory ", "Charles ", "Elizabeth ", "Colonial ", "Monroe ", "Winding ", "Valley ", "Fairway ", "Vineyard ", "Woodland ", "Brookside ", "Hillside ", "Harrison ", "Heather ", "Primrose ", "Berkshire ", "Buckingham ", "Clinton ", "George ", "Hillcrest ", "Hillside ", "Penn ", "Durham ", "Hamilton ", "Holly ", "Lafayette ", "Linden ", "Cambridge ", "Clark ", "Jameston ", "Magnolia ", "Surrey ", "Warren ", "Willams ", "Williamson "}; // email domain array String[] email = {"@gmail.com", "@yahoo.com", "@me.com", "@microsoft.com", "@icloud.com", "@godaddy.org", "@outlook.com", "@hotmail.com", "@msn.com", "@aol.com"}; // favorite color array String[] color = {"Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Pink", "Brown", "Grey", "White", "Black"}; // main code while (true) { // clears terminal System.out.print("\033[H\033[2J"); System.out.flush(); // outputs banner System.out.println(SOURCE_TITLE_COLOR+bannerGenerator()+RESET); System.out.println(CONFIRMATION_STATUS_COLOR+"\t\t\t[::]False Identity Profile Generator | v.1[::]\n\t\t\t [::]Created By : Chris Taylor[::]\n"+RESET); System.out.println(HEADER_COLOR+"[::]GitHub : https://github.com/CosmodiumCS/profiler[::]"+RESET); String profiles = ""; // user input try { // formats terminal user@program String term_host = "\n"+INPUT_STATUS_COLOR+"[~] "+RESET+SUB_BANNER_COLOR+"root"+RESET+SOURCE_TITLE_COLOR+"@"+RESET+EXCEPTION_STATUS_COLOR+"profiler "+RESET+SOURCE_TITLE_COLOR+"$ "+RESET; // gets number of profiles System.out.print(term_host+INPUT_STATUS_COLOR+"How Many Profiles Do You Wish To Generate? : "+RESET); int profile_number = s.nextInt(); // determines whether or not the output will be written to a file System.out.print(term_host+INPUT_STATUS_COLOR+"Would You like To Output The Profiles To \""+output_file+"\"? [y/n]: "+RESET); String write_file = s.next(); // notifies user of progress System.out.print(CONFIRMATION_STATUS_COLOR+"\n[*] Generating Profiles...\n"+RESET); // initializes output variables boolean write_to_file; boolean colored_print; // formats file output if (write_file.equalsIgnoreCase("y") || write_file.equalsIgnoreCase("yes")) { write_to_file = true; colored_print = false; } // formats terminal output else if (write_file.equalsIgnoreCase("n") || write_file.equalsIgnoreCase("no")) { write_to_file = false; colored_print = true; } // exception else { System.out.println(EXCEPTION_STATUS_COLOR+"\n[!!] Input Not Recognized, Try Again With "+RESET+SOURCE_TITLE_COLOR+ "\"y\""+RESET+EXCEPTION_STATUS_COLOR+" for "+RESET+SOURCE_TITLE_COLOR+"\"yes\""+RESET+ EXCEPTION_STATUS_COLOR+" or "+RESET+SOURCE_TITLE_COLOR+"\"n\""+RESET+EXCEPTION_STATUS_COLOR+ " for "+RESET+SOURCE_TITLE_COLOR+"\"no\"\n"+RESET); break; } // creates colored variable titles if os allows for it String title_color; String data_color; String symbol_color; String reset_text; if (colored_print == true) { title_color = CONFIRMATION_STATUS_COLOR; data_color = SOURCE_TITLE_COLOR; symbol_color = EXCEPTION_STATUS_COLOR; reset_text = RESET; } else{ title_color = ""; data_color = ""; symbol_color = ""; reset_text = ""; } for (int i = 0; i < profile_number; i++) { // identity variables String first_name_input = randomItem(first_name); String last_name_input = randomItem(last_name); String email_input = randomItem(email); String input_month = randomItem(month); String name_of_street = randomItem(street_name); String abbreviated_street = randomItem(street_abbreviation); String name_of_city = randomItem(city); String abbreviated_state = randomItem(state); String favorite_color = randomItem(color); String race_ethnicity = randomItem(race); // output variables String contact = contactGenerator(first_name_input, middle_initial_input, last_name_input, email_input, title_color, data_color, symbol_color, reset_text); String racial_output = String.format("\n%s[+]-----------%s%sRACE%s%s : %s%s%s%s", symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, race_ethnicity, reset_text); String dob = dobGenerator(input_month, title_color, data_color, symbol_color, reset_text); String location = locationGenerator(name_of_street, abbreviated_street, name_of_city, abbreviated_state, title_color, data_color, symbol_color, reset_text); String color_output = String.format("\n%s[+]-%s%sFAVORITE-COLOR%s%s : %s%s%s%s\n", symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, favorite_color, reset_text); // counts profiles int iterable = i + 1; // sets profile header for each profile [written to file] profiles += "[+] Profile-"+iterable+":\n=============="+contact+racial_output+dob+location+color_output+"\n"; // writes output to file if (write_to_file == true) { System.out.println(writeFile(output_file, profiles, iterable)+"\n"); } // terminal output else { // prints profile number System.out.print(HEADER_COLOR+"\n[+] Profile-"+RESET+iterable+SUB_BANNER_COLOR+":\n=============="+RESET); // outputs contact information [full name, email, phone #, social security #] System.out.print(contact); // outputs race and ethnic background System.out.print(racial_output); // outputs date of birth and age System.out.print(dob); // outputs location System.out.print(location); // outputs favorite color, possible security question System.out.print(color_output+"\n"); } } break; } // exception catch (InputMismatchException e){ System.out.println(EXCEPTION_STATUS_COLOR+"\n[!!] Input Not Recognized, Enter a Number"+RESET+CONFIRMATION_STATUS_COLOR+"\n[+] i.e "+RESET+SOURCE_TITLE_COLOR+"\"23\""+RESET+"\n"); break; } } } // confirms use of color based on operating system [os] public static String colorDetect(String color, String os) { String confirm; // confirms color use if (os.toLowerCase().indexOf("mac") >= 0 || os.toLowerCase().indexOf("nix") >= 0 || os.toLowerCase().indexOf("nux") >= 0 || os.toLowerCase().indexOf("aix") > 0 ) { confirm = color; } // denies color use else { confirm = ""; } return confirm; } // gets operating system [os] distro public static final String OS = System.getProperty("os.name"); // colored variables public static final String RESET = colorDetect("\033[0m", OS); // text reset public static final String SOURCE_TITLE_COLOR = colorDetect("\033[0;33m", OS); // yellow public static final String INPUT_STATUS_COLOR = colorDetect("\033[0;37m", OS); // white public static final String EXCEPTION_STATUS_COLOR = colorDetect("\033[0;31m", OS); // red public static final String CONFIRMATION_STATUS_COLOR = colorDetect("\033[0;36m", OS); // cyan public static final String HEADER_COLOR = colorDetect("\033[0;35m", OS); // purple public static final String SUB_BANNER_COLOR = colorDetect("\033[0;32m", OS); // green // gets random item from array public static String randomItem(String[] array) { int r = new Random().nextInt(array.length); return array[r]; } // gets random banner public static String bannerGenerator() { // banners String stargazing_font = " ::::::::: ::::::::: :::::::: :::::::::: ::::::::::: ::: :::::::::: ::::::::: \r\n" + " :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: \r\n" + " +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ \r\n" + " +#++:++#+ +#++:++#: +#+ +:+ :#::+::# +#+ +#+ +#++:++# +#++:++#: \r\n" + " +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ \r\n" + " #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# \r\n" + "### ### ### ######## ### ########### ########## ########## ### ### "; String graffiti_font = "__________ _____.__.__ \r\n" + "\\______ \\_______ _____/ ____\\__| | ___________ \r\n" + " | ___/\\_ __ \\/ _ \\ __\\| | | _/ __ \\_ __ \\\r\n" + " | | | | \\( <_> ) | | | |_\\ ___/| | \\/\r\n" + " |____| |__| \\____/|__| |__|____/\\___ >__| \r\n" + " \\/ "; // gets and returns random banner String[] font_options = {stargazing_font, graffiti_font}; String banner = randomItem(font_options); return "\n"+banner; } // creates file public static String createFile(String file) { // creates or checks output file try { File outputFile = new File(file); // creates file if (outputFile.createNewFile()) { return CONFIRMATION_STATUS_COLOR+"\n[+] File Created: "+RESET+SOURCE_TITLE_COLOR+outputFile.getName()+RESET; } // checks file else { return EXCEPTION_STATUS_COLOR+"\n[!] File Already Exists...\n"+RESET+CONFIRMATION_STATUS_COLOR+"[+] Continuing Profile Generation..."+RESET; } } // exception catch (IOException e) { e.printStackTrace(); return EXCEPTION_STATUS_COLOR+"\n[!!] Error Creating File"+RESET; } } // writes to file public static String writeFile(String file, String write, int iteration) { String profile = "Profile-"+iteration; // write file formatting try { FileWriter output = new FileWriter(file); // writes output to file output.write(write); output.close(); return CONFIRMATION_STATUS_COLOR+"\n[+] Success! "+RESET+SOURCE_TITLE_COLOR+ profile+RESET+CONFIRMATION_STATUS_COLOR+" Written To "+RESET+ SOURCE_TITLE_COLOR+"\""+file+"\""+RESET; } // exception catch (IOException e) { e.printStackTrace(); return EXCEPTION_STATUS_COLOR+"\n[!!] Error Writing File"+RESET; } } // full name, email, and phone number generator [contact information] public static String contactGenerator(String first, char middle, String last, String domain, String title_color, String data_color, String symbol_color, String reset_text) { Random r = new Random(); // full name formatting String fullname_format = symbol_color+"\n[+]-----------"+reset_text+title_color+"NAME"+reset_text+symbol_color+" : "+reset_text+data_color+"%s%c. %s\n"+reset_text; String fullname = String.format(fullname_format, first, middle, last); // phone number formatting int phone_number = r.nextInt(10000 - 1000) + 1000; //social security number [ssn] formatting int ssn1 = r.nextInt(1000 - 100) + 100; int ssn2 = r.nextInt(100 - 10) + 10; // email formatting String email = first.toLowerCase() + last.toLowerCase() + domain; String user_email = email.replaceAll(" ", ""); // make string variables for password formatting String phone = String.valueOf(phone_number); String ssn_one = String.valueOf(ssn1); String ssn_two = String.valueOf(ssn2); String[] password_options = {first, last, phone, ssn_one, ssn_two}; // create password String password_part1 = randomItem(password_options); int password_part2 = r.nextInt(1000 - 10) + 10; String partone = password_part1.toString(); String parttwo = String.valueOf(password_part2); // password formatting String password_unformatted = partone + parttwo; String password = password_unformatted.replaceAll(" ", ""); // return output String contact = String.format("%s%s[+]----------%s%sEMAIL%s%s : %s%s%s%s\n%s[+]-------%s%sPASSWORD%s%s : %s%s%s%s\n%s[+]----------%s%sPHONE%s%s : %s%sXXX-XXX-%d%s\n%s[+]------------%s%sSSN%s%s : %s%s%d-%d-XXXX%s", fullname, symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, user_email, reset_text, symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, password, reset_text, symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, phone_number, reset_text, symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, ssn1, ssn2, reset_text); return contact; } // date of birth [dob] and age generator public static String dobGenerator(String birth_month, String title_color, String data_color, String symbol_color, String reset_text) { Random r = new Random(); // get and format current year LocalDateTime getTime = LocalDateTime.now(); DateTimeFormatter get_year_format = DateTimeFormatter.ofPattern("yyyy"); String year = getTime.format(get_year_format); int current_year = Integer.parseInt(year); // maximum and minimum birth years int max_year = current_year - 10; int min_year = current_year - 65; // dob variables int birth_year = r.nextInt(max_year - min_year) + min_year; int birth_day = r.nextInt(32 - 1) + 1; int age = (current_year - birth_year); // return output String dob = String.format("\n%s[+]------------%s%sDOB%s%s : %s%s%s%d, %s%s\n%s[+]------------%s%sAGE%s%s : %s%s%d Years of Age%s", symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, birth_month, birth_day, birth_year, reset_text, symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, age, reset_text); return dob; } // address and location generator public static String locationGenerator(String street, String abbr, String city_name, String state_name, String title_color, String data_color, String symbol_color, String reset_text) { Random r = new Random(); // generate numeric variables int address_number = r.nextInt(10000 - 1) + 1; int zip_code = r.nextInt(100000 - 10000) + 10000; // return output String location = String.format("\n%s[+]-------%s%sLOCATION%s%s : %s%s%d %s%s%s%s%d%s", symbol_color, reset_text, title_color, reset_text, symbol_color, reset_text, data_color, address_number, street, abbr, city_name, state_name, zip_code, reset_text); return location; } }
package lotto.step1; public class Calculator { private String text; private Validation validation; private Delimiter delimiter; private static final int NEGATIVE_NUMBER_CONDITION = 0; private static final int PRINT_NUMBER = 0; public Calculator(String text) { this.text = text; this.delimiter = new Delimiter(text); this.validation = new Validation(text); } public int calculate() { if (validation.checkEmptyAndNull()) { return PRINT_NUMBER; } if (validation.checkOnlyNumber()) { return printNumber(); } return addNumbers(delimiter.getNumbers()); } public void isNegativeNumber(String number) { if (Integer.valueOf(number) < NEGATIVE_NUMBER_CONDITION) { throw new IllegalArgumentException("음수는 입력할 수 없습니다."); } } public int printNumber() { return Integer.valueOf(text); } public int addNumbers(String numbers[]) { int sum = 0; for (String number : numbers) { isNegativeNumber(number); sum += Integer.valueOf(number); } return sum; } }
package nl.hsleiden.gamepad.events; public enum States { PRESSED, RELEASED }
package com.espendwise.manta.util.validation.rules; import com.espendwise.manta.model.data.PropertyData; import com.espendwise.manta.model.data.UserData; import com.espendwise.manta.util.validation.ValidationRule; import com.espendwise.manta.util.validation.ValidationRuleResult; import org.apache.log4j.Logger; import java.util.List; public class UserNotificationConfigurationConstraint implements ValidationRule { private static final Logger logger = Logger.getLogger(UserNotificationConfigurationConstraint.class); private Long storeId; private UserData userData; private List<PropertyData> propertyDataList; public UserNotificationConfigurationConstraint(Long storeId, UserData userData, List<PropertyData> propertyDataList) { this.storeId = storeId; this.userData = userData; this.propertyDataList = propertyDataList; } public Long getStoreId() { return storeId; } public ValidationRuleResult apply() { logger.info("apply()=> BEGIN"); ValidationRuleResult result = new ValidationRuleResult(); result.success(); logger.info("apply()=>END"); return result; } }
import java.util.*; /** * 剑指 Offer 38. 字符串的排列 * Medium * 应该做过类似的排列题,时间太久了就还是要重新想 */ public class Solution { private void recur(List<String> res, String str, List<String> chars) { if (chars.size() == 0) { res.add(str); return; } Set<String> set = new HashSet<>(); // 当前层集合 for (int i = 0; i < chars.size(); i++) { if(set.contains(chars.get(i))) // 剪枝 continue; String t = chars.remove(i); set.add(t); recur(res, str + t, chars); chars.add(i, t); } } public String[] permutation(String s) { List<String> res = new ArrayList<>(); List<String> charList = new LinkedList<>(); for (char c : s.toCharArray()) { charList.add(String.valueOf(c)); } recur(res, "", charList); return res.toArray(new String[res.size()]); } public static void main(String[] args) { Solution s = new Solution(); String[] strings = { "abc", "abcd", "a", "aab" }; for (String str : strings) { String[] res = s.permutation(str); System.out.println(String.join(",", res)); } } }
package com.mighty.eurekacustomer.controller; import com.mighty.eurekacustomer.service.HelloService; import org.apache.coyote.Request; 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.RestController; import org.springframework.web.client.RestTemplate; /** * Consumer of services * * @author mighty * @create 2018-11-20 21:30 */ @RestController public class ConsumerController { @Autowired RestTemplate restTemplate; @Autowired HelloService helloService; @RequestMapping(value="/ribbon-consumer", method = RequestMethod.GET) public String helloConsumer(){ return helloService.helloService(); } }
package com.petersoft.mgl.connection; import com.petersoft.mgl.model.*; import javax.persistence.TypedQuery; import java.util.List; public class MainFrameQuery extends AbstractQuery { public MainFrameQuery() { } public static List<Lepcso> getLepcsoList() { open(); TypedQuery<Lepcso> query = EntityManagerHandler.INSTANCE .getEntityManager().createQuery("SELECT l FROM Lepcso l", Lepcso.class); return query.getResultList(); } public static List<Tipus> getTipusList() { open(); TypedQuery<Tipus> query = EntityManagerHandler.INSTANCE .getEntityManager().createQuery("SELECT t FROM Tipus t", Tipus.class); return query.getResultList(); } public static List<Location> getLocationList() { open(); TypedQuery<Location> query = EntityManagerHandler.INSTANCE .getEntityManager().createQuery("SELECT l FROM Location l", Location.class); return query.getResultList(); } public static void saveTipus(Tipus tipus) { open(); EntityManagerHandler.INSTANCE.getEntityManager().persist(tipus); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static void saveLocation(Location location) { open(); EntityManagerHandler.INSTANCE.getEntityManager().persist(location); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static void saveLepcso(Lepcso lepcso) { open(); EntityManagerHandler.INSTANCE.getEntityManager().merge(lepcso); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static List<ErintesVedelem> getErVedList() { open(); TypedQuery<ErintesVedelem> query = EntityManagerHandler.INSTANCE .getEntityManager().createQuery("SELECT ev FROM ErintesVedelem ev", ErintesVedelem.class); return query.getResultList(); } public static void saveErintesVedelem(ErintesVedelem e) { open(); EntityManagerHandler.INSTANCE.getEntityManager().persist(e); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static List<Hiba> getHibaList() { open(); TypedQuery<Hiba> query = EntityManagerHandler.INSTANCE .getEntityManager().createQuery("SELECT hiba FROM Hiba hiba", Hiba.class); return query.getResultList(); } public static List<Javitas> getJavitasList() { open(); TypedQuery<Javitas> query = EntityManagerHandler.INSTANCE .getEntityManager().createQuery("SELECT jav FROM Javitas jav", Javitas.class); return query.getResultList(); } public static void saveHiba(Hiba hiba) { open(); EntityManagerHandler.INSTANCE.getEntityManager().persist(hiba); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static void saveJavitas(Javitas javitas) { open(); EntityManagerHandler.INSTANCE.getEntityManager().persist(javitas); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static void shutdown() { shuttingdown(); } public static void deleteLepcso(Lepcso lepcso) { open(); EntityManagerHandler.INSTANCE.getEntityManager().remove(lepcso); EntityManagerHandler.INSTANCE.getEntityTransaction().commit(); } public static void rollback() { EntityManagerHandler.INSTANCE.getEntityTransaction().rollback(); } }
package com.qiyi.openapi.demo.presenter; public interface IBaseContrackPresenter { }
package org.tc.aop; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestApp { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class); DemoAnnotationServiceImpl demoAnnotationService = context.getBean(DemoAnnotationServiceImpl.class); DemoMethodServiceImpl demoMethodService = context.getBean(DemoMethodServiceImpl.class); demoAnnotationService.add();//基于注解的拦截 demoMethodService.add();//给予方法规则的拦截 context.close(); } }
package com.secoo.bigdata.kaggle.talkingdata.service; import org.apache.commons.math3.distribution.PoissonDistribution; import com.secoo.bigdata.kaggle.talkingdata.domain.Group; public class ForecastAgeService { public double[] forecast(double meanAge, double stdAge, double maleProbability, double femaleProbability) { PoissonDistribution nd1 = new PoissonDistribution(meanAge); double[] p = new double[Group.GROUPS.length]; int i = 0; for (Group group : Group.GROUPS) { double tp = 0; for (int age = group.getAgeBottom(); age <= group.getAgeTop(); age++) { tp += nd1.probability(age); } if (group.getGender().equals("F")) p[i++] = tp * femaleProbability; else p[i++] = tp * maleProbability; } return p; } }
package com.question.service.impl; import com.question.dao.TitleDao; import com.question.model.Title; import com.question.service.TitleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service("TitleService") public class TitleServiceImpl implements TitleService { private Logger logger= LoggerFactory.getLogger(TitleServiceImpl.class); @Autowired private TitleDao titleDao; @Override public Title getTitle(int questionId) { return titleDao.getTitle(questionId); } @Override public int getTitleNum(){ return titleDao.getTitleNum(); }; }
package com.example.membresia; import com.example.membresia.entities.Membresia; import com.example.membresia.entities.PagoMembresia; import com.example.membresia.entities.Tarjeta; import com.example.membresia.services.impl.MembresiaServiceImpl; import com.example.membresia.services.impl.PagoMembresiaServiceImpl; import com.example.membresia.services.impl.TarjetaServiceImpl; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.util.Assert; import javax.validation.constraints.AssertFalse; import java.util.List; @SpringBootTest class MembresiaServiceApplicationTests { Membresia membresia = new Membresia(); MembresiaServiceImpl MSI = new MembresiaServiceImpl(); PagoMembresia pagomembresia = new PagoMembresia(); PagoMembresiaServiceImpl PMSI = new PagoMembresiaServiceImpl(); Tarjeta tarjeta = new Tarjeta(); TarjetaServiceImpl TSI = new TarjetaServiceImpl(); @Test void TestComprarMembresia() { Membresia Expected = MSI.save(membresia); Assertions.assertSame(Expected,membresia); } @Test void TestIngresarPagoMembresia() { PagoMembresia Expected = PMSI.save(pagomembresia); Assertions.assertSame(Expected,pagomembresia); } @Test void TestAgregarTarjeta(){ Tarjeta Expected = TSI.save(tarjeta); Assertions.assertSame(Expected, tarjeta); } @Test void TestEliminarTarjeta() { try { TSI.deleteById((long) 1); } finally { Assert.isTrue(true,"Eliminacion Correcta"); } ; Assert.state(false, "Eliminacion Fallida"); } @Test void TestListarTarjetas() { List<Tarjeta> Expected = TSI.findAll(); Assertions.assertSame(Expected, TSI.findAll()); } }
package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * Authorization */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-04-02T16:04:50.980Z") public class Authorization { @JsonProperty("userId") private String userId = null; @JsonProperty("token") private String token = null; public Authorization userId(String userId) { this.userId = userId; return this; } /** * Get userId * @return userId **/ @ApiModelProperty(example = "31234567890", value = "") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Authorization token(String token) { this.token = token; return this; } /** * Get token * @return token **/ @ApiModelProperty(example = "Basic ZllvSFpwcnJCR01XZXExZk9IYUFIWTZmWE53bTA1TDJLaXdZRFI2azZrWDYyclhTY3REOEhVbHZVRzZGcEVlOA==", value = "") public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Authorization authorization = (Authorization) o; return Objects.equals(this.userId, authorization.userId) && Objects.equals(this.token, authorization.token); } @Override public int hashCode() { return Objects.hash(userId, token); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Authorization {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" token: ").append(toIndentedString(token)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.example.demo.service; import com.example.demo.domain.Employee; import com.example.demo.domain.EmployeePage; import java.util.List; public interface EmployeeService { public List<Employee> selectBypage(EmployeePage page); public int addEmployee(Employee employee); public int deleteEmployee(int id); public int updateEmployee(Employee employee); public int getCount(EmployeePage page); }
package org.gooru.dap.jobs.components; import java.util.ArrayList; import java.util.List; public final class AppInitializer { private AppInitializer() { throw new AssertionError(); } private static final List<InitializationAwareComponent> initializers = new ArrayList<>(); static { initializers.add(DataSourceRegistry.getInstance()); } public static void initializeApp() { for (InitializationAwareComponent initializer : initializers) { initializer.initializeComponent(); } } }
package com.service; import com.domain.User; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import javax.inject.Inject; import javax.inject.Named; import java.util.Objects; /** * Created by Michał on 2016-11-15. */ @Named public class UserValidator implements Validator { @Inject private UserService userService; @Override public boolean supports(Class<?> clazz) { return User.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; String email = user.getEmail(); validateEmailUniqueness(email, errors); } private void validateEmailUniqueness(String email, Errors errors) { User userWithSameEmail = userService.getUserByEmail(email); if (Objects.nonNull(userWithSameEmail)) { errors.rejectValue("email", "email.unique", "This email is used by another user."); } } }
package hirondelle.web4j.model; import java.io.Serializable; import java.util.List; import javax.servlet.ServletException; /** Base class for most exceptions defined by WEB4J. <P>Differs from most exception classes in that multiple error messages may be used, instead of just one. Used in JSPs to inform the user of error conditions, usually related to user input validations. <P>This class is {@link Serializable}, since all {@link Throwable}s are serializable. */ public class AppException extends ServletException implements MessageList { /** No-argument constructor. */ public AppException(){ super(); } /** Constructor. @param aMessage text describing the problem. Must have content. @param aThrowable root cause underlying the problem. */ public AppException(String aMessage, Throwable aThrowable){ super(aMessage, aThrowable); add(aMessage); //using instanceof is distasteful, but overloading constructors, //that is, defining a second ctor(String, AppException), does not work if ( aThrowable instanceof AppException ) { add( (AppException)aThrowable ); } } public final void add(String aErrorMessage){ fErrorMessages.add(aErrorMessage); } public final void add(String aErrorMessage, Object... aParams){ fErrorMessages.add(aErrorMessage, aParams); } public final void add(AppException ex){ fErrorMessages.add(ex); } public boolean isEmpty(){ return fErrorMessages.isEmpty(); } public final boolean isNotEmpty(){ return !fErrorMessages.isEmpty(); } public final List<AppResponseMessage> getMessages(){ return fErrorMessages.getMessages(); } /** Intended for debugging only. */ @Override public String toString(){ return fErrorMessages.toString(); } // PRIVATE /** List of error messages attached to this exception. <P>Implementation Note : This class is a wrapper of MessageListImpl, and simply forwards related method calls to this field. This avoids code repetition. */ private MessageList fErrorMessages = new MessageListImpl(); }
<<<<<<< HEAD import processing.core.PApplet; import javax.swing.*; public class Main extends PApplet { static int n; float x; float y; float r; int c; public void settings() { fullScreen(); } public void setup() { frameRate(4); } public void draw() { background(0); for (int i = 0; i < n; i++) { x = random(0, width); y = random(0, height); r = random(40, 100); c = (int) (0xFF000000 + random(0x00FFFFFF)); fill(c); ellipse(x, y, r, r); } noLoop(); } public static void main(String... args) { n = Integer.parseInt(JOptionPane.showInputDialog("N: ")); PApplet.main("Main"); } ======= import processing.core.PApplet; import javax.swing.*; public class Main extends PApplet { static int n; float x; float y; float r; int c; public void settings() { fullScreen(); } public void setup() { frameRate(4); } public void draw() { background(0); for (int i = 0; i < n; i++) { x = random(0, width); y = random(0, height); r = random(40, 100); c = (int) (0xFF000000 + random(0x00FFFFFF)); fill(c); ellipse(x, y, r, r); } noLoop(); } public static void main(String... args) { n = Integer.parseInt(JOptionPane.showInputDialog("N: ")); PApplet.main("Main"); } >>>>>>> 6becc31ecf0535cde9041672d21f2c62b7103190 }
/** * ReservationInfoPrice.java $version 2018. 8. 14. * * Copyright 2018 NAVER Corp. All rights Reserved. * NAVER PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.nts.pjt3.dto; /** * @author Seok Jeongeum * */ public class ReservationInfoPrice { private int id; private int reservationInfoId; private int productPriceId; private int count; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the reservationInfoId */ public int getReservationInfoId() { return reservationInfoId; } /** * @param reservationInfoId the reservationInfoId to set */ public void setReservationInfoId(int reservationInfoId) { this.reservationInfoId = reservationInfoId; } /** * @return the productPriceId */ public int getProductPriceId() { return productPriceId; } /** * @param productPriceId the productPriceId to set */ public void setProductPriceId(int productPriceId) { this.productPriceId = productPriceId; } /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } @Override public String toString() { return "ReservationInfoPrice [id=" + id + ", reservationInfoId=" + reservationInfoId + ", productPriceId=" + productPriceId + ", count=" + count + "]"; } }
/** * */ package taller.excepciones; /** * @author agonzalez * */ @SuppressWarnings("serial") public class ErrorIdentificadorMecanicoNoValido extends Exception { /** * */ public ErrorIdentificadorMecanicoNoValido() { // TODO Auto-generated constructor stub } /** * @param arg0 */ public ErrorIdentificadorMecanicoNoValido(String arg0) { super(arg0); // TODO Auto-generated constructor stub } /** * @param arg0 */ public ErrorIdentificadorMecanicoNoValido(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub } /** * @param arg0 * @param arg1 */ public ErrorIdentificadorMecanicoNoValido(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } }
package fol.ast; public class OrExpr extends Expr { Expr left; Expr right; public OrExpr(Expr left, Expr right) { super(); this.left=left; this.right=right; } @Override public String toString() { return left.toString()+'+'+right.toString(); } }
/** * */ package de.zarncke.lib.sys.mbean; import javax.management.MBeanRegistrationException; import de.zarncke.lib.err.Warden; import de.zarncke.lib.sys.Headquarters; import de.zarncke.lib.sys.Health; /** * Exposes Headquarters state for monitoring. * * @author Gunnar Zarncke */ public class HeadquartersAccess implements HeadquartersAccessMBean { @Override public String getName() { return Headquarters.HEADQUARTERS.get().getInstallation().getName().getDefault(); } @Override public String getHealth() { return Headquarters.HEADQUARTERS.get().getHealth().name(); } @Override public String getState() { return Headquarters.HEADQUARTERS.get().getState().name(); } @Override public double getLoad() { return Headquarters.HEADQUARTERS.get().getLoad(); } @Override public void minimumFor(final String callerKey, final int minimum) { Headquarters.HEADQUARTERS.get().assignMinimumCount(callerKey, minimum); } @Override public void importantFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.IMPORTANT); } @Override public void errorsFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.ERRORS); } @Override public void failuresFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.FAILURE); } @Override public void infoFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.INFO); } @Override public void discardableFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.DISCARDABLE); } @Override public void warningsFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.WARNINGS); } @Override public void okFor(final String callerKey) { Headquarters.HEADQUARTERS.get().assignSeverity(callerKey, Health.OK); } @Override public void refreshModules() { try { JmxHeadquarters.startOrRestartHeadquartersMBean(); } catch (MBeanRegistrationException e) { Warden.report(e); } } }