blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
ea95bd3f4f73cb6ff3c335c7e5b6fae9e4b0caa4
Java
wishwa-gayan/SosialApp
/app/src/main/java/com/wixmat/sosialapp/setup.java
UTF-8
18,639
1.570313
2
[]
no_license
package com.wixmat.sosialapp; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.internal.InternalTokenProvider; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.like.LikeButton; import com.like.OnLikeListener; import com.squareup.picasso.Picasso; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import java.util.Calendar; import java.util.HashMap; public class setup extends AppCompatActivity { private EditText firstNameTxt, lastNameTxt, dateTxt, uname; private RadioGroup radioGroupGender; private RadioButton malegbtn, femalegbtn; private ImageView imageView,backbutton; private int gselection; private int date; private int year; private int month; private DatePickerDialog.OnDateSetListener mDateSetListener; private FirebaseAuth mAuth; private FirebaseDatabase database; private DatabaseReference userRef; private StorageReference UserProfileImageRef; private LikeButton likeButton; private final String Tag = "DataPicker"; private String cuserid,downloadurl; final static int Gallery_Pick = 1; ProgressDialog progressDialog; private Toolbar toolbar; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup); imageView = findViewById(R.id.profile_image1); firstNameTxt = findViewById(R.id.first_name_txt); lastNameTxt = findViewById(R.id.last_name_txt); malegbtn = findViewById(R.id.malegbtn); femalegbtn = findViewById(R.id.femalegbtn); radioGroupGender = findViewById(R.id.gnder_grop); dateTxt = findViewById(R.id.bithday_txt); uname = findViewById(R.id.unametxt); toolbar = (Toolbar) findViewById(R.id.setup_toolbar); TextView toolbar_title = toolbar.findViewById(R.id.toolbar_title); toolbar_title.setText(R.string.setup_tool_bar_title); ImageView backbutton = toolbar.findViewById(R.id.back_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); mAuth = FirebaseAuth.getInstance(); database = FirebaseDatabase.getInstance(); FirebaseApp.initializeApp(setup.this); UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images"); cuserid = mAuth.getCurrentUser().getUid(); userRef = database.getInstance().getReference().child("Users").child(cuserid); progressDialog = new ProgressDialog(this); cuserid = mAuth.getCurrentUser().getUid(); boolean sessionId = getIntent().getBooleanExtra("backbutton", false); if(sessionId){ backbutton.setVisibility(View.VISIBLE); intialize(); }else{ backbutton.setVisibility(View.GONE); } userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { if (dataSnapshot.hasChild("profileimage")) { String image = dataSnapshot.child("profileimage").getValue().toString(); Picasso.get().load(image).placeholder(R.drawable.profile).into(imageView); } else { Toast.makeText(setup.this, "Please select profile image first.", Toast.LENGTH_SHORT).show(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); backbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SendUserToMainActivity(); } }); } private void SendUserToMainActivity() { Intent mainIntent = new Intent(setup.this, MainActivity.class); startActivity(mainIntent); } public void intialize(){ userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { String fname = ""; fname = dataSnapshot.child("fname").getValue().toString(); String lname =""; lname = dataSnapshot.child("lname").getValue().toString(); String username = ""; username = dataSnapshot.child("uname").getValue().toString(); String bod = ""; bod = dataSnapshot.child("bod").getValue().toString(); String gender = ""; gender = dataSnapshot.child("gender").getValue().toString(); uname.setText(username); firstNameTxt.setText(fname); lastNameTxt.setText(lname); dateTxt.setText(bod); gselection = radioGroupGender.getCheckedRadioButtonId(); if (gender == "male") { malegbtn.setSelected(true); } else { femalegbtn.setSelected(true); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public void setDate(View view) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog( setup.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener, year, month, day); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { month = month + 1; Log.d(Tag, "onDateSet: mm/dd/yyy: " + month + "/" + day + "/" + year); String date = month + "/" + day + "/" + year; dateTxt.setText(date); } }; } public void reg(View view) { saveAccoutnInformation(); } private void saveAccoutnInformation() { String fname = ""; fname = firstNameTxt.getText().toString(); String lname = ""; lname = lastNameTxt.getText().toString(); String bod =""; bod = dateTxt.getText().toString(); String uanme =""; uanme = uname.getText().toString(); String gender = ""; gselection = radioGroupGender.getCheckedRadioButtonId(); if (gselection == R.id.malegbtn) { gender = "male"; } else if (gselection == R.id.femalegbtn) { gender = "female"; } if (fname.isEmpty()) Toast.makeText(setup.this, R.string.setup_fname_error, Toast.LENGTH_LONG).show(); if (lname.isEmpty()) Toast.makeText(setup.this, R.string.setup_lname_error, Toast.LENGTH_LONG).show(); if (bod.isEmpty()) Toast.makeText(setup.this, R.string.setup_bod_error, Toast.LENGTH_LONG).show(); if (gender.isEmpty()) Toast.makeText(setup.this, R.string.setup_gender_error, Toast.LENGTH_LONG).show(); if (uanme.isEmpty()) Toast.makeText(setup.this, R.string.setup_uname_error, Toast.LENGTH_LONG).show(); else { progressDialog.setTitle(R.string.setup_title); progressDialog.setMessage(R.string.setup_msg + ""); progressDialog.show(); progressDialog.setCanceledOnTouchOutside(true); HashMap usermap = new HashMap(); usermap.put("fname", fname); usermap.put("uid", cuserid); usermap.put("lname", lname); usermap.put("uname", uanme); usermap.put("proflieiamge", downloadurl); usermap.put("bod", bod); usermap.put("type", "0"); usermap.put("gender", gender); usermap.put("status", R.string.setup_status); userRef.updateChildren(usermap).addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { sendToMainAcitity(); } else // Toast.makeText(setup.this, R.string.setup_toast2+task.getException().getMessage().toString(), Toast.LENGTH_LONG).show(); progressDialog.dismiss(); } }); } } @Override protected void onStart() { checkUserExitanse(); super.onStart(); } private void checkUserExitanse() { final String current_user_id = mAuth.getCurrentUser().getUid(); userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(current_user_id)) { } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void sendToMainAcitity() { Intent mainActitiyIntent = new Intent(setup.this, MainActivity.class); mainActitiyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK ); startActivity(mainActitiyIntent); finish(); } public void setImage(View view) { Intent gallIntent = new Intent(); gallIntent.setAction(Intent.ACTION_GET_CONTENT); gallIntent.setType("image/*"); startActivityForResult(gallIntent, Gallery_Pick); userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { if (dataSnapshot.hasChild("profileimage")) { String image = dataSnapshot.child("profileimage").getValue().toString(); Picasso.get().load(image).placeholder(R.drawable.profile).into(imageView); } else { Toast.makeText(setup.this, "Please select profile image first.", Toast.LENGTH_SHORT).show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) { Uri ImageUri = data.getData(); CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .setAspectRatio(1, 1) .start(this); } if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if(resultCode == RESULT_OK) { progressDialog.setTitle("Profile Image"); progressDialog.setMessage("Please wait, while we updating your profile image..."); progressDialog.show(); progressDialog.setCanceledOnTouchOutside(true); Uri resultUri = result.getUri(); final StorageReference filePath = UserProfileImageRef.child(cuserid + ".jpg"); UploadTask urlTask = filePath.putFile(resultUri); Task<Uri> urlTask1 = urlTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return filePath.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); downloadurl = downloadUri.toString(); Log.i("eroor", downloadUri.toString()); userRef.child("profileimage").setValue(downloadUri.toString()).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { // Intent selfIntent = new Intent(setup.this, setup.class); // startActivity(selfIntent); Toast.makeText(setup.this, "Profile Image stored to Firebase Database Successfully...", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); // intialize();// } else { String message = task.getException().getMessage(); Toast.makeText(setup.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } }); } else { // Handle failures // ... } } }); /*addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() { @Override public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) { if(task.isSuccessful()) { final UploadTask.TaskSnapshot snapshots = task.getResult(); Task<Uri> downloadUri = snapshots.getStorage().getDownloadUrl(); System.out.println("Upload " + downloadUri.toString()); progressDialog.dismiss(); userRef.child("profileimage").setValue(downloadUri) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { Intent selfIntent = new Intent(setup.this, setup.class); startActivity(selfIntent); Toast.makeText(setup.this, "Profile Image stored to Firebase Database Successfully...", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } else { String message = task.getException().getMessage(); Toast.makeText(setup.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } }); } } });*/ } else { Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } } public void sendToMain(View view) { Intent mainActitiyIntent = new Intent(setup.this, MainActivity.class); startActivity(mainActitiyIntent); finish(); } }
true
96f153fb10b220e108d857920a5f1133605806c3
Java
hokhyk/sso_web
/WEB-INF/lib/shr_sso_client_820.jar.src/com/kingdee/shr/sso/client/util/BASE64Encoder.java
UTF-8
2,707
1.945313
2
[]
no_license
/* */ package com.kingdee.shr.sso.client.util; /* */ /* */ public class BASE64Encoder /* */ { /* */ public static String encodeBuffer(byte[] bytes) { /* 6 */ char[] Base64Code = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 7 */ 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 8 */ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 9 */ '8', '9', '+', '/', '=' }; /* 10 */ byte empty = 0; /* 11 */ StringBuffer outmessage = new StringBuffer(); /* 12 */ int messageLen = bytes.length; /* 13 */ int page = messageLen / 3; /* 14 */ int use = 0; /* 15 */ if ((use = messageLen % 3) > 0) /* */ { /* */ /* 18 */ byte[] newbyte = new byte[messageLen + 3 - use]; /* */ /* 20 */ for (int i = 0; i < messageLen; i++) { /* 21 */ newbyte[i] = bytes[i]; /* */ } /* */ /* 24 */ for (int i = 0; i < 3 - use; i++) { /* 25 */ newbyte[(messageLen + i)] = empty; /* */ } /* 27 */ page++; /* 28 */ bytes = newbyte; /* */ } /* 30 */ outmessage = new StringBuffer(page * 4); /* 31 */ for (int i = 0; i < page; i++) /* */ { /* 33 */ byte[] instr = new byte[3]; /* 34 */ instr[0] = bytes[(i * 3)]; /* 35 */ instr[1] = bytes[(i * 3 + 1)]; /* 36 */ instr[2] = bytes[(i * 3 + 2)]; /* 37 */ int[] outstr = new int[4]; /* 38 */ outstr[0] = (instr[0] >>> 2 & 0x3F); /* 39 */ outstr[1] = ((instr[0] & 0x3) << 4 ^ instr[1] >>> 4 & 0xF); /* 40 */ if (instr[1] != empty) { /* 41 */ outstr[2] = ((instr[1] & 0xF) << 2 ^ instr[2] >>> 6 & 0x3); /* */ } else /* 43 */ outstr[2] = 64; /* 44 */ if (instr[2] != empty) { /* 45 */ outstr[3] = (instr[2] & 0x3F); /* */ } else { /* 47 */ outstr[3] = 64; /* */ } /* 49 */ outmessage.append(Base64Code[outstr[0]]); /* 50 */ outmessage.append(Base64Code[outstr[1]]); /* 51 */ outmessage.append(Base64Code[outstr[2]]); /* 52 */ outmessage.append(Base64Code[outstr[3]]); /* */ } /* 54 */ return outmessage.toString(); /* */ } /* */ } /* Location: F:\1 人力资源开发服务公司\53 集团人力系统管理员管维方案\SHR二开资料\单点登录-8.2及以上版本等\demo示例\第三方应用集成s-HR\sso_web\WEB-INF\lib\shr_sso_client_820.jar!\com\kingdee\shr\sso\client\util\BASE64Encoder.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
dbef4d315da608d75b60485203c819a434ca7172
Java
happy6eve/cap-other
/cap-metadata/src/main/java/com/comtop/cap/bm/metadata/base/model/SoaBaseType.java
UTF-8
1,210
2.34375
2
[]
no_license
/****************************************************************************** * Copyright (C) 2014 ShenZhen ComTop Information Technology Co.,Ltd * All Rights Reserved. * 本软件为深圳康拓普开发研制。未经本公司正式书面同意,其他任何个人、团体不得使用、 * 复制、修改或发布本软件. *****************************************************************************/ package com.comtop.cap.bm.metadata.base.model; /** * soa 基础枚举类型 * * @author 林玉千 * @since jdk1.6 * @version 2016-6-28 林玉千 */ public enum SoaBaseType { /** 实体 */ ENTITY_TYPE("entity"), /** 服务实体 */ SERVICEOBJECT_TYPE("serviceObject"); /** 枚举项对应的值 */ private String value; /** * 构造函数 * * @param value 枚举类型值 */ private SoaBaseType(String value) { this.value = value; } /** * @return 获取 value属性值 */ public String getValue() { return value; } /** * * @see java.lang.Enum#toString() */ @Override public String toString() { return this.value; } }
true
254c3de1971722211331d2d186e15667f1e6ff2d
Java
ycycchre/SA_Kanban2020
/SA1321/src/main/java/kanban/domain/adapter/repository/workflow/data/WorkflowData.java
UTF-8
687
2.1875
2
[]
no_license
package kanban.domain.adapter.repository.workflow.data; import java.util.List; public class WorkflowData { private String name; private String workflowId; private List<StageData> stageDatas; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public List<StageData> getStageDatas() { return stageDatas; } public void setStageDatas(List<StageData> stageDatas) { this.stageDatas = stageDatas; } }
true
e04acc12eeecbbd1c079ab3250799379ed9d4a7b
Java
yapingzhang/framework
/framework-dao/src/main/java/cn/bidlink/framework/dao/ibatis/MybatisConfig.java
UTF-8
1,827
2.296875
2
[]
no_license
package cn.bidlink.framework.dao.ibatis; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.core.io.Resource; import org.springframework.util.Assert; public class MybatisConfig extends SqlSessionFactoryBean { //加载所有module下的vo类为默认别名类 Resource[] aliasModuleClass ; public void setAliasModuleClass(Resource[] aliasModuleClass) { this.aliasModuleClass = aliasModuleClass; } /** * 加载所有module下的vo类为默认别名类 */ public void afterPropertiesSet() throws Exception { //先计算出当前class路径是生么 // String localPathName = this.getClass().getClassLoader().getResource("").getPath(); // if(localPathName!=null && localPathName.contains("%20")){ // localPathName = localPathName.replaceAll("%20", " "); // } //然后计算出该路径下的所有类 // Class[] classType = new Class[aliasModuleClass.length]; // if(aliasModuleClass!=null){ // for(int i=0;i<aliasModuleClass.length;i++){ // Resource re = aliasModuleClass[i]; // String classPath = re.getURI().getPath(); // if(classPath!=null && classPath.contains("%20")){ // classPath = classPath.replaceAll("%20", " "); // } // classPath = classPath.replace(localPathName, ""); // classPath = classPath.replaceAll("/", "."); // classPath = classPath.substring(0,classPath.lastIndexOf(".class")); // //最后生成类名放入数组中 // classType[i] = Class.forName(classPath); // } // } //把类名生成到mybatis的配置中 通过调用super这个对象方法 // super.setTypeAliases(classType); //setTypeAliasesPackage("cn.bidlink.baseInfo.user.model"); super.afterPropertiesSet(); } }
true
070a3a1556f928e2d215258bba483b10756a5103
Java
iuventaas/ImageProcessing
/src/Coder.java
UTF-8
6,914
2.984375
3
[]
no_license
import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; public class Coder { JFrame codingFrame = new JFrame("Кодирование"); BufferedImage img; private JButton codeBtn; private JButton decodeBtn; Font font = new Font("Verdana", Font.PLAIN, 11); JTextField alphabet; JTextField toDecodeStart; JTextField toDecodeEnd; JTextField toCode; public Coder() { JLabel label1 = new JLabel("Алфавит:"); label1.setBounds(5, 10, 120, 25); JLabel label2 = new JLabel("Закодировать:"); label2.setBounds(5, 40, 120, 25); JLabel label3 = new JLabel("Раскодировать:"); label3.setBounds(5, 70, 120, 25); alphabet = new JTextField(); toCode = new JTextField(); toDecodeStart = new JTextField(); toDecodeEnd = new JTextField(); alphabet.setBounds(130, 10, 250, 25); toCode.setBounds(130, 40, 250, 25); toDecodeStart.setBounds(130, 70, 250, 25); codingFrame.getContentPane().add(label1); codingFrame.getContentPane().add(label2); codingFrame.getContentPane().add(label3); codingFrame.getContentPane().add(alphabet); codingFrame.getContentPane().add(toCode); codingFrame.getContentPane().add(toDecodeStart); codeBtn = new JButton("code"); decodeBtn = new JButton("decode"); codeBtn.setBounds(30, 120, 100, 25); decodeBtn.setBounds(150, 120, 100, 25); codingFrame.getContentPane().add(decodeBtn); codingFrame.getContentPane().add(codeBtn); codingFrame.setSize(new Dimension(600, 200)); codingFrame.getContentPane().add(leftPanelGen()); codingFrame.getContentPane().setLayout(null); codingFrame.setVisible(true); } private JPanel leftPanelGen() { final JPanel leftPanel = new JPanel(new BorderLayout()); leftPanel.setBorder(BorderFactory.createEtchedBorder()); codeBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String toCodeStr = toCode.getText(); String alphabetStr = alphabet.getText() + "!"; if (alphabetStr.isEmpty()) { JOptionPane.showMessageDialog(codingFrame, "пустой алфавит"); return; } if (toCodeStr.isEmpty()) { JOptionPane.showMessageDialog(codingFrame, "пустая строка"); return; } if (toCodeStr.contains("!")) { JOptionPane.showMessageDialog(codingFrame, "! это стоп символ"); return; } if (!check(alphabetStr, toCodeStr)) { JOptionPane.showMessageDialog(codingFrame, "алфавит не включает все символы"); return; } else { double[] res = code(alphabetStr, toCodeStr + "!"); JTextArea result = new JTextArea("[" + res[0] + "; " + res[1] + ")"); JFrame resFrame = new JFrame("результат кодировки"); resFrame.add(result); resFrame.setSize(new Dimension(300, 100)); resFrame.setVisible(true); } } }); decodeBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { double start; String alphabetStr; try { start = Double.valueOf(toDecodeStart.getText()); alphabetStr = alphabet.getText() + "!"; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(codingFrame, "not a number"); return; } if (start < 0 || start > 1) { JOptionPane.showMessageDialog(codingFrame, "число должно попадать в [0;1]"); return; } StringBuffer res = decode(alphabetStr, start); JTextArea result = new JTextArea(res.toString()); JFrame resFrame = new JFrame("результат кодировки"); resFrame.add(result); resFrame.setSize(new Dimension(300, 100)); resFrame.setVisible(true); } }); return leftPanel; } private boolean check(String alphabet, String strToCode) { ArrayList<Character> chAlphabet = toChars(alphabet); for (int i = 0; i < strToCode.length(); i++) { char ch = strToCode.charAt(i); if (!chAlphabet.contains(ch)) return false; } return true; } private StringBuffer decode(String alphabet, double value) { StringBuffer res = new StringBuffer(); ArrayList<Character> chAlphabet = toChars(alphabet); double n = 1 / (double) chAlphabet.size(); res = decodeR(chAlphabet, res, value, n); return res; } private StringBuffer decodeR( ArrayList<Character> chAlphabet, StringBuffer res, double value, double n){ int k = (int) Math.floor(value / n); if (chAlphabet.get(k).equals('!')) return res; res.append(chAlphabet.get(k)); double codeN = (value - k * n) / n; decodeR(chAlphabet, res, codeN, n); return res; } private ArrayList<Character> toChars(String str) { ArrayList<Character> charList = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (!charList.contains(ch)) charList.add(ch); } return charList; } private double[] code(String alphabet, String strToCode) { ArrayList<Character> chAlphabet = toChars(alphabet); double n = 1 / (double) chAlphabet.size(); double[] interval = new double[2]; interval[0] = 0; interval[1] = 1; for (int i = 0; i < strToCode.length(); i++) { char ch = strToCode.charAt(i); int k = chAlphabet.indexOf(ch); double newHigh = interval[0] + (interval[1] - interval[0]) * (k + 1) * n; double newLow = interval[0] + (interval[1] - interval[0]) * k * n; interval[0] = newLow; interval[1] = newHigh; } return interval; } }
true
610e0859f56370346000b2900e6f70bbf9e75afd
Java
jomaribenito/DetectMe
/app/src/main/java/com/fsgtech/detectme/listeners/MyLocationListener.java
UTF-8
8,724
1.867188
2
[]
no_license
package com.fsgtech.detectme.listeners; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.widget.Toast; import com.fsgtech.detectme.RequestUserPermission; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; /** * Created by jomari on 10/20/2017. */ public class MyLocationListener implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener { private static final long UPDATE_INTERVAL = 10 * 1000; private static final long FASTEST_INTERVAL = 5 * 1000; private GoogleApiClient mGoogleApiClient; private Location mLocation; private LocationManager locationManager; private LocationRequest mLocationRequest; private PendingResult<LocationSettingsResult> result; private final static int REQUEST_LOCATION = 199; double longitude, latitude, accuracy; Activity activity; public static boolean loc = false; public MyLocationListener(Activity activity) { this.activity = activity; } @Override public void onConnected(@Nullable Bundle bundle) { toggleGPS(); startLocationUpdates(); getLocation(); } @Override public void onConnectionSuspended(int i) { Log.e("ERROR", "Connection Suspended"); connGAC(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.e("ERROR", "Connection failed. Error: " + connectionResult.getErrorCode()); } @Override public void onLocationChanged(Location location) { getLocation(); } public synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(activity) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } public void connGAC(){ mGoogleApiClient.connect(); } public void dconnGAC(){ if (mGoogleApiClient.isConnected()){ mGoogleApiClient.disconnect(); } } private void toggleGPS() { mLocationRequest = LocationRequest.create(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(UPDATE_INTERVAL); mLocationRequest.setFastestInterval(FASTEST_INTERVAL); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); builder.setAlwaysShow(true); result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); //final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. //... break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult( activity, REQUEST_LOCATION); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. //... break; } } }); } private void startLocationUpdates() { // Create the location request mLocationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(UPDATE_INTERVAL) .setFastestInterval(FASTEST_INTERVAL); // Request location updates if (ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } private void getLocation() { if (ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. RequestUserPermission requestUserPermission = new RequestUserPermission(activity); requestUserPermission.verifyLocationPermissions(); return; } mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLocation == null) { startLocationUpdates(); } if (mLocation != null) { latitude = mLocation.getLatitude(); longitude = mLocation.getLongitude(); accuracy = mLocation.getAccuracy(); // Toast.makeText(activity, "Location Detected", Toast.LENGTH_SHORT).show(); loc = true; } else { // Toast.makeText(activity, "Location not Detected", Toast.LENGTH_SHORT).show(); loc = false; } } public double getLatitude() { if (mLocation != null) { latitude = mLocation.getLatitude(); } // return latitude return latitude; } public double getLongitude() { if (mLocation != null) { longitude = mLocation.getLongitude(); } // return longitude return longitude; } public double getAccuracy() { if (mLocation != null) { accuracy = mLocation.getAccuracy(); } return accuracy; } }
true
fd5142199913f4a8d3590dcb9dc841239e3d2467
Java
xujia233/FirstTest
/src/main/java/common/ClassLoadTest.java
UTF-8
1,132
2.96875
3
[]
no_license
package common; import org.junit.Test; /** * Created by xujia on 2019/11/22 */ public class ClassLoadTest { public static void main(String[] args) { // 只会初始化定义该字段的类,不会初始化其子类 System.out.println(ChildClass.CONSTANTS); } @Test public void test01() { // 应用程序加载器,负责加载用户类路径上所指定的类库 System.out.println(ClassLoader.getSystemClassLoader()); } } class ParentClass { static { System.out.println("parent static init"); } // 被final修饰的静态字段不会触发当前类的初始化 // public static String CONSTANTS = "constants"; // 如果是常量,即被final static修饰的字段不会触发类的初始化,因为在编译阶段通过常量传播优化已经存入调用类的常量池中,本质上并没有直接引用到定义常量的类,因此不会触发该类的初始化 public static final String CONSTANTS = "constants"; } class ChildClass extends ParentClass { static { System.out.println("child static init"); } }
true
825967593177ccf7d7dd2e2ab41bea65de6a43aa
Java
xhyrzldf/leetcodeJava
/src/main/java/string/ValidPalindrome_125.java
UTF-8
1,711
3.9375
4
[]
no_license
package string; /** * Description : Given a string, determine if it is a palindrome, considering only alphanumeric * characters and ignoring cases. * <p> * <p>For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a * palindrome. * <p> * <p>Note: Have you consider that the string might be empty? This is a good question to ask during * an interview. * <p> * <p>For the purpose of this problem, we define empty string as valid palindrome. * <p> * <p>描述:给定一个字符串,确定它是否是一个回文,只考虑字母数字字符和并且忽略大小写的情况。 * <p> * <p>例如:“A man, a plan, a canal: Panama" is a palindrome.”是一个回文。“race a car”不是一个回文。 * <p> * <p>注意:你是否考虑过字符串可能是空的? * <p> * <p>为了解决这个问题,我们将空字符串定义为有效的回文。 * <p> * <p>Author : Matrix [xhyrzldf@foxmail.com] * <p> * <p>Date : 2017/10/10 23:37 */ public class ValidPalindrome_125 { public static void main(String[] args) { String input = "0123456789"; System.out.println(input.substring(3)); } public boolean isPalindrome(String s) { if (s.isEmpty()) { return true; } // 利用正则直接替换,虽然速度相比于直接用unicode码来找会有些慢,但是在可以允许的时间房范围内这样我觉得代码和时间都是很好的 s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); int n = s.length(); for (int i = 0; i < n / 2; i++) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } }
true
cf32bd8696abdf026e19c8d44a2b8f32ffe4de54
Java
zhanghaichaogit/spring-boot
/java-base-program/src/main/java/com/pro/base/controller/ErrorController.java
UTF-8
760
2
2
[]
no_license
package com.pro.base.controller; import com.pro.base.util.BaseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.Map; @Controller public class ErrorController extends WebBaseController { private final static Logger LOGGER = LoggerFactory.getLogger(ErrorController.class); /** * 404方法 */ @RequestMapping(value = "404", method = {RequestMethod.GET}, produces = BaseUtil.HTML) public String errorNotFound(Map<String, Object> model) { model.put("message", "访问链接不存在"); return "error_404"; } }
true
49d1df0b6e529bd692f5c59bbd78a62731913149
Java
psychobunnies/Psychobunnies
/Platformer/src/com/gravity/camera/PanningCamera.java
UTF-8
1,280
2.953125
3
[ "MIT" ]
permissive
package com.gravity.camera; import org.newdawn.slick.geom.Vector2f; import com.gravity.geom.Rect; import com.gravity.levels.UpdateCycling; /** A camera that pans at a constant rate */ public class PanningCamera implements Camera, UpdateCycling { private final float velX, velY; private final float delay; private final float height, width; private final float stopX, stopY; private float curX, curY; private float time; public PanningCamera(float delay, Vector2f start, Vector2f vel, Vector2f finish, float width, float height) { this.delay = delay; this.velX = -vel.x; this.velY = -vel.y; this.curX = -start.x; this.curY = -start.y; this.stopX = -finish.x; this.stopY = -finish.y; this.width = width; this.height = height; this.time = 0; } @Override public Rect getViewport() { return new Rect(curX, curY, width, height); } @Override public void finishUpdate(float millis) { time += millis; if (time > delay && curX >= stopX && curY >= stopY) { curX += millis * velX; curY += millis * velY; } } @Override public void startUpdate(float millis) { // No-op } }
true
973e87a57d2999109ba027c6d6c4b9083f9bf162
Java
hreflee/mis_sw1
/src/servlet/patientInfo.java
UTF-8
1,890
2.453125
2
[]
no_license
package servlet; import java.io.IOException; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import entity.Patient; import entity.User; /** * Servlet implementation class PatientInfo */ @WebServlet("/patientInfo") public class patientInfo extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public patientInfo() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); User user=new User("", "", ""); String id=URLDecoder.decode(request.getParameter("patientID"), "UTF-8"); Patient patient=user.queryPatientInfo(id); JSONObject jsonData=new JSONObject(); try { jsonData.put("patientID", patient.getPatient_id()); jsonData.put("name", patient.getPatient_name()); jsonData.put("sex", patient.getSex()); jsonData.put("birthday", patient.getBirthday()); response.getWriter().println(jsonData.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
true
500352f8a1044a2dd89cda7f2ed3857564f7a435
Java
cuba-labs/kafka-sample
/modules/core/src/com/company/kafkasample/service/KafkaSenderServiceBean.java
UTF-8
1,435
2.375
2
[]
no_license
package com.company.kafkasample.service; import com.haulmont.cuba.core.app.UniqueNumbersService; import org.slf4j.Logger; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.stereotype.Service; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; import javax.inject.Inject; @Service(KafkaSenderService.NAME) public class KafkaSenderServiceBean implements KafkaSenderService { @Inject private Logger log; @Inject private KafkaTemplate<Integer, String> template; @Inject private UniqueNumbersService uniqueNumbersService; @Override public void sendMessage(String message) { log.info("Sending {} using Kafka", message); long id = uniqueNumbersService.getNextNumber("users"); ListenableFuture<SendResult<Integer, String>> send = template.send("users", (int) id, message); send.addCallback(new ListenableFutureCallback<SendResult<Integer, String>>() { @Override public void onFailure(Throwable ex) { log.info("Failed to send message {}, error {}", message, ex.getMessage()); } @Override public void onSuccess(SendResult<Integer, String> result) { log.info("Message {} sent", message); } }); } }
true
278867bee9f29e36cf76057f57aaa72c7db92c8c
Java
wangjingf/idea-database-navigator
/src/com/dci/intellij/dbn/execution/explain/result/ui/ExplainPlanTreeTableCellRenderer.java
UTF-8
1,633
2.125
2
[ "Apache-2.0" ]
permissive
package com.dci.intellij.dbn.execution.explain.result.ui; import javax.swing.JComponent; import javax.swing.JTable; import java.awt.Component; import com.intellij.ui.treeStructure.treetable.TreeTable; import com.intellij.ui.treeStructure.treetable.TreeTableCellRenderer; import com.intellij.ui.treeStructure.treetable.TreeTableTree; public class ExplainPlanTreeTableCellRenderer extends TreeTableCellRenderer { private final TreeTableTree tree; public ExplainPlanTreeTableCellRenderer(TreeTable treeTable, TreeTableTree tree) { super(treeTable, tree); this.tree = tree; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int modelRow = table.convertRowIndexToModel(row); //TableModel model = myTreeTable.getModel(); //myTree.setTreeTableTreeBorder(hasFocus && model.getColumnClass(column).equals(TreeTableModel.class) ? myDefaultBorder : null); tree.setVisibleRow(modelRow); final Object treeObject = tree.getPathForRow(modelRow).getLastPathComponent(); boolean leaf = tree.getModel().isLeaf(treeObject); final boolean expanded = tree.isExpanded(modelRow); Component component = tree.getCellRenderer().getTreeCellRendererComponent(tree, treeObject, isSelected, expanded, leaf, modelRow, hasFocus); if (component instanceof JComponent) { table.setToolTipText(((JComponent)component).getToolTipText()); } //myTree.setCellFocused(false); return tree; } }
true
109474ecbe24f3471245f6e468b3efa61565982b
Java
a-ko0620/java_tst
/addressbook-web-tests/src/test/java/ru/spqr/addressbook/appmanager/ContactHelper.java
UTF-8
3,680
2.390625
2
[]
no_license
package ru.spqr.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import ru.spqr.addressbook.model.ContactCreation; import ru.spqr.addressbook.model.GroupData; import java.util.ArrayList; import java.util.List; public class ContactHelper extends HelperBase { public ContactHelper(WebDriver wd) { super(wd); } public void submitNewContact() { click(By.xpath("(//input[@name='submit'])[2]")); } public void fillingContactForms(ContactCreation contactCreation) { type(By.name("firstname"), contactCreation.getFirstName()); type(By.name("lastname"), contactCreation.getLastName()); type(By.name("nickname"), contactCreation.getNickName()); type(By.name("title"), contactCreation.getTitle()); type(By.name("company"), contactCreation.getCompany()); type(By.name("address"), contactCreation.getAddress()); type(By.name("home"), contactCreation.getHome()); type(By.name("mobile"), contactCreation.getMobile()); type(By.name("work"), contactCreation.getWork()); type(By.name("fax"), contactCreation.getFax()); type(By.name("email"), contactCreation.getEmail()); type(By.name("homepage"), contactCreation.getHomePage()); select(By.name("bday"), contactCreation.getBirthDay()); select(By.name("bmonth"), contactCreation.getBirthMonth()); type(By.name("byear"), contactCreation.getBirthYear()); type(By.name("address2"), contactCreation.getAddress2()); type(By.name("phone2"), contactCreation.getPhone()); type(By.name("notes"), contactCreation.getNotes()); } public void initContactCreation() { click(By.linkText("add new")); } public void selectContact(int index) { wd.findElements(By.name("name=selected[]")).get(index).click(); } public void deleteContact() { click(By.xpath("//input[@value='Delete']")); } public void initContactModification() { click(By.xpath("//img[@alt='Edit']")); } public void submitContactModification() { click(By.name("update")); } public void returnToContactsPage() { click(By.linkText("home page")); } public boolean isThereAContact() { return isElementPresent(By.name("selected[]")); } public void createContact(ContactCreation contact) { initContactCreation(); fillingContactForms(contact); submitNewContact(); returnToContactsPage(); } public int getContactCount() { return wd.findElements(By.name("selected[]")).size(); } public List<ContactCreation> getContactList() { List<ContactCreation> contacts = new ArrayList<ContactCreation>(); List<WebElement> line = wd.findElements(By.cssSelector("tr[name = entry]")); for (WebElement element : line) { List<WebElement> elements = element.findElements(By.tagName("td")); String firstName = elements.get(2).getText(); String lastName = elements.get(1).getText(); ContactCreation contact = new ContactCreation(firstName, lastName, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); contacts.add(contact); } return contacts; } }
true
618d46d3ba0831f7e2ae3373b2e1f5bd5b37c23b
Java
Romern/gms_decompiled
/sources/com/google/android/gms/wallet/intentoperation/p083ib/ReportFacilitatedTransactionChimeraIntentOperation.java
UTF-8
1,961
1.53125
2
[]
no_license
package com.google.android.gms.wallet.intentoperation.p083ib; import android.accounts.Account; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.chimera.IntentOperation; import com.google.android.gms.wallet.shared.BuyFlowConfig; /* renamed from: com.google.android.gms.wallet.intentoperation.ib.ReportFacilitatedTransactionChimeraIntentOperation */ /* compiled from: :com.google.android.gms@201515033@20.15.15 (120300-306758586) */ public class ReportFacilitatedTransactionChimeraIntentOperation extends IntentOperation { /* renamed from: a */ public awgj f110273a; /* renamed from: b */ private awpg f110274b; public ReportFacilitatedTransactionChimeraIntentOperation() { } public final void onCreate() { awgj awgj = new awgj(rpr.m34216b().getRequestQueue()); this.f110274b = new awpg(this, "ReportTxnIntentOp"); this.f110273a = awgj; } public final void onHandleIntent(Intent intent) { BuyFlowConfig buyFlowConfig = (BuyFlowConfig) sef.m35067a(intent, "com.google.android.gms.wallet.buyFlowConfig", BuyFlowConfig.CREATOR); bxvd da = blwc.f127918c.mo74144da(); bxtx a = bxtx.m123261a(intent.getByteArrayExtra("com.google.android.gms.wallet.service.ib.ReportFacilitatedTransactionChimeraIntentOperation.transactionCompletionToken")); if (da.f164950c) { da.mo74035c(); da.f164950c = false; } blwc blwc = (blwc) da.f164949b; a.getClass(); blwc.f127920a |= 2; blwc.f127921b = a; Account account = buyFlowConfig.f110418b.f110407b; Log.i("ReportTxnIntentOp", "Reported facilitated transaction."); this.f110274b.mo52446a(new awnc(this, account, buyFlowConfig, (blwc) da.mo74062i())); } public ReportFacilitatedTransactionChimeraIntentOperation(Context context) { attachBaseContext(context); } }
true
2629b041dd408786058a871ea9ac6482fc7590ae
Java
OuadiBelmokhtar/ocp8-cert-code-training
/src/chap06/generics/AnimalHolder.java
UTF-8
1,631
3.875
4
[]
no_license
package chap06.generics; //public class AnimalHolder<T extends Animal> public class AnimalHolder<T> { // using T is correct. It wont mean the same T declared in the class static <U> void staticMtd(U t) { } // Overloaded version static <U> void staticMtd(U[] t) { } public static void main(String[] args) { AnimalHolder.staticMtd(new Dog()); // (Dog) version Dog[] dogs = new Dog[3]; AnimalHolder.staticMtd(dogs); // (Dog[]) version AnimalHolder<Dog> ahd = AnimalHolder.getMe(new Dog()); AnimalHolder<Dog> ah = new AnimalHolder<Dog>(); ah.notStaticMtd(new Dog());// OK // // The method staticMtd(Dog) is undefined for the type AnimalHolder // AnimalHolder.staticMtd(new Dog()); // KO } static <U> AnimalHolder<U> getMe(U u) { System.out.println("preparing " + u); return new AnimalHolder<U>(); } static <U> AnimalHolder<U> getMe(U[] u) { System.out.println("preparing " + u); return new AnimalHolder<U>(); } // Cannot make a static reference to the non-static type T static void staticMtd(T t) { } void notStaticMtd(T p) { } T a; T b = new T(); // Cannot instantiate the type T static T s; // Cannot make a static reference to the non-static type T T[] arr1; // OK T[] arr2 = new T[3]; // Cannot create a generic array of T void m1(T p) { if (p instanceof T) { // Cannot perform instanceof check against type parameter T. Use its erasure // Object instead since further generic type information will be erased at // runtime } } // public <T super Animal> T doSomeThing(T o) { // // Syntax error on token "super", , expected // T t = o; // return t; // } }
true
955a063e262b14698db91d5bca2b941bc0159f4f
Java
sinokaba/OR3
/main/java/HomeUI.java
UTF-8
3,266
2.71875
3
[]
no_license
import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; public class HomeUI { AutoCompleteTextField locationSearchField, restaurantSearchField; DropdownMenu searchDropdown; Button searchBtn; private DBConnection db; private GoogleMapsService mapsApi; GridPane layout; public HomeUI(boolean loggedInUser, DBConnection db, GoogleMapsService api){ layout = new GridPane(); layout.getStyleClass().add("bg-image"); this.db = db; mapsApi = api; Label mainTitle = new Label("OR3"); mainTitle.getStyleClass().add("title"); mainTitle.setAlignment(Pos.TOP_CENTER); layout.add(mainTitle, 1, 0); HBox searchWrap = createSearchBar(layout); layout.add(searchWrap, 1, 1); HBox hbBtn = new HBox(30); hbBtn.setAlignment(Pos.CENTER); layout.add(hbBtn, 1, 6); layout.setAlignment(Pos.CENTER); layout.setHgap(10); layout.setVgap(10); } public HBox createSearchBar(GridPane grid){ //pane is empty, acts as buffer for layout other elements Pane buffer = new Pane(); grid.add(buffer, 2, 0); createSearchOptions(); locationSearchField = new AutoCompleteTextField("US state or city :).", 300, 44); locationSearchField.autocomplete("cities", null, mapsApi); //restaurantSearchField = new AutoCompleteTextField("of Restaurant...", 420, 44); restaurantSearchField = new AutoCompleteTextField("Restaurant name or keyword.", 420, 44); restaurantSearchField.autocomplete(null, db, null); searchBtn = new Button("Search"); searchBtn.getStyleClass().addAll("main-button", "search-button"); searchBtn.defaultButtonProperty().bind(Bindings.or( locationSearchField.focusedProperty(), restaurantSearchField.focusedProperty())); //hbox lays out its children in a single row, for formatting HBox searchWrap = new HBox(3); //searchWrap.getChildren().add(searchDropdown); searchWrap.getChildren().addAll(restaurantSearchField, locationSearchField, searchBtn); return searchWrap; } public void createSearchOptions(){ ObservableList<String> searchChoices = FXCollections.observableArrayList( "Name", "Type", "Food", "Keyword" ); searchDropdown = new DropdownMenu(null, 4, searchChoices, 0, 0, true); searchDropdown.addClass("main-search-dropdown"); searchDropdown.setOnAction((e) -> { String currentSelectedItem = searchDropdown.getSelectionModel().getSelectedItem().toString(); if(currentSelectedItem.equals("Name") || currentSelectedItem.equals("Type")){ restaurantSearchField.setPromptText("of Restaurant..."); } else if(currentSelectedItem.equals("Food")){ restaurantSearchField.setPromptText("called or category..."); } else{ restaurantSearchField.setPromptText("for whatever I feel like..."); } }); } public void clearFields(){ locationSearchField.clear(); restaurantSearchField.clear(); } }
true
68a275ad27454fc05f61c3157d3bf64147374ebd
Java
svn2github/csjxing_corner
/code/biz/common/src/main/java/com/doucome/corner/biz/dal/dataobject/dcome/DcExchangeItemDO.java
GB18030
2,815
1.78125
2
[]
no_license
package com.doucome.corner.biz.dal.dataobject.dcome; import java.math.BigDecimal; import java.util.Date; import com.doucome.corner.biz.dal.model.AbstractModel; /** * ֶһƷDO * @author ze2200 * */ public class DcExchangeItemDO extends AbstractModel { private static final long serialVersionUID = 1L; private Long id; private Long itemId; private String itemTitle; private BigDecimal itemPrice; private String itemPictures; private Integer exIntegral; private Integer exCount; private String itemType; private Integer exSuccCount = 0; /** * һ */ private String exType ; /** * Ҫֶ */ private String requireFields ; private Long userId; private Date gmtModified; private Date gmtCreate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getItemId() { return itemId; } public void setItemId(Long itemId) { this.itemId = itemId; } public String getItemTitle() { return itemTitle; } public void setItemTitle(String itemTitle) { this.itemTitle = itemTitle; } public BigDecimal getItemPrice() { return itemPrice; } public void setItemPrice(BigDecimal itemPrice) { this.itemPrice = itemPrice; } public String getItemPictures() { return itemPictures; } public void setItemPictures(String itemPictures) { this.itemPictures = itemPictures; } public Integer getExIntegral() { return exIntegral; } public void setExIntegral(Integer exIntegral) { this.exIntegral = exIntegral; } public void setExCount(Integer exCount) { this.exCount = exCount; } public String getItemType() { return itemType; } public void setItemType(String itemType) { this.itemType = itemType; } public Integer getExCount() { return this.exCount; } public Integer getExSuccCount() { return exSuccCount; } public void setExSuccCount(Integer exSuccCount) { this.exSuccCount = exSuccCount; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public String getExType() { return exType; } public void setExType(String exType) { this.exType = exType; } public String getRequireFields() { return requireFields; } public void setRequireFields(String requireFields) { this.requireFields = requireFields; } }
true
338e6e5e165487e61a08b2a3a3bdca692b4fddfc
Java
dleorb0816/project
/fun_mymodel4/src/main/java/com/exam/controller/admin/notice/AdminNoticeModifyFormController.java
UHC
1,719
2.1875
2
[]
no_license
package com.exam.controller.admin.notice; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.exam.controller.Controller; import com.exam.dao.NoticeAttachMyBatisDao; import com.exam.dao.NoticeMyBatisDao; import com.exam.vo.NoticeAttachVo; import com.exam.vo.NoticeVo; public class AdminNoticeModifyFormController implements Controller { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("AdminNoticeModifyFormController...."); // HttpSession session = request.getSession(); // α Ȯ String id = (String) session.getAttribute("id"); if (id == null) { return "redirect:/adminNoticeBoard.do"; } // ĶͰ pageNum int num = Integer.parseInt(request.getParameter("num")); String pageNum = request.getParameter("pageNum"); // DAO غ NoticeMyBatisDao noticeDao = NoticeMyBatisDao.getInstance(); NoticeAttachMyBatisDao attachDao = NoticeAttachMyBatisDao.getInstance(); // ۹ȣ num شϴ ۳ VO NoticeVo noticeVo = noticeDao.getNoticeByNum(num); // ۹ȣ num شϴ ÷ Ʈ List<NoticeAttachVo> noticeAttachList = attachDao.getAttachesByNoNum(num); // (jsp) ʿ request ü request.setAttribute("pageNum", pageNum); request.setAttribute("noticeAttachList", noticeAttachList); request.setAttribute("noticeVo", noticeVo); return "admin/noticeModifyForm"; } }
true
114c74a0cb562e3b8ed50ae7a6475e91609615f3
Java
poshjosh/bcuiappbase
/src/main/java/com/bc/appbase/xls/SheetProcessorContext.java
UTF-8
1,601
1.875
2
[]
no_license
/* * Copyright 2017 NUROX Ltd. * * Licensed under the NUROX Ltd Software License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.looseboxes.com/legal/licenses/software.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bc.appbase.xls; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import jxl.Cell; import jxl.Sheet; /** * @author Chinomso Bassey Ikwuagwu on Jun 2, 2017 2:12:25 PM */ public interface SheetProcessorContext { Consumer<Sheet> getSheetRowToEntityProcessor( Sheet sheet, BiConsumer<Cell[], List> rowResultHandler, BiConsumer<Cell, Exception> cellExceptionHandler, BiConsumer<Cell[], Exception> rowExceptionHandler, Consumer<Sheet> outputIfNone); MatchExcelToDatabaseColumnsPrompt getMatchExcelToDatabaseColumnsPrompt(); Function<List<CellResult>, List> getEntityListFromRowResultsBuilder(Class entityType); SelectFileThenWorksheetPrompt getSelectFileThenWorksheetPrompt(); SheetToDatabaseMetaDataBuilder getSheetToDatabaseMetaDataBuilder(); <R> SheetProcessorBuilder<R> getSheetProcessorBuilder(Class<R> rowResultType); }
true
12526ebb3e74779a3c4577a9e012893be1b261b5
Java
lisunshine1234/furniture
/src/main/java/com/lzy/furniture/service/impl/NavigationServiceImpl.java
UTF-8
4,116
2.140625
2
[]
no_license
package com.lzy.furniture.service.impl; import com.lzy.furniture.config.redis.RedisService; import com.lzy.furniture.entity.NavigationChild; import com.lzy.furniture.entity.NavigationFather; import com.lzy.furniture.repository.NavigationChildRepository; import com.lzy.furniture.repository.NavigationFatherRepository; import com.lzy.furniture.repository.ProductRepository; import com.lzy.furniture.service.NavigationService; import org.hibernate.pretty.MessageHelper; import org.omg.CosNaming.NameHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Set; @Service public class NavigationServiceImpl implements NavigationService { @Autowired private NavigationFatherRepository navigationFatherRepository; @Autowired private NavigationChildRepository navigationChildRepository; @Autowired private RedisService redisService; @Autowired private ProductRepository productRepository; @Override public List<NavigationFather> getNavigationList() { List<NavigationFather> navigationFatherList; if (redisService.hasKey("furniture:navigation:all")) { navigationFatherList = (List<NavigationFather>) redisService.get("furniture:navigation:all"); } else { navigationFatherList = navigationFatherRepository.findAll(); redisService.set("furniture:navigation:all", navigationFatherList, 1800); } return navigationFatherList; } @Override public List<NavigationChild> getNavigationChildList(Integer fatherId) { return navigationChildRepository.findAllByFatherId(fatherId); } @Override public List<NavigationChild> getNavigationChildListByChildId(Set<Integer> childIdList) { return navigationChildRepository.findAllByIdIn(childIdList); } @Override public List<NavigationChild> getNavigationFatherChild() { List<NavigationChild> navigationChildList = navigationChildRepository.findAll(); List<NavigationFather> navigationFatherList = navigationFatherRepository.findAll(); List<NavigationChild> list = new ArrayList<NavigationChild>(); for (NavigationChild navigationChild : navigationChildList) { for (NavigationFather navigationFather : navigationFatherList) { if (navigationChild.getFatherId().equals(navigationFather.getId())) { navigationChild.setFatherName(navigationFather.getNaviName()); list.add(navigationChild); break; } } } return list; } @Override public List<NavigationChild> getNavigationChildList() { return navigationChildRepository.findAll(); } @Override public boolean addNavigationFather(NavigationFather navigationFather) { redisService.del("furniture:navigation:all"); navigationFatherRepository.save(navigationFather); return true; } @Override public boolean addNavigationChild(NavigationChild navigationChild) { redisService.del("furniture:navigation:all"); navigationChildRepository.save(navigationChild); return true; } @Override public boolean deleteNavigationFather(Integer fatherId) { if (productRepository.findAllByFatherId(fatherId).size() > 0) { return false; } else if (navigationChildRepository.findAllByFatherId(fatherId).size() > 0) { return false; } else { redisService.del("furniture:navigation:all"); navigationFatherRepository.deleteById(fatherId); return true; } } @Override public boolean deleteNavigationChild(Integer childId) { if (productRepository.findAllByChildId(childId).size() > 0) { return false; } else { redisService.del("furniture:navigation:all"); navigationChildRepository.deleteById(childId); return true; } } }
true
66b893186ea2c699090cc44559af5254dcda6e91
Java
Alex-Fenris/Magi-World
/src/com/Fenris/MagiWorld/Game/MagiWorld.java
UTF-8
2,984
3.515625
4
[]
no_license
package com.Fenris.MagiWorld.Game; import com.Fenris.MagiWorld.Personnages.Guerrier; import com.Fenris.MagiWorld.Personnages.Mage; import com.Fenris.MagiWorld.Personnages.Personage; import com.Fenris.MagiWorld.Personnages.Rodeur; import com.Fenris.MagiWorld.Tools.Tools; import java.util.Scanner; /** * @author AlexFenris */ public class MagiWorld { public MagiWorld() { // For receive the values with the keyboard this.scan = new Scanner(System.in); // Initialization of 2 personages this.players = new Personage[2]; // Choices the Personage type for (int i=0 ; i<this.players.length ; i++) this.players[i] = choiceOfPersonage("Joueur " + (i+1)); } /** * Choix du personnage * Objet contenant le nom du personnage * Objet contenant le personnage choisit */ private Personage choiceOfPersonage(String name) { // Displays the terminal messages System.out.println("Création du personnage du " + name); System.out.println("Veuillez choisir la classe de votre peronnage (1 : Guerrier, 2 : Rôdeur, 3 : Mage)"); // Gets back the choice. It must be in the range [1 ; 3] int choice = Tools.askToUser(this.scan, 1, 3); Personage personage = null; switch (choice) { case 1: personage = new Guerrier(name); break; case 2: personage = new Rodeur(name); break; case 3: personage = new Mage(name); break; } return personage; } /** * Starts du jeu MagiWorld */ public void run() { // Useful variable int choice = -1; // Infinite loop with a condition to exit while (true) { for (int i=0 ; i<this.players.length ; i++) { // Displays the terminal messages System.out.println(this.players[i].getName() + " (" + this.players[i].getVitality() + ") " + "veuillez choisir une action (1 : Attaque Basique, 2 : Attaque Spéciale)"); // Gets back the choice. It must be in the range [1 ; 2] choice = Tools.askToUser(this.scan, 1, 2); if (choice == 1) this.players[i].throwBasicAttack(this.players[i==0 ? 1 : 0]); else this.players[i].throwSpecialAttack(this.players[i==0 ? 1 : 0]); // Displays a terminal message that says the name of the looser if (this.players[i==0 ? 1 : 0].getVitality() == 0) { System.out.println(this.players[i==0 ? 1 : 0].getName() + " a perdu !"); return; } } } } //--------------------------------------------------------------------------------------------- private Scanner scan; private Personage[] players; }
true
945d7172525959d87079b3b8448bd46fd4e231f9
Java
BarberaRyan/intro-to-compsci
/lab4/src/problem5/Main.java
UTF-8
1,648
3.453125
3
[]
no_license
package problem5; public class Main { public static void main(String[] args){ Ant TomBrady = new Thrower(); Ant SillyPeasant = new Harvester(); Bee UnstoppableJuggernaut = new Bee(); //Getting a place for the ants to be, the bee has a starting place already at 1,1, also giving silly peasant a food use int[] lamePlace = {0,0}; int[] coolPlace = {2,2}; SillyPeasant.setfoodUse(9999); TomBrady.setLocation(coolPlace); SillyPeasant.setLocation(lamePlace); System.out.println(TomBrady.toString()); System.out.println(""); // Testing the Bee move System.out.println(UnstoppableJuggernaut.insectToString()); UnstoppableJuggernaut.beeMove(); System.out.println("Juggernaut has moved"); System.out.println(UnstoppableJuggernaut.insectToString()); System.out.println(""); //Testing the isAnt, quality System.out.println("Testing is ant, first is tom brady, second is the juggernaut"); System.out.println(Boolean.toString(TomBrady.isAnt())); System.out.println(Boolean.toString(UnstoppableJuggernaut.isAnt())); System.out.println(""); //Testing the Bee attack UnstoppableJuggernaut.sting(SillyPeasant); UnstoppableJuggernaut.sting(TomBrady); System.out.println(TomBrady.toString()); System.out.println(SillyPeasant.toString()); System.out.println(""); //Testing Tom Brady's award winning touch down toss //For some reason, throws at does not work for ants, even though tom brady is a thrower System.out.println("This is the end for you"); ((Thrower) TomBrady).throwsAt(UnstoppableJuggernaut); System.out.println(UnstoppableJuggernaut.insectToString()); } }
true
ca0df6782716a45cbde2d3a1a538198379b1ea63
Java
prbqb/springboot
/prb-spring-all/prb-mybatis-plus/src/main/java/com/prb/service/UserLockService.java
UTF-8
466
1.546875
2
[]
no_license
package com.prb.service; import com.baomidou.mybatisplus.extension.service.IService; import com.prb.entity.User; public interface UserLockService extends IService<User> { Integer upUserByTx(User user); Integer upUserForOptimistic(Long userId); Integer upUserForPessimistic(Long userId); Integer upUserAgeForNormal(Long userId); Integer upUserDecrAgeNormal(Long userId); Integer upUserDecrAgeDelay(Long userId); }
true
6adf4b07562f5d8bd8f98488ef7b8007f19b1b9c
Java
herozhi0821/Activiti7Boot
/src/main/java/com/example/activiti7boot/security/hander/MyAuthenctiationInvalidSessionStrategy.java
UTF-8
1,272
2.0625
2
[]
no_license
package com.example.activiti7boot.security.hander; import com.example.activiti7boot.common.msgreturn.ResultCode; import com.example.activiti7boot.common.msgreturn.ResultGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.web.session.InvalidSessionStrategy; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * session到期 * @author ZhiPengyu * */ @Component public class MyAuthenctiationInvalidSessionStrategy implements InvalidSessionStrategy{ private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired ResultGenerator resultGenerator; @Override public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logger.info("session到期!"); response.setContentType("application/json;charset=UTF-8"); // response.setStatus(HttpStatus.BAD_REQUEST.value()); response.getWriter().write(resultGenerator.getFreeResult(ResultCode.SESSION_EXPIRES).toString()); } }
true
1969a77c2c3627231050ed44af661c584c1ca702
Java
AY1920S1-CS2113T-W13-3/main
/src/test/java/sgtravel/model/planning/RecommendationTest.java
UTF-8
710
2.3125
2
[ "MIT" ]
permissive
package sgtravel.model.planning; import org.junit.jupiter.api.Test; import sgtravel.ModelStub; import sgtravel.commons.exceptions.FileLoadFailException; import sgtravel.commons.exceptions.RecommendationFailException; import sgtravel.model.Model; import static org.junit.jupiter.api.Assertions.assertThrows; class RecommendationTest { @Test void testMakeItinerary() throws FileLoadFailException { Model model = new ModelStub(); Recommendation recommendation = model.getRecommendations(); String[] itineraryDetails = {"itinerary ", "23/04/28", "24/05/28"}; assertThrows(RecommendationFailException.class, () -> recommendation.makeItinerary(itineraryDetails)); } }
true
d2f04f6445dd3df9eed9e53ba5d3d98c7a172035
Java
gmstrbytes/geode
/geode-apis-compatible-with-redis/src/integrationTest/java/org/apache/geode/redis/internal/executor/set/AbstractSPopIntegrationTest.java
UTF-8
7,898
2.21875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.redis.internal.executor.set; import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_INTEGER; import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.Protocol; import org.apache.geode.redis.RedisIntegrationTest; import org.apache.geode.test.awaitility.GeodeAwaitility; public abstract class AbstractSPopIntegrationTest implements RedisIntegrationTest { private JedisCluster jedis; private static final int REDIS_CLIENT_TIMEOUT = Math.toIntExact(GeodeAwaitility.getTimeout().toMillis()); @Before public void setUp() { jedis = new JedisCluster(new HostAndPort("localhost", getPort()), REDIS_CLIENT_TIMEOUT); } @After public void tearDown() { flushAll(); jedis.close(); } @Test public void givenKeyNotProvided_returnsWrongNumberOfArgumentsError() { assertThatThrownBy(() -> jedis.sendCommand("key", Protocol.Command.SPOP)) .hasMessageContaining("ERR wrong number of arguments for 'spop' command"); } @Test public void givenMoreThanThreeArguments_returnsSyntaxError() { assertThatThrownBy( () -> jedis.sendCommand("key", Protocol.Command.SPOP, "key", "NaN", "extraArg")) .hasMessageContaining(ERROR_SYNTAX); } @Test public void givenCountIsNotAnInteger_returnsNotIntegerError() { assertThatThrownBy(() -> jedis.sendCommand("key", Protocol.Command.SPOP, "key", "NaN")) .hasMessageContaining(ERROR_NOT_INTEGER); } @Test public void testSPop() { int ENTRIES = 10; List<String> masterSet = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { masterSet.add("master-" + i); } jedis.sadd("master", masterSet.toArray(new String[] {})); String poppy = jedis.spop("master"); masterSet.remove(poppy); assertThat(jedis.smembers("master").toArray()).containsExactlyInAnyOrder(masterSet.toArray()); assertThat(jedis.spop("spopnonexistent")).isNull(); } @Test public void testSPopAll() { int ENTRIES = 10; List<String> masterSet = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { masterSet.add("master-" + i); } jedis.sadd("master", masterSet.toArray(new String[] {})); Set<String> popped = jedis.spop("master", ENTRIES); assertThat(jedis.smembers("master").toArray()).isEmpty(); assertThat(popped.toArray()).containsExactlyInAnyOrder(masterSet.toArray()); } @Test public void testSPopAllPlusOne() { int ENTRIES = 10; List<String> masterSet = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { masterSet.add("master-" + i); } jedis.sadd("master", masterSet.toArray(new String[] {})); Set<String> popped = jedis.spop("master", ENTRIES + 1); assertThat(jedis.smembers("master").toArray()).isEmpty(); assertThat(popped.toArray()).containsExactlyInAnyOrder(masterSet.toArray()); } @Test public void testSPopAllMinusOne() { int ENTRIES = 10; List<String> masterSet = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { masterSet.add("master-" + i); } jedis.sadd("master", masterSet.toArray(new String[] {})); Set<String> popped = jedis.spop("master", ENTRIES - 1); assertThat(jedis.smembers("master").toArray()).hasSize(1); assertThat(popped).hasSize(ENTRIES - 1); assertThat(masterSet).containsAll(popped); } @Test public void testManySPops() { int ENTRIES = 100; List<String> masterSet = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { masterSet.add("master-" + i); } jedis.sadd("master", masterSet.toArray(new String[] {})); List<String> popped = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { popped.add(jedis.spop("master")); } assertThat(jedis.smembers("master")).isEmpty(); assertThat(popped.toArray()).containsExactlyInAnyOrder(masterSet.toArray()); assertThat(jedis.spop("master")).isNull(); } @Test public void testConcurrentSPops() throws InterruptedException { int ENTRIES = 1000; List<String> masterSet = new ArrayList<>(); for (int i = 0; i < ENTRIES; i++) { masterSet.add("master-" + i); } jedis.sadd("master", masterSet.toArray(new String[] {})); List<String> popped1 = new ArrayList<>(); Runnable runnable1 = () -> { for (int i = 0; i < ENTRIES / 2; i++) { popped1.add(jedis.spop("master")); } }; List<String> popped2 = new ArrayList<>(); Runnable runnable2 = () -> { for (int i = 0; i < ENTRIES / 2; i++) { popped2.add(jedis.spop("master")); } }; Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2); thread1.start(); thread2.start(); thread1.join(); thread2.join(); assertThat(jedis.smembers("master")).isEmpty(); popped1.addAll(popped2); assertThat(popped1.toArray()).containsExactlyInAnyOrder(masterSet.toArray()); } @Test public void testSPopWithOutCount_shouldReturnNil_givenEmptySet() { Object result = jedis.sendCommand("noneSuch", Protocol.Command.SPOP, "noneSuch"); assertThat(result).isNull(); } @Test public void testSPopWithCount_shouldReturnEmptyList_givenEmptySet() { Set<String> result = jedis.spop("noneSuch", 2); assertThat(result).isEmpty(); } @Test public void testSPopWithCountOfOne_shouldReturnList() { jedis.sadd("set", "one"); Object actual = jedis.sendCommand("set", Protocol.Command.SPOP, "set", "1"); assertThat(actual).isInstanceOf(List.class); } @Test public void testSPopWithoutCount_shouldNotReturnList() { jedis.sadd("set", "one"); Object actual = jedis.sendCommand("set", Protocol.Command.SPOP, "set"); assertThat(actual).isNotInstanceOf(List.class); } @Test public void testSPopWithCountZero_shouldReturnEmptyList() { jedis.sadd("set", "one"); Set<String> result = jedis.spop("set", 0); assertThat(result).isEmpty(); } @Test public void testSPopWithoutArg_shouldReturnBulkString() throws Exception { jedis.sadd("set", "one"); try (Socket redisSocket = new Socket("localhost", getPort())) { byte[] rawBytes = new byte[] { '*', '2', 0x0d, 0x0a, '$', '4', 0x0d, 0x0a, 'S', 'P', 'O', 'P', 0x0d, 0x0a, '$', '3', 0x0d, 0x0a, 's', 'e', 't', 0x0d, 0x0a, }; redisSocket.getOutputStream().write(rawBytes); byte[] inputBuffer = new byte[1024]; int n = redisSocket.getInputStream().read(inputBuffer); String result = new String(Arrays.copyOfRange(inputBuffer, 0, n)); assertThat(result).isEqualTo("$3\r\none\r\n"); } } }
true
9b6cf506f27d82a33b9b9769aae425a38826dc29
Java
xuzh01/shopping
/src/main/java/cn/edu/jxufe/shopping/entity/AdvertisementExample.java
UTF-8
23,401
2.3125
2
[]
no_license
package cn.edu.jxufe.shopping.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class AdvertisementExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private Integer limit; private Long offset; public AdvertisementExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getLimit() { return limit; } public void setOffset(Long offset) { this.offset = offset; } public Long getOffset() { return offset; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andAdvIdIsNull() { addCriterion("adv_id is null"); return (Criteria) this; } public Criteria andAdvIdIsNotNull() { addCriterion("adv_id is not null"); return (Criteria) this; } public Criteria andAdvIdEqualTo(Integer value) { addCriterion("adv_id =", value, "advId"); return (Criteria) this; } public Criteria andAdvIdNotEqualTo(Integer value) { addCriterion("adv_id <>", value, "advId"); return (Criteria) this; } public Criteria andAdvIdGreaterThan(Integer value) { addCriterion("adv_id >", value, "advId"); return (Criteria) this; } public Criteria andAdvIdGreaterThanOrEqualTo(Integer value) { addCriterion("adv_id >=", value, "advId"); return (Criteria) this; } public Criteria andAdvIdLessThan(Integer value) { addCriterion("adv_id <", value, "advId"); return (Criteria) this; } public Criteria andAdvIdLessThanOrEqualTo(Integer value) { addCriterion("adv_id <=", value, "advId"); return (Criteria) this; } public Criteria andAdvIdIn(List<Integer> values) { addCriterion("adv_id in", values, "advId"); return (Criteria) this; } public Criteria andAdvIdNotIn(List<Integer> values) { addCriterion("adv_id not in", values, "advId"); return (Criteria) this; } public Criteria andAdvIdBetween(Integer value1, Integer value2) { addCriterion("adv_id between", value1, value2, "advId"); return (Criteria) this; } public Criteria andAdvIdNotBetween(Integer value1, Integer value2) { addCriterion("adv_id not between", value1, value2, "advId"); return (Criteria) this; } public Criteria andAdvTitleIsNull() { addCriterion("adv_title is null"); return (Criteria) this; } public Criteria andAdvTitleIsNotNull() { addCriterion("adv_title is not null"); return (Criteria) this; } public Criteria andAdvTitleEqualTo(String value) { addCriterion("adv_title =", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleNotEqualTo(String value) { addCriterion("adv_title <>", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleGreaterThan(String value) { addCriterion("adv_title >", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleGreaterThanOrEqualTo(String value) { addCriterion("adv_title >=", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleLessThan(String value) { addCriterion("adv_title <", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleLessThanOrEqualTo(String value) { addCriterion("adv_title <=", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleLike(String value) { addCriterion("adv_title like", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleNotLike(String value) { addCriterion("adv_title not like", value, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleIn(List<String> values) { addCriterion("adv_title in", values, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleNotIn(List<String> values) { addCriterion("adv_title not in", values, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleBetween(String value1, String value2) { addCriterion("adv_title between", value1, value2, "advTitle"); return (Criteria) this; } public Criteria andAdvTitleNotBetween(String value1, String value2) { addCriterion("adv_title not between", value1, value2, "advTitle"); return (Criteria) this; } public Criteria andAdvPicUrlIsNull() { addCriterion("adv_pic_url is null"); return (Criteria) this; } public Criteria andAdvPicUrlIsNotNull() { addCriterion("adv_pic_url is not null"); return (Criteria) this; } public Criteria andAdvPicUrlEqualTo(String value) { addCriterion("adv_pic_url =", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlNotEqualTo(String value) { addCriterion("adv_pic_url <>", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlGreaterThan(String value) { addCriterion("adv_pic_url >", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlGreaterThanOrEqualTo(String value) { addCriterion("adv_pic_url >=", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlLessThan(String value) { addCriterion("adv_pic_url <", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlLessThanOrEqualTo(String value) { addCriterion("adv_pic_url <=", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlLike(String value) { addCriterion("adv_pic_url like", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlNotLike(String value) { addCriterion("adv_pic_url not like", value, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlIn(List<String> values) { addCriterion("adv_pic_url in", values, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlNotIn(List<String> values) { addCriterion("adv_pic_url not in", values, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlBetween(String value1, String value2) { addCriterion("adv_pic_url between", value1, value2, "advPicUrl"); return (Criteria) this; } public Criteria andAdvPicUrlNotBetween(String value1, String value2) { addCriterion("adv_pic_url not between", value1, value2, "advPicUrl"); return (Criteria) this; } public Criteria andAdvOfflineIsNull() { addCriterion("adv_offline is null"); return (Criteria) this; } public Criteria andAdvOfflineIsNotNull() { addCriterion("adv_offline is not null"); return (Criteria) this; } public Criteria andAdvOfflineEqualTo(Short value) { addCriterion("adv_offline =", value, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineNotEqualTo(Short value) { addCriterion("adv_offline <>", value, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineGreaterThan(Short value) { addCriterion("adv_offline >", value, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineGreaterThanOrEqualTo(Short value) { addCriterion("adv_offline >=", value, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineLessThan(Short value) { addCriterion("adv_offline <", value, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineLessThanOrEqualTo(Short value) { addCriterion("adv_offline <=", value, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineIn(List<Short> values) { addCriterion("adv_offline in", values, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineNotIn(List<Short> values) { addCriterion("adv_offline not in", values, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineBetween(Short value1, Short value2) { addCriterion("adv_offline between", value1, value2, "advOffline"); return (Criteria) this; } public Criteria andAdvOfflineNotBetween(Short value1, Short value2) { addCriterion("adv_offline not between", value1, value2, "advOffline"); return (Criteria) this; } public Criteria andAdvOrderIsNull() { addCriterion("adv_order is null"); return (Criteria) this; } public Criteria andAdvOrderIsNotNull() { addCriterion("adv_order is not null"); return (Criteria) this; } public Criteria andAdvOrderEqualTo(Integer value) { addCriterion("adv_order =", value, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderNotEqualTo(Integer value) { addCriterion("adv_order <>", value, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderGreaterThan(Integer value) { addCriterion("adv_order >", value, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderGreaterThanOrEqualTo(Integer value) { addCriterion("adv_order >=", value, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderLessThan(Integer value) { addCriterion("adv_order <", value, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderLessThanOrEqualTo(Integer value) { addCriterion("adv_order <=", value, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderIn(List<Integer> values) { addCriterion("adv_order in", values, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderNotIn(List<Integer> values) { addCriterion("adv_order not in", values, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderBetween(Integer value1, Integer value2) { addCriterion("adv_order between", value1, value2, "advOrder"); return (Criteria) this; } public Criteria andAdvOrderNotBetween(Integer value1, Integer value2) { addCriterion("adv_order not between", value1, value2, "advOrder"); return (Criteria) this; } public Criteria andAdvLinkUrlIsNull() { addCriterion("adv_link_url is null"); return (Criteria) this; } public Criteria andAdvLinkUrlIsNotNull() { addCriterion("adv_link_url is not null"); return (Criteria) this; } public Criteria andAdvLinkUrlEqualTo(String value) { addCriterion("adv_link_url =", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlNotEqualTo(String value) { addCriterion("adv_link_url <>", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlGreaterThan(String value) { addCriterion("adv_link_url >", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlGreaterThanOrEqualTo(String value) { addCriterion("adv_link_url >=", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlLessThan(String value) { addCriterion("adv_link_url <", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlLessThanOrEqualTo(String value) { addCriterion("adv_link_url <=", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlLike(String value) { addCriterion("adv_link_url like", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlNotLike(String value) { addCriterion("adv_link_url not like", value, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlIn(List<String> values) { addCriterion("adv_link_url in", values, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlNotIn(List<String> values) { addCriterion("adv_link_url not in", values, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlBetween(String value1, String value2) { addCriterion("adv_link_url between", value1, value2, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvLinkUrlNotBetween(String value1, String value2) { addCriterion("adv_link_url not between", value1, value2, "advLinkUrl"); return (Criteria) this; } public Criteria andAdvCratetimeIsNull() { addCriterion("adv_cratetime is null"); return (Criteria) this; } public Criteria andAdvCratetimeIsNotNull() { addCriterion("adv_cratetime is not null"); return (Criteria) this; } public Criteria andAdvCratetimeEqualTo(Date value) { addCriterion("adv_cratetime =", value, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeNotEqualTo(Date value) { addCriterion("adv_cratetime <>", value, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeGreaterThan(Date value) { addCriterion("adv_cratetime >", value, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeGreaterThanOrEqualTo(Date value) { addCriterion("adv_cratetime >=", value, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeLessThan(Date value) { addCriterion("adv_cratetime <", value, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeLessThanOrEqualTo(Date value) { addCriterion("adv_cratetime <=", value, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeIn(List<Date> values) { addCriterion("adv_cratetime in", values, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeNotIn(List<Date> values) { addCriterion("adv_cratetime not in", values, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeBetween(Date value1, Date value2) { addCriterion("adv_cratetime between", value1, value2, "advCratetime"); return (Criteria) this; } public Criteria andAdvCratetimeNotBetween(Date value1, Date value2) { addCriterion("adv_cratetime not between", value1, value2, "advCratetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeIsNull() { addCriterion("adv_updatetime is null"); return (Criteria) this; } public Criteria andAdvUpdatetimeIsNotNull() { addCriterion("adv_updatetime is not null"); return (Criteria) this; } public Criteria andAdvUpdatetimeEqualTo(Date value) { addCriterion("adv_updatetime =", value, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeNotEqualTo(Date value) { addCriterion("adv_updatetime <>", value, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeGreaterThan(Date value) { addCriterion("adv_updatetime >", value, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeGreaterThanOrEqualTo(Date value) { addCriterion("adv_updatetime >=", value, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeLessThan(Date value) { addCriterion("adv_updatetime <", value, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeLessThanOrEqualTo(Date value) { addCriterion("adv_updatetime <=", value, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeIn(List<Date> values) { addCriterion("adv_updatetime in", values, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeNotIn(List<Date> values) { addCriterion("adv_updatetime not in", values, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeBetween(Date value1, Date value2) { addCriterion("adv_updatetime between", value1, value2, "advUpdatetime"); return (Criteria) this; } public Criteria andAdvUpdatetimeNotBetween(Date value1, Date value2) { addCriterion("adv_updatetime not between", value1, value2, "advUpdatetime"); return (Criteria) this; } } /** */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
true
4fbd7c399407e7bcaf8fe4d98f6a83ccd1464e47
Java
spectuu/rpgquest-2d-version
/src/main/java/com/spectu/game/scenes/Statistics.java
UTF-8
5,225
2.578125
3
[]
no_license
package com.spectu.game.scenes; import com.spectu.game.Main; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import javafx.scene.text.Font; public class Statistics implements RPGScene { public static Label playerHeal; public static AnchorPane rootStatistics; public static Scene sceneStatistics; public static ScrollPane inventoryScrollPane; public static HBox inventory; Button back; Label playerName; Label playerClass; Label character; Label specialWeapon; Label playerAbility; Label playerSpecialWeaponDescription; Label Equipment; ImageView playerCharacter; ImageView playerSpecialWeapon; @Override public Scene create(Stage stage) { playerName = new Label("Player name: " + CreateCharacter.player.name); playerName.setFont(new Font(15)); playerName.setLayoutX(20); playerName.setLayoutY(30); playerHeal = new Label("Player heal: " + CreateCharacter.player.heal + "/100"); playerHeal.setFont(new Font(15)); playerHeal.setLayoutX(20); playerHeal.setLayoutY(60); playerClass = new Label("Player class: " + CreateCharacter.player.playerClass); playerClass.setFont(new Font(15)); playerClass.setLayoutX(20); playerClass.setLayoutY(90); character = new Label("Character: "); character.setFont(new Font(15)); character.setLayoutX(20); character.setLayoutY(120); playerCharacter = CreateCharacter.player.getPlayerCharacterImageView(); playerCharacter.setLayoutX(30); playerCharacter.setLayoutY(140); playerCharacter.setFitWidth(30); playerCharacter.setFitHeight(46); specialWeapon = new Label("Special Weapon: "); specialWeapon.setFont(new Font(15)); specialWeapon.setLayoutX(120); specialWeapon.setLayoutY(120); playerSpecialWeaponDescription = new Label(CreateCharacter.player.getPlayerCharacterSpecialWeaponDescription()); playerSpecialWeaponDescription.setFont(new Font(15)); playerSpecialWeaponDescription.setLayoutX(30); playerSpecialWeaponDescription.setLayoutY(210); playerAbility = new Label(CreateCharacter.player.getPlayerCharacterAbilityDescription()); playerAbility.setFont(new Font(15)); playerAbility.setLayoutX(30); playerAbility.setLayoutY(300); Equipment = new Label("Objects and basic Weapons: "); Equipment.setFont(new Font(15)); Equipment.setLayoutX(30); Equipment.setLayoutY(360); playerSpecialWeapon = CreateCharacter.player.getPlayerCharacterSpecialWeaponImageView(); playerSpecialWeapon.setLayoutX(155); playerSpecialWeapon.setLayoutY(150); inventoryScrollPane = new ScrollPane(); inventoryScrollPane.setLayoutX(10); inventoryScrollPane.setLayoutY(430); inventory = new HBox(); inventory.setLayoutX(10); inventory.setLayoutY(420); back = new Button("Back"); back.setFont(new Font(15)); back.setLayoutX(20); back.setLayoutY(500); back.setOnAction((e) -> { Main.show(GameMenu.class); }); rootStatistics = new AnchorPane(); sceneStatistics = new Scene(rootStatistics, 1024, 530); CreateCharacter.player.inventory.sceneChecker = Statistics.sceneStatistics; CreateCharacter.player.inventory.showInventory(); CreateCharacter.player.inventory.getHealingPotion().onClick(); CreateCharacter.player.inventory.getMythril().onClick(); CreateCharacter.player.inventory.getSpectral().onClick(); CreateCharacter.player.inventory.getSpecialWeapon().specialWeaponLabel(); CreateCharacter.player.inventory.getMythrilSword().weaponLabelInventory(); CreateCharacter.player.inventory.getSpectralHoz().weaponLabelInventory(); rootStatistics.getChildren().add(playerName); rootStatistics.getChildren().add(playerHeal); rootStatistics.getChildren().add(playerClass); rootStatistics.getChildren().add(playerAbility); rootStatistics.getChildren().add(Equipment); rootStatistics.getChildren().add(back); rootStatistics.getChildren().add(playerCharacter); rootStatistics.getChildren().add(character); rootStatistics.getChildren().add(playerSpecialWeapon); rootStatistics.getChildren().add(specialWeapon); rootStatistics.getChildren().add(playerSpecialWeaponDescription); inventoryScrollPane.setContent(inventory); //inventoryScrollPane.get rootStatistics.getChildren().add(inventoryScrollPane); rootStatistics.getChildren().add(inventory); stage.setScene(sceneStatistics); inventoryScrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); inventoryScrollPane.setMaxWidth(1000); return sceneStatistics; } }
true
578df0c866af782abd347e2d25105ec7fe5048fa
Java
GVK927/First-repository
/src/figures/quadrilaterals/Quadrilateral.java
UTF-8
312
1.867188
2
[]
no_license
package figures.quadrilaterals; public class Quadrilateral{} class ConvexQuadrilateral extends Quadrilateral{} class Trapezoid extends ConvexQuadrilateral{} class Parallelogram extends Trapezoid{} class Rectangle extends Parallelogram{} class Rhombus extends Parallelogram{} class Square extends Rhombus{}
true
0a31796e01411b792041c789e37fce4cba11a9b3
Java
Kennywest3/vahan
/newreg/src/java/nic/vahan/form/bean/reports/VehicleParticularRePrintBean.java
UTF-8
4,160
1.796875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nic.vahan.form.bean.reports; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import nic.vahan.form.dobj.reports.VehicleParticularDobj; import nic.vahan.form.impl.PrintDocImpl; import nic.vahan.form.impl.Util; import org.apache.log4j.Logger; import org.primefaces.PrimeFaces; /** * * @author nicsi */ @ManagedBean(name = "printVehParBean") @ViewScoped public class VehicleParticularRePrintBean implements Serializable { private static final Logger LOGGER = Logger.getLogger(VehicleParticularRePrintBean.class); private String regn_no; private String state_cd; private int off_cd; private String appl_no; private List<VehicleParticularDobj> printVchParDobj = new ArrayList<VehicleParticularDobj>(); public void setListBeans(List<VehicleParticularDobj> listDobjs) { setPrintVchParDobj(listDobjs); } @PostConstruct public void init() { try { state_cd = Util.getUserStateCode(); off_cd = Util.getSelectedSeat().getOff_cd(); ArrayList<VehicleParticularDobj> list = PrintDocImpl.getVchParTodayPrintedDetails(state_cd, off_cd); if (list.isEmpty()) { PrimeFaces.current().dialog().showMessageDynamic(new FacesMessage(FacesMessage.SEVERITY_WARN, "Alert!", "There is no printed RC as on Today !!")); return; } else { this.setListBeans(list); } } catch (Exception e) { LOGGER.error(e.toString() + " " + e.getStackTrace()[0]); } } public void confirmPrintVP() { if (regn_no == null || "".contains(regn_no)) { PrimeFaces.current().dialog().showMessageDynamic(new FacesMessage(FacesMessage.SEVERITY_WARN, "Alert!", "Registration No should not be Blank !!")); return; } try { appl_no = PrintDocImpl.isRegnExistForVehParPrint(regn_no.trim().toUpperCase(), state_cd, off_cd); if (appl_no == null) { PrimeFaces.current().dialog().showMessageDynamic(new FacesMessage(FacesMessage.SEVERITY_WARN, "Alert!", "Registration does not exist or you are not authorized to print Vehicle Particular for this Registration !!!!")); return; } else { //RequestContext ca = RequestContext.getCurrentInstance(); PrimeFaces.current().executeScript("PF('printVP').show()"); } } catch (Exception e) { LOGGER.error(e); } } public String printVehicleParticular() { FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("veh_par_regn_no", regn_no.trim().toUpperCase()); FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("veh_par_appl_no", appl_no); return "rePrintVehParticulatReport"; } /** * @return the regn_no */ public String getRegn_no() { return regn_no; } /** * @param regn_no the regn_no to set */ public void setRegn_no(String regn_no) { this.regn_no = regn_no; } /** * @return the appl_no */ public String getAppl_no() { return appl_no; } /** * @param appl_no the appl_no to set */ public void setAppl_no(String appl_no) { this.appl_no = appl_no; } /** * @return the printVchParDobj */ public List<VehicleParticularDobj> getPrintVchParDobj() { return printVchParDobj; } /** * @param printVchParDobj the printVchParDobj to set */ public void setPrintVchParDobj(List<VehicleParticularDobj> printVchParDobj) { this.printVchParDobj = printVchParDobj; } }
true
23e572fda2c45cf1636d2b4f82e2da2b1b1a0a13
Java
jfreax/IsleGenerator
/Main/src/de/jdsoft/stranded/map/planet/generator/World.java
UTF-8
9,763
2.90625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Beerware" ]
permissive
package de.jdsoft.stranded.map.planet.generator; import com.marcrh.graph.Point; import de.jdsoft.stranded.map.planet.entity.Tile; import java.util.*; public class World extends Generator { private float absoluteMaxHeight = 0; private int noOfTiles; private ArrayList<Tile> landTiles; private Random randomHeight = new Random(); public World(int width, int height) { super(width, height); landTiles = new ArrayList<Tile>(); } public void Compute(ArrayList<Tile> tiles) { noOfTiles = tiles.size(); LinkedList<Tile>nexts = new LinkedList<Tile>(); for( Tile tile : tiles) { for( Point p : tile.getPoints() ) { if( p.x == 0 || p.y == 0 || p.x == width || p.y == height ) { tile.isOnBorder(true); tile.setType(Tile.WATER); tile.setDistance(0); nexts.add(tile); } } } FillRecursive(nexts); // More mountain for( int i = random.nextInt(12)+5; i >= 0; i-- ) { generateBonusMountain(tiles, random.nextInt(5)+3, 0.2f); } // Lakes! generateBonusLakes(tiles); // Compute height for every _point_ HashMap<Point, List<Tile> > nei = new HashMap<Point, List<Tile> >(); for( Tile tile : tiles ) { for( Point p : tile.getPoints()) { // if( tile.getType() != Tile.WATER && tile.getSpecificType() != Tile.BEACH ) { // p.z = tile.getHeight() / getAbsoluteMaxHeight(); // } if( nei.containsKey(p)) { nei.get(p).add(tile); } else { nei.put(p, new LinkedList<Tile>()); nei.get(p).add(tile); } } } for (Map.Entry<Point, List<Tile> > entry : nei.entrySet()) { //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); float meanHeight = 0.f; float minHeight = 99999; boolean isOneWater = false; for( Tile tile : entry.getValue()) { if( tile.getType() == Tile.WATER ) { isOneWater = true; break; } if( tile.getSpecificType() == Tile.BEACH ) { isOneWater = true; break; } minHeight = Math.min(minHeight, tile.getHeight()); meanHeight += tile.getHeight(); } if( isOneWater ) { entry.getKey().z = 0.f; continue; } //meanHeight /= entry.getValue().size(); meanHeight = minHeight; meanHeight /= getAbsoluteMaxHeight(); entry.getKey().z = meanHeight; } } private void FillRecursive(LinkedList<Tile> nexts ) { LinkedList<Tile> nextNexts = new LinkedList<Tile>(); for( Tile tile : nexts) { nextNexts.addAll(changeType(tile)); } Collections.sort(nextNexts); if( !nextNexts.isEmpty() ) { FillRecursive(nextNexts); } } private LinkedList<Tile> changeType(Tile tile) { LinkedList<Tile> nextNexts = new LinkedList<Tile>(); for( Tile neighbor : tile.neighbors ) { if( tile.getType() == Tile.WATER ) { neighbor.waterNeighbors++; } // Only not visited neighbors if( neighbor.getType() != Tile.NONE ) { continue; } // This tile is water if( tile.getType() == Tile.WATER ) { // Maybe the neighbor should be water to? if( isOcean(neighbor)) { neighbor.setType( Tile.WATER ); neighbor.setDistance(tile.getDistance() + 1); nextNexts.addFirst(neighbor); } else { // No water, this is land neighbor.setType(Tile.LAND); neighbor.setSpecificType(Tile.BEACH); landTiles.add(neighbor); nextNexts.addLast(neighbor); } } else if (random.nextInt(100) < 15) { // This is land, so the neighbor should be land to, but its heigher // Set new height float maxHeight = 0.f; for( Tile neighbor2 : tile.neighbors) { maxHeight = Math.max(maxHeight, neighbor2.getHeight()); } neighbor.setHeight( maxHeight + ( (float)(randomHeight.nextGaussian()*2.f) - 1.2f) ); if( neighbor.getHeight() > absoluteMaxHeight ) { absoluteMaxHeight = neighbor.getHeight(); } // Make land! neighbor.setType(Tile.LAND); landTiles.add(neighbor); nextNexts.addLast(neighbor); } } nextNexts.addAll(nextNexts); return nextNexts; } private boolean first = true; private boolean isOcean(Tile tile) { if ( first ) { first = false; return false; } // probability to generate new island if( random.nextInt(1000) <= 8) { return false; } if( random.nextInt(1000) <= 80) { return true; } for( Tile neighbor : tile.neighbors) { if( neighbor.getType() == Tile.LAND ) { return false; } } return true; } private void generateBonusMountain(ArrayList<Tile> tiles, int mountainHeight, float decay) { float incHeight = mountainHeight; // Select random land tile Tile randomTile = null; for(int i = tiles.size()-1; i > 0; i--) { int rand = random.nextInt(tiles.size()-1); randomTile = tiles.get(rand); if( randomTile.getType() == Tile.LAND) { if( randomTile.getHeight() < getAbsoluteMaxHeight() - incHeight) { break; } } } // No fitting tile found if( randomTile == null ) { return; } LinkedList<Tile> toVised = new LinkedList<Tile>(); toVised.add(randomTile); toVised.addAll(randomTile.neighbors); HashSet<Tile> visited = new HashSet<Tile>(); visited.add(randomTile); while(true) { LinkedList<Tile> toVisedNext = new LinkedList<Tile>(); for( Tile neighbor : toVised ) { if( visited.contains(neighbor) || neighbor.getType() == Tile.WATER ) { continue; } // Mark as visited visited.add(neighbor); neighbor.incHeight(incHeight); toVisedNext.addAll(neighbor.neighbors); if(neighbor.getHeight() > getAbsoluteMaxHeight()) { setAbsoluteMaxHeight(neighbor.getHeight()); } } incHeight -= random.nextFloat() * decay; if(incHeight <= 0.) { break; } toVised = toVisedNext; } } private void generateBonusLakes( ArrayList<Tile> tiles ) { float lakeSize = 5; // Select "random" land tile Tile randomTile = null; for( Tile tile : tiles) { if( tile.getType() == Tile.WATER ) { continue; } boolean foundGood = true; for( Tile neighbor : tile.neighbors ) { if( neighbor.getType() == Tile.WATER || neighbor.getSpecificType() == Tile.BEACH ) { foundGood = false; break; } } // Take only maybe if( foundGood ) { randomTile = tile; break; } } // No fitting tile found if( randomTile == null ) { return; } float lakeHeight = randomTile.getHeight(); LinkedList<Tile> toVised = new LinkedList<Tile>(); toVised.add(randomTile); toVised.addAll(randomTile.neighbors); HashSet<Tile> visited = new HashSet<Tile>(); //visited.add(randomTile); for(int i = random.nextInt(4)+1; i >= 0; i--) { LinkedList<Tile> toVisedNext = new LinkedList<Tile>(); for( Tile neighbor : toVised ) { if( visited.contains(neighbor) ) { continue; } if( neighbor.getType() == Tile.WATER || neighbor.getSpecificType() == Tile.BEACH ) { continue; } if ( Math.abs(neighbor.getHeight() - lakeHeight) > 0.1f * absoluteMaxHeight ) { continue; } // Mark as visited visited.add(neighbor); if( random.nextFloat() > 0.3f) { toVisedNext.addAll(neighbor.neighbors); } neighbor.setType(Tile.WATER); neighbor.setSpecificType(Tile.LAKE); neighbor.setHeight(lakeHeight); } toVised = toVisedNext; } } public ArrayList<Tile> getLandTiles() { return landTiles; } public float getAbsoluteMaxHeight() { return absoluteMaxHeight; } public void setAbsoluteMaxHeight(float absoluteMaxHeight) { this.absoluteMaxHeight = absoluteMaxHeight; } }
true
680e3a780c2fab49e2b21c2ad036b2d91f609d85
Java
zhangchengku/CinemaLetter
/app/src/main/java/com/myp/cinema/ui/Prizesreading/Prizesreading.java
UTF-8
4,733
1.976563
2
[]
no_license
package com.myp.cinema.ui.Prizesreading; import com.myp.cinema.R; import com.myp.cinema.base.MyApplication; import com.myp.cinema.entity.ShopBO; import com.myp.cinema.mvp.MVPBaseActivity; import com.myp.cinema.ui.WebViewActivity; import com.myp.cinema.util.LogUtils; import com.myp.cinema.util.StringUtils; import com.myp.cinema.widget.superadapter.CommonAdapter; import com.myp.cinema.widget.superadapter.ViewHolder; import com.myp.cinema.widget.swiferefresh.SwipeRefreshVie; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by Administrator on 2018/1/24.game_list */ public class Prizesreading extends MVPBaseActivity<PrizesreadingContract.View, PrizesreadingPresenter> implements PrizesreadingContract.View, AdapterView.OnItemClickListener { @Bind(R.id.game_list) ListView list; @Bind(R.id.refreshLayout) SmartRefreshLayout smartRefreshLayout; private ArrayList<HomeTopBean.DataBo> data = new ArrayList<>(); private CommonAdapter<HomeTopBean.DataBo> adapter; private int page = 1; @Override protected int getLayout() { return R.layout.act_prizes_read; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); goBack(); setTitle("有奖阅读"); list.setOnItemClickListener(this); mPresenter.loadTaskList(1); setPullRefresher(); adapter(); } private void adapter() { adapter = new CommonAdapter<HomeTopBean.DataBo>(this, R.layout.item_prizes_read, data) { @Override protected void convert(ViewHolder viewHolder, HomeTopBean.DataBo item, int position) { if (StringUtils.isEmpty(item.getPic())) { viewHolder.setImageResource(R.id.prizes_image, R.drawable.zhanwei2); } else { viewHolder.setImageUrl(R.id.prizes_image, item.getPic()); } viewHolder.setText(R.id.prizes_text, item.getTitle()); viewHolder.setText(R.id.read_text, item.getDescription()); } }; } private void setPullRefresher() { smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshlayout) { mPresenter.loadTaskList(1); page = 1; smartRefreshLayout.finishRefresh(1000); refreshlayout.finishRefresh(2000); } }); smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() { @Override public void onLoadmore(RefreshLayout refreshlayout) { page++; mPresenter.loadTaskList(page); smartRefreshLayout.finishLoadmore(1000); refreshlayout.finishLoadmore(2000); } }); } @Override public void onRequestError(String msg) { LogUtils.showToast(msg); } @Override public void onRequestEnd() { } @Override public void getTaskList(List<HomeTopBean.DataBo> gameBOs, int pageNos) { if (pageNos == 1) { data.clear(); data.addAll(gameBOs); list.setAdapter(adapter); } else { data.addAll(gameBOs); adapter.setmDatas(data); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Bundle bundle = new Bundle(); bundle.putString("title", data.get(position).getTitle()); bundle.putString("title", data.get(position).getTitle()); bundle.putString("pic", data.get(position).getPic()); bundle.putString("description", data.get(position).getDescription()); bundle.putString("url", data.get(position).getArticleUrl() + "&flag=1"); String yes = "yes"; bundle.putString("fenxiang", yes); bundle.putString("back", "yes"); gotoActivity(WebViewActivity.class, bundle, false); } @Override protected void onDestroy() { super.onDestroy(); ButterKnife.unbind(this); } }
true
eaf22d0bb073bd3f75ec03bda1ca6c0edaef9c70
Java
nsl1065539573/mechanicsmanagementsystem
/src/main/java/com/example/mechanicsmanagementsystem/utils/JavaWebToken.java
UTF-8
1,323
2.4375
2
[]
no_license
package com.example.mechanicsmanagementsystem.utils; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Map; public class JavaWebToken { private static Logger log = LoggerFactory.getLogger(JavaWebToken.class); private static Key getKeyInstance() { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("tutu"); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); return signingKey; } // 生成token public static String createToken(Map<String, Object> claims) { return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact(); } public static Map<String, Object> parseToken(String token) { try { Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJwt(token).getBody(); return jwtClaims; } catch (Exception e) { log.error("parse token failed"); return null; } } }
true
3b3420de22c099e81f2fdd503f778374aecb7d4f
Java
kalyanihandal/FileToSonali
/src/test/java/com/TestCases/TC_Login_001.java
UTF-8
541
2.171875
2
[]
no_license
package com.TestCases; import org.testng.annotations.Test; import com.PageObject.LoginPage; public class TC_Login_001 extends BaseClass { @Test(priority=1) public void verifyLogin() throws Exception { LoginPage lp=new LoginPage(driver); lp.clickLoginText(); logger.info("Clicked on Login text"); lp.enterEmail(email); logger.info("Entered Email ID"); //Assert.assertTrue(false); lp.enterPassword(password); logger.info("Entered Password"); lp.clickOnLoginButton(); logger.info("Clicked on Login Button"); } }
true
c3527ecad1ba86541c67cc767405a687633d0500
Java
jorge-luque/hb
/sources/com/applovin/impl/sdk/p052d/C1867ab.java
UTF-8
2,761
1.664063
2
[]
no_license
package com.applovin.impl.sdk.p052d; import com.applovin.impl.p033a.C1482c; import com.applovin.impl.p033a.C1483d; import com.applovin.impl.p033a.C1489i; import com.applovin.impl.sdk.C1941j; import com.applovin.impl.sdk.network.C1960b; import com.applovin.impl.sdk.p050b.C1841c; import com.applovin.impl.sdk.utils.C2025o; import com.applovin.impl.sdk.utils.C2029r; import com.applovin.impl.sdk.utils.C2032t; import com.applovin.sdk.AppLovinAdLoadListener; /* renamed from: com.applovin.impl.sdk.d.ab */ class C1867ab extends C1864a { /* access modifiers changed from: private */ /* renamed from: a */ public C1482c f6222a; /* access modifiers changed from: private */ /* renamed from: c */ public final AppLovinAdLoadListener f6223c; C1867ab(C1482c cVar, AppLovinAdLoadListener appLovinAdLoadListener, C1941j jVar) { super("TaskResolveVastWrapper", jVar); this.f6223c = appLovinAdLoadListener; this.f6222a = cVar; } /* access modifiers changed from: private */ /* renamed from: a */ public void m7199a(int i) { mo8410d("Failed to resolve VAST wrapper due to error code " + i); if (i == -103) { C2029r.m8008a(this.f6223c, this.f6222a.mo7196g(), i, this.f6217b); } else { C1489i.m5784a(this.f6222a, this.f6223c, i == -102 ? C1483d.TIMED_OUT : C1483d.GENERAL_WRAPPER_ERROR, i, this.f6217b); } } public void run() { String a = C1489i.m5780a(this.f6222a); if (C2025o.m7963b(a)) { mo8405a("Resolving VAST ad with depth " + this.f6222a.mo7190a() + " at " + a); try { this.f6217b.mo8533L().mo8474a((C1864a) new C1921y<C2032t>(C1960b.m7596a(this.f6217b).mo8663a(a).mo8669b("GET").mo8662a(C2032t.f6742a).mo8661a(((Integer) this.f6217b.mo8549a(C1841c.f6018eI)).intValue()).mo8668b(((Integer) this.f6217b.mo8549a(C1841c.f6019eJ)).intValue()).mo8666a(false).mo8667a(), this.f6217b) { /* renamed from: a */ public void mo7627a(int i) { mo8410d("Unable to resolve VAST wrapper. Server returned " + i); C1867ab.this.m7199a(i); } /* renamed from: a */ public void mo7628a(C2032t tVar, int i) { this.f6217b.mo8533L().mo8474a((C1864a) C1914u.m7369a(tVar, C1867ab.this.f6222a, C1867ab.this.f6223c, C1867ab.this.f6217b)); } }); } catch (Throwable th) { mo8406a("Unable to resolve VAST wrapper", th); } } else { mo8410d("Resolving VAST failed. Could not find resolution URL"); m7199a(-1); } } }
true
fd370c0decdb1f7c56eccea74ea25597c17a657c
Java
SecureSmartHome/SecureSmartHome
/core/src/main/java/de/unipassau/isl/evs/ssh/core/container/AccessLogger.java
UTF-8
5,873
2.03125
2
[ "MIT" ]
permissive
/* * MIT License * * Copyright (c) 2016. * Bucher Andreas, Fink Simon Dominik, Fraedrich Christoph, Popp Wolfgang, * Sell Leon, Werli Philemon * * 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 de.unipassau.isl.evs.ssh.core.container; import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Set; import de.ncoder.typedmap.Key; import de.unipassau.isl.evs.ssh.core.schedule.ExecutionServiceComponent; import io.netty.channel.EventLoop; /** * @author Niko Fink */ public class AccessLogger extends AbstractComponent { private static final String TAG = AccessLogger.class.getSimpleName(); public static final Key<AccessLogger> KEY = new Key<>(AccessLogger.class); private final Set<Integer> knownStackTraces = new HashSet<>(); private Writer writer; private EventLoop eventLoop; @Override public void init(Container container) { super.init(container); final Context context = requireComponent(ContainerService.KEY_CONTEXT); final String name = context.getPackageName() + "-access.log"; File dir = context.getExternalFilesDir(null); if (dir == null) { dir = context.getFilesDir(); } final File file = new File(dir, name); try { writer = new FileWriter(file, true); writer.append("\n===============================================================================\n") .append("Logging for ").append(context.getPackageName()) .append(" started at ").append(new Date().toString()).append("\n"); Log.i(TAG, "Logging to " + file); eventLoop = requireComponent(ExecutionServiceComponent.KEY).next(); } catch (IOException e) { Log.w(TAG, "Could not open FileOutputStream to " + file, e); } } @Override public void destroy() { if (writer != null) { try { writer.append("Log closed at").append(new Date().toString()).append("\n"); writer.close(); } catch (IOException e) { Log.w(TAG, "Could not close FileOutputStream", e); } } super.destroy(); } /** * Log that the given object has been access together with the current call stack. */ public void logAccess(Object accessed) { if (writer == null) { return; } final String name; if (accessed != null) { name = accessed.getClass().getSimpleName() + "." + accessed.toString(); } else { name = ""; } final Date timestamp = new Date(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); eventLoop.execute(new Runnable() { @Override public void run() { try { final int hash = Arrays.hashCode(stackTrace); if (knownStackTraces.contains(hash)) { return; } else { knownStackTraces.add(hash); } writer.append(timestamp.toString()) .append("\naccess to ").append(name) .append(" from\n"); for (int i = 1; i < stackTrace.length; i++) { final String className = stackTrace[i].getClassName(); final String methodName = stackTrace[i].getMethodName(); // filter all low level calls like Thread.run() if (!className.startsWith("de.unipassau")) continue; // filter the calls through the library that led to logAccess being called, // so only the relevant parts of the stack are logged final boolean isMessage = methodName.startsWith("sendMessage") || methodName.startsWith("sendReply"); final boolean isMessageClass = className.endsWith("AbstractMessageHandler") || className.endsWith("OutgoingRouter"); final boolean isPermission = methodName.startsWith("hasPermission"); final boolean isPermissionClass = className.endsWith("AbstractMasterHandler") || className.endsWith("PermissionController"); if (!((isMessage && isMessageClass) || (isPermission && isPermissionClass))) { writer.append(stackTrace[i].toString()).append("\n"); } } } catch (IOException e) { e.printStackTrace(); } } }); } }
true
fe27338bdc13e58c0d2d8327d45b8bfb388bce4d
Java
ilscipio/scipio-erp
/applications/product/src/com/ilscipio/scipio/product/seo/SeoUrlUtil.java
UTF-8
2,210
2.046875
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown", "LicenseRef-scancode-jdom", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "MPL-1.1", "CPL-1.0", "GFDL-1.1-or-later", "MPL-2.0", "CC-BY-2.5", "SPL-1.0", "LicenseRef-scancode-proprietary-license", "C...
permissive
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.ilscipio.scipio.product.seo; import java.util.Map; import org.ofbiz.base.util.UtilValidate; /** * SCIPIO: SEO Catalog URL util */ public class SeoUrlUtil { /** * @deprecated this method did not preserve order of charFilters (though it could have * with LinkedHashMap, method has no control) - use {@link UrlProcessors.CharFilter} instead. */ @Deprecated public static String replaceSpecialCharsUrl(String url, Map<String, String> charFilters) { if (charFilters == null) return url; if (UtilValidate.isEmpty(url)) { url = ""; } for (String characterPattern : charFilters.keySet()) { url = url.replaceAll(characterPattern, charFilters.get(characterPattern)); } return url; } /** * @deprecated does not properly handle delimiters. */ @Deprecated public static String removeContextPath(String uri, String contextPath) { if (UtilValidate.isEmpty(contextPath) || UtilValidate.isEmpty(uri)) { return uri; } if (uri.length() > contextPath.length() && uri.startsWith(contextPath)) { return uri.substring(contextPath.length()); } return uri; } }
true
5317b71fb4dd18c893d3d58adc9c57d6d4854c0d
Java
ryanpepe2000/cmpt220pepe
/labs/2/Problem5.java
UTF-8
850
4.3125
4
[]
no_license
import java.util.Scanner; public class Problem5 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("This program will compare two strings lexiocographically and sort them in ascending order."); // Asks the user for two strings System.out.print("Enter a string: "); String str1 = input.nextLine(); System.out.print("Enter another string: "); String str2 = input.nextLine(); String str3 = ""; // Sorts strings lexicographically if ((str1.compareTo(str2) < 0)){ str3 = str1 + " " + str2; } else if ((str1.compareTo(str2) == 0)) { System.out.println("These strings are lexicographically equivalent."); } else { str3 = str2 + " " + str1; } //Outputs combined strings sorted lexicographically System.out.println(str3); input.close(); } }
true
ae4aaa333f0ffabd16b99625d1e491afc3db3203
Java
ColinYu25/yhpc
/src/main/java/com/safetys/cas/web/action/RoleSetAction.java
UTF-8
1,414
1.890625
2
[]
no_license
package com.safetys.cas.web.action; import java.util.List; import com.safetys.cas.web.action.base.BaseAction; import com.safetys.framework.domain.model.FkRole; import com.safetys.framework.facade.iface.RoleFacadeIface; /** * 设置角色 * * 配置子系统用户先设置默认角色 * * @author maomj * */ public class RoleSetAction extends BaseAction { /** * */ private static final long serialVersionUID = 1L; private RoleFacadeIface roleFacadeIface; private List<FkRole> fkRoles; /** * 配置默认角色 */ public Long[] roleIds; public static Long[] settingRoleIds={477413l}; //477413安监局查看权限 410安监部门 public String loadRoles() { try { // fkRoles = roleFacadeIface.b(); roleIds=RoleSetAction.settingRoleIds; } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; } public String defaultRoles() { RoleSetAction.settingRoleIds=roleIds; responseMessage.write(getText("global.updateok"), true); return SUCCESS; } public Long[] getRoleIds() { return roleIds; } public void setRoleIds(Long[] roleIds) { this.roleIds = roleIds; } public List<FkRole> getFkRoles() { return fkRoles; } public void setFkRoles(List<FkRole> fkRoles) { this.fkRoles = fkRoles; } public void setRoleFacadeIface(RoleFacadeIface roleFacadeIface) { this.roleFacadeIface = roleFacadeIface; } }
true
5a286235cf20ac54d42bba1bf9688cdc6d291f4e
Java
andriol1979/p12soapclient
/src/main/java/nedu/edsn/data/p4collecteddatabatchresultresponse/_2/standard/P4CollectedDataBatchResultResponseEnvelope.java
UTF-8
3,174
2.09375
2
[]
no_license
package nedu.edsn.data.p4collecteddatabatchresultresponse._2.standard; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for P4CollectedDataBatchResultResponseEnvelope complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="P4CollectedDataBatchResultResponseEnvelope"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="EDSNBusinessDocumentHeader" type="{urn:nedu:edsn:data:p4collecteddatabatchresultresponse:2:standard}P4CollectedDataBatchResultResponseEnvelope_EDSNBusinessDocumentHeader"/&gt; * &lt;element name="P4Content" type="{urn:nedu:edsn:data:p4collecteddatabatchresultresponse:2:standard}P4CollectedDataBatchResultResponseEnvelope_P4Content"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "P4CollectedDataBatchResultResponseEnvelope", propOrder = { "edsnBusinessDocumentHeader", "p4Content" }) public class P4CollectedDataBatchResultResponseEnvelope { @XmlElement(name = "EDSNBusinessDocumentHeader", required = true) protected P4CollectedDataBatchResultResponseEnvelopeEDSNBusinessDocumentHeader edsnBusinessDocumentHeader; @XmlElement(name = "P4Content", required = true) protected P4CollectedDataBatchResultResponseEnvelopeP4Content p4Content; /** * Gets the value of the edsnBusinessDocumentHeader property. * * @return * possible object is * {@link P4CollectedDataBatchResultResponseEnvelopeEDSNBusinessDocumentHeader } * */ public P4CollectedDataBatchResultResponseEnvelopeEDSNBusinessDocumentHeader getEDSNBusinessDocumentHeader() { return edsnBusinessDocumentHeader; } /** * Sets the value of the edsnBusinessDocumentHeader property. * * @param value * allowed object is * {@link P4CollectedDataBatchResultResponseEnvelopeEDSNBusinessDocumentHeader } * */ public void setEDSNBusinessDocumentHeader(P4CollectedDataBatchResultResponseEnvelopeEDSNBusinessDocumentHeader value) { this.edsnBusinessDocumentHeader = value; } /** * Gets the value of the p4Content property. * * @return * possible object is * {@link P4CollectedDataBatchResultResponseEnvelopeP4Content } * */ public P4CollectedDataBatchResultResponseEnvelopeP4Content getP4Content() { return p4Content; } /** * Sets the value of the p4Content property. * * @param value * allowed object is * {@link P4CollectedDataBatchResultResponseEnvelopeP4Content } * */ public void setP4Content(P4CollectedDataBatchResultResponseEnvelopeP4Content value) { this.p4Content = value; } }
true
12a8ee22f21cebf46e98442277275b22e27c99eb
Java
nicmarti/lunatech-timekeeper
/src/main/java/fr/lunatech/timekeeper/services/responses/OrganizationResponse.java
UTF-8
5,921
2.03125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Lunatech S.A.S * * 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 fr.lunatech.timekeeper.services.responses; import fr.lunatech.timekeeper.models.Organization; import fr.lunatech.timekeeper.models.Profile; import fr.lunatech.timekeeper.models.Project; import fr.lunatech.timekeeper.models.User; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.List; import java.util.stream.Collectors; public class OrganizationResponse { @NotNull private final Long id; @NotBlank private final String name; @NotNull private final String tokenName; @NotNull private final List<OrganizationProjectResponse> projects; @NotNull private final List<OrganizationUserResponse> users; public OrganizationResponse( @NotNull Long id, @NotBlank String name, @NotNull String tokenName, @NotNull List<OrganizationProjectResponse> projects, @NotNull List<OrganizationUserResponse> users ) { this.id = id; this.name = name; this.tokenName = tokenName; this.projects = projects; this.users = users; } public static OrganizationResponse bind(@NotNull Organization organization) { return new OrganizationResponse( organization.id, organization.name, organization.tokenName, organization.projects .stream() .map(OrganizationProjectResponse::bind) .collect(Collectors.toList()), organization.users .stream() .map(OrganizationUserResponse::bind) .collect(Collectors.toList()) ); } public Long getId() { return id; } public String getName() { return name; } public String getTokenName() { return tokenName; } public List<OrganizationProjectResponse> getProjects() { return projects; } public List<OrganizationUserResponse> getUsers() { return users; } /* 🎁 OrganizationProjectResponse */ public static final class OrganizationProjectResponse { @NotNull private final Long id; @NotNull private final String name; @NotNull private final Boolean publicAccess; @NotNull private final Integer userCount; private OrganizationProjectResponse( @NotNull Long id, @NotNull String name, @NotNull Boolean publicAccess, @NotNull Integer userCount ) { this.id = id; this.name = name; this.publicAccess = publicAccess; this.userCount = userCount; } public static OrganizationProjectResponse bind(@NotNull Project project) { return new OrganizationProjectResponse( project.id, project.name, project.publicAccess, project.users.size() ); } public Long getId() { return id; } public String getName() { return name; } public Boolean isPublicAccess() { return publicAccess; } public Integer getUserCount() { return userCount; } } /* 👤 OrganizationUserResponse */ public static final class OrganizationUserResponse { @NotNull private final Long id; @NotBlank private final String name; @NotBlank @Email private final String email; @NotNull private final String picture; @NotNull private final Integer projectCount; @NotEmpty private final List<Profile> profiles; public OrganizationUserResponse( @NotNull Long id, @NotBlank String name, @NotBlank @Email String email, @NotNull String picture, @NotNull Integer projectCount, @NotEmpty List<Profile> profiles ) { this.id = id; this.name = name; this.email = email; this.picture = picture; this.projectCount = projectCount; this.profiles = profiles; } public static OrganizationUserResponse bind(@NotNull User user) { return new OrganizationUserResponse( user.id, user.getFullName(), user.email, user.picture, user.projects.size(), user.profiles ); } public Long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } public String getPicture() { return picture; } public Integer getProjectCount() { return projectCount; } public List<Profile> getProfiles() { return profiles; } } }
true
ba7eada9a3a9b8a3b8e0e038f173147ae0dc5543
Java
kieuminhduc01/ClientFinalAndroidThayKien
/app/src/main/java/com/example/prmfinal/Client/model/Exercise.java
UTF-8
2,463
2.46875
2
[]
no_license
package com.example.prmfinal.Client.model; public class Exercise { private String id; private String name; private float caloriesPerRep; private String muscleFocus; private String mucDichTap; private String equipment; private String level; private String typeOfExercise; private String videoUrl; private String imgUrl; public Exercise() { } public Exercise(String name, float caloriesPerRep, String muscleFocus, String mucDichTap, String equipment, String level, String typeOfExercise, String videoUrl, String imgUrl) { this.name = name; this.caloriesPerRep = caloriesPerRep; this.muscleFocus = muscleFocus; this.mucDichTap = mucDichTap; this.equipment = equipment; this.level = level; this.typeOfExercise = typeOfExercise; this.videoUrl = videoUrl; this.imgUrl = imgUrl; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getCaloriesPerRep() { return caloriesPerRep; } public void setCaloriesPerRep(float caloriesPerRep) { this.caloriesPerRep = caloriesPerRep; } public String getMuscleFocus() { return muscleFocus; } public void setMuscleFocus(String muscleFocus) { this.muscleFocus = muscleFocus; } public String getMucDichTap() { return mucDichTap; } public void setMucDichTap(String mucDichTap) { this.mucDichTap = mucDichTap; } public String getEquipment() { return equipment; } public void setEquipment(String equipment) { this.equipment = equipment; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getTypeOfExercise() { return typeOfExercise; } public void setTypeOfExercise(String typeOfExercise) { this.typeOfExercise = typeOfExercise; } public String getVideoUrl() { return videoUrl; } public void setVideoUrl(String videoUrl) { this.videoUrl = videoUrl; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } }
true
7f352c535bee863988efbd9000253a406cc43294
Java
khamyl/eDoklad
/Android/android/app/src/main/java/sk/tuke/edoklad/classes/Data.java
UTF-8
531
2.375
2
[]
no_license
package sk.tuke.edoklad.classes; public class Data { String prevadzka, adresa, datum; public void setPrevadzka(String prevadzka) { this.prevadzka = prevadzka; } public void setAdresa(String adresa) { this.adresa = adresa; } public void setDatum(String datum) { this.datum = datum; } public String getPrevadzka() { return prevadzka; } public String getAdresa() { return adresa; } public String getDatum() { return datum; } }
true
55f8c5e42d80e736e40993e45511402b4fbb1623
Java
AppSecAI-TEST/hospital
/project/hs-engine-entity/src/main/java/com/neusoft/hs/domain/treatment/ListTreatmentItemValue.java
UTF-8
1,749
2.21875
2
[]
no_license
//Source file: F:\\my_workspace\\201611������ҽ�������\\DesignModel\\DesignElement\\SimpleTreatmentItemValue.java package com.neusoft.hs.domain.treatment; import java.util.LinkedHashMap; import java.util.Map; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import org.hibernate.Hibernate; import com.neusoft.hs.domain.medicalrecord.ListMedicalRecordItemValue; import com.neusoft.hs.domain.medicalrecord.MedicalRecordException; import com.neusoft.hs.domain.medicalrecord.MedicalRecordItemValue; @Entity @DiscriminatorValue("List") public class ListTreatmentItemValue extends TreatmentItemValue { @ElementCollection(fetch = FetchType.LAZY) @CollectionTable(name = "domain_treatment_item_value_list", joinColumns = @JoinColumn(name = "value_id")) @Column(name = "data") private Map<String, String> data = new LinkedHashMap<String, String>(); /** * @roseuid 58A108960144 */ public ListTreatmentItemValue() { } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } public void putData(String key, String value) { this.data.put(key, value); } @Override public MedicalRecordItemValue toMedicalRecordItemValue() throws MedicalRecordException { return new ListMedicalRecordItemValue(this); } @Override public void doLoad() { Hibernate.initialize(data); } @Override public String toString() { return data.toString(); } }
true
dd42cb5a90b7eed94c5dcc80b6e65d3f5fdb232d
Java
abdulhadiniamati/batchOne
/Training/src/OOPS/Apple.java
UTF-8
584
3.359375
3
[]
no_license
package OOPS; public class Apple implements Fruit { private String name; public Apple(String name){ setName(name); //this.name=name; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void color () { System.out.println("The color for Apples is Red"); } public void shape() { System.out.println("The Shape for Apple is O type"); } public void place() { System.out.println("The best place you can find apple is Afghanistan"); } public String isRotten(){ return "NO"; } }
true
a8a8a915f15668ab89c62af43d3cfe868080dbe0
Java
svilenvul/Java
/oop/src/school/Disciplines.java
UTF-8
83
1.71875
2
[]
no_license
package school; public enum Disciplines { BG,EN,MATH,CHEM,PHYS,BIOL,SPORT,ART; }
true
d79846bc99fba7f807c23b98e059798801def1e2
Java
ZoranYaoYao/LeetCode
/src/com/zoran/leetcode/simple2/Test31.java
GB18030
651
3.078125
3
[]
no_license
package com.zoran.leetcode.simple2; /** * ֤Ĵ * https://leetcode-cn.com/submissions/detail/2909345/ * * ʲôǻַ * https://blog.csdn.net/vvnnnn/article/details/80066085 */ public class Test31 { public boolean Nice_isPalindrome(String s) { char[] cha = s.toCharArray(); int i = 0, j = cha.length -1; while (i < j) { if (!Character.isLetterOrDigit(cha[i])) i++; else if (!Character.isLetterOrDigit(cha[j])) { j--; }else { if (Character.toLowerCase(cha[i]) == Character.toLowerCase(cha[j])) { i++; j--; } else { return false; } } } return true; } }
true
71f75c6382b0f98b69c80265b506c68b9eb5d2a7
Java
zlcjfalsvk/algorithm
/PROGRAMMERS/java/Level1/P_level1_2.java
UTF-8
413
2.765625
3
[]
no_license
package PROGRAMMERS.Level1; /** * 약수의 합 * https://programmers.co.kr/learn/courses/30/lessons/12928 */ public class P_level1_2 { class Solution { public int solution(int n) { if(n <= 1) return n; int answer = 1 + n; for(int i = 2 ; i <= n/2 ; i ++) { if(n % i == 0) answer+=i; } return answer; } } }
true
4c7a725c9e4c2551799138e8dde2e3a896eebc6e
Java
svetthesaiyan/softuni-projects-pb-with-java
/2021.04.17 Advanced Conditional Statements (Lab)/src/advanced_conditional_statements_lab/g_work_hours.java
UTF-8
887
4.03125
4
[]
no_license
package advanced_conditional_statements_lab; import java.util.Scanner; public class g_work_hours { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an hour of the day and we'll tell you whether we're open at said time: "); int hours=Integer.parseInt(scanner.nextLine()); System.out.print("Enter the day of the week when you'd like to visit us: "); String day=scanner.nextLine(); System.out.println(); if(hours>=10 && hours<=18) { switch(day) { case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": case "Saturday": System.out.println("Yes, we are indeed open. Welcome!"); break; default: System.out.println("I'm afraid we're closed at this time. We don't work on Sundays."); } } else System.out.println("closed"); } }
true
db29c24436a23db0e15d10024a676ae5827cc124
Java
superknight/depot
/dsy/src/main/java/dsy/service/member/impl/AddressServiceImpl.java
UTF-8
1,450
2.203125
2
[]
no_license
package dsy.service.member.impl; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dsy.dao.BaseJdbcDao; import dsy.module.DsyAddress; import dsy.service.member.AddressService; @Service public class AddressServiceImpl implements AddressService { @Autowired private BaseJdbcDao baseJdbcDao; @Override public List<DsyAddress> getAddressList(HttpServletRequest request) throws Exception { String customerId = request.getParameter("customerId"); //数据库返回的字段要与前端dataTable的字段和Bean类的字段名字都要相同 String sql = "select * from dsy_address where customer_id=" +customerId+" order by in_time desc"; ResultSet rs = this.baseJdbcDao.execResultSet(sql); List<DsyAddress> list = new ArrayList<DsyAddress>(); while(rs.next()){ DsyAddress address = new DsyAddress(); address.setId(rs.getString("id")); address.setAddress(rs.getString("address")); address.setPhone(rs.getString("phone")); address.setReceiver(rs.getString("receiver")); if(rs.getString("remark") == null){ address.setRemark(""); } else{ address.setRemark(rs.getString("remark")); } address.setIn_time(rs.getTimestamp("in_time")); list.add(address); } return list; } }
true
43a63daf28c298c3ef3af32910d041b68b27147e
Java
qiaohhgz/workspaces
/1000/src/com/common/PropertyManager.java
UTF-8
5,443
2.59375
3
[]
no_license
package com.common; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Created by IntelliJ IDEA. * User: petrop01 * Date: Oct 24, 2011 * Time: 1:20:49 PM * To change this template use File | Settings | File Templates. */ public class PropertyManager { private Map<String, Object> targets = new TreeMap<String, Object>(); private Map<String, Object> t = new HashMap<String, Object>(); private String linkName = ""; private String linkValue = ""; public List<Map<String, String>> getAllProperties(){ List<Map<String, String>> lst = new ArrayList<Map<String, String>>(); for (String objName : targets.keySet()){ TreeMap<String, String> hm = new TreeMap<String, String>(); Object obj = targets.get(objName); Class cl = obj.getClass(); Method[] methods = cl.getDeclaredMethods(); for (Method m : methods){ try{ Object result = null; if (checkMethod(m)) { String propName = getPropertyName(m.getName()); try { result = m.invoke(obj, new Object[]{}); if (result == null){ result = "null"; } }catch (Exception e){ //Logging.logError("Error while calling method " + m.getName(), e); result = null; } if (result!=null){ hm.put(objName.substring(objName.indexOf(".")+1) + "." + propName, result.toString()); } } }catch (Exception ex){ //Logging.logError("Error while processing method " + m.getName(), ex); } } lst.add(hm); } return lst; } public boolean saveProperty(String property, String value){ String objectName = property.substring(0, property.indexOf(".")); String propName = property.substring(property.indexOf(".") + 1); Object obj = this.t.get(objectName); Class clazz = obj.getClass(); boolean success = false; for(Method m : clazz.getMethods()){ if ( ("set" + propName).equals(m.getName()) && m.getParameterTypes().length == 1 && ((m.getModifiers() & Modifier.STATIC) == 0) ) { try { Object v = convertStringToObject(value, m.getParameterTypes()[0]); m.invoke(obj, new Object[]{v}); success = true; break; } catch (Exception ex) { //Logging.logError("Failed to invoke setter method.", ex); } } } return success; } private static Object convertStringToObject(String value, Class c){ if (value == null){ return null; }else if ("null".equals(value)){ return null; }else if (c == String.class){ return value; }else if (c == Integer.class || c == int.class){ return new Integer(value); }else if (c == Long.class || c == long.class){ return new Long(value); }else if (c == Boolean.class || c == boolean.class){ return new Boolean(value.toLowerCase()); }else{ throw new IllegalArgumentException ("Argument conversion failed for ["+value+", " + c.getName() +"]."); } } private static boolean checkMethod(Method m){ boolean ok = (m.getName().startsWith("get") || m.getName().startsWith("is")) && m.getParameterTypes().length==0 && (m.getModifiers() & Modifier.STATIC) == 0; if (!ok) { return false; } else { Annotation[] anns = m.getAnnotations(); for (Annotation ann : anns){ Class clazz = ann.annotationType(); if (clazz == PropertyEditable.class){ return true; } } return false; } } private static String getPropertyName(String nameGetterSetter){ if (nameGetterSetter.startsWith("is")){ return nameGetterSetter.substring(2); }else{ return nameGetterSetter.substring(3); } } public Map<String, Object> getTargets() { return targets; } public void setTargets(Map<String, Object> targets) { this.targets.clear(); this.targets.putAll(targets); this.t.clear(); for(String key : targets.keySet()){ int ind = key.indexOf("."); this.t.put(key.substring(ind+1), targets.get(key)); } } public String getLinkName() { return linkName; } public void setLinkName(String linkName) { this.linkName = linkName; } public String getLinkValue() { return linkValue; } public void setLinkValue(String linkValue) { this.linkValue = linkValue; } }
true
3bb352730e665e85ebcaf48e669118fff8ad9cd7
Java
MirMiao/Miaoheng20191221
/app/src/main/java/com/bw/miaoheng20191221/width/FlowLayout.java
UTF-8
3,061
2.3125
2
[]
no_license
package com.bw.miaoheng20191221.width; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bw.miaoheng20191221.R; import com.bw.miaoheng20191221.app.App; import java.util.List; /** * 时间 :2019/12/21 9:04 * 作者 :苗恒 * 功能 : */ public class FlowLayout extends ViewGroup { public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onLayout(boolean changed, int l, final int t, int r, int b) { int left=0; int top=0; int right=0; int bottom=0; int childCount = getChildCount(); if(childCount>0){ for (int i = 0; i < childCount; i++) { final View childAt = getChildAt(i); childAt.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { TextView textView= (TextView) childAt; flowCallBack.getName(textView.getText().toString()); } }); childAt.measure(0,0); int childWidth = childAt.getMeasuredWidth(); int childHeight = childAt.getMeasuredHeight(); int widthPixels = getResources().getDisplayMetrics().widthPixels; right=left+childWidth; if(right>widthPixels){ left=0; right=left+childWidth; top=bottom+30; } bottom=childHeight+top; childAt.layout(left,top,right,bottom); left+=childWidth+30; } } } public void add(List<String> tags) { if(tags.size()>0&&tags!=null){ for (int i = 0; i < tags.size(); i++) { TextView textView = new TextView(App.getContext()); textView.setText(tags.get(i)); textView.setPadding(10,10,10,10); textView.setTextColor(Color.BLACK); textView.setBackgroundResource(R.drawable.flow); addView(textView); } } } public void addShopView(String s) { TextView textView = new TextView(App.getContext()); textView.setText(s); textView.setPadding(10,10,10,10); textView.setTextColor(Color.BLACK); textView.setBackgroundResource(R.drawable.flow); addView(textView); } public FlowCallBack flowCallBack; public void setFlowCallBack(FlowCallBack flowCallBack) { this.flowCallBack = flowCallBack; } public interface FlowCallBack{ void getName(String s); } }
true
fc8b911dbd6fc2b7f3da3c75202c2bc0fb04ec97
Java
xrobert35/soundlink
/SoundLink_Server/soundlink_dao/src/main/java/soundlink/dao/repositories/PlaylistRepository.java
UTF-8
644
1.96875
2
[]
no_license
package soundlink.dao.repositories; 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 soundlink.model.entities.Playlist; public interface PlaylistRepository extends JpaRepository<Playlist, Integer> { @Query("SELECT playlist " + "FROM Playlist playlist " + "INNER JOIN playlist.users usersArtistes " + "INNER JOIN usersArtistes.user user " + "WHERE user.id = :userId") List<Playlist> getPlaylistsFromUserId(@Param("userId") Integer userId); }
true
31de2583ec06adbc29fdfd06e081f0bfca96449b
Java
s4kibs4mi/minio-play-rest-api
/app/security/DataValidation.java
UTF-8
1,293
2.5
2
[ "Apache-2.0" ]
permissive
package security; import com.fasterxml.jackson.databind.JsonNode; import play.data.validation.Constraints; public class DataValidation { private static Constraints.EmailValidator emailValidator = new Constraints.EmailValidator(); public static String filterForSqlInjection(String value) { return value.replace("'", "") .replaceAll("\"", "") .replaceAll("=", ""); } public static boolean isNotNull(Object value) { return value != null; } public static boolean isNull(Object value) { return value == null; } public static boolean isValid(String value) { return value != null && !value.trim().isEmpty(); } public static boolean isNotEmpty(String value) { return !value.isEmpty(); } public static boolean isEmpty(String value) { return value.isEmpty(); } public static boolean isEmail(String value) { return emailValidator.isValid(value); } public static String getParam(JsonNode value, String key) { JsonNode it = value.get(key); if (isNotNull(it)) { String param = filterForSqlInjection(it.asText()); return param.trim().isEmpty() ? null : param.trim(); } return null; } }
true
d38e3a5bd16a0234a05c19b620370ea5d6cc06a2
Java
viggyuvce/AuSpring2018
/DesignPrincipleAssignment/src/com/accolite/au/java/design/abstractFactory/HockeyStickFactory.java
UTF-8
452
3
3
[]
no_license
package com.accolite.au.java.design.abstractFactory; public class HockeyStickFactory extends Product implements SportsAbstractFactory { String type; public String getType() { return type; } public HockeyStickFactory(String brand2, float price2, String type) { super(brand2, price2); this.type = type; } @Override public Product createProduct() { // TODO Auto-generated method stub return new HockeyStick(brand,price,type); } }
true
46885c2cf9524f949e035ab15675412ff4cdf197
Java
Long0408Rin/A0720I1_LeHuuLong
/Module4/Sample/casestudy4/src/main/java/modul4/casestudy/model/CT_AttachService.java
UTF-8
637
2.109375
2
[]
no_license
package modul4.casestudy.model; import com.fasterxml.jackson.annotation.JsonBackReference; import lombok.*; import javax.persistence.*; import java.util.Set; @Entity @Data @AllArgsConstructor @NoArgsConstructor public class CT_AttachService { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private Double cost; private Integer unit; /* Cai enum ni lam sau private enum status */ @ManyToMany(mappedBy = "attachService") @JsonBackReference private Set<CT_ContractDetail> contractDetails; public CT_AttachService() { } }
true
0431c2ebd1cca59e0f14a344028f4de64adf7016
Java
liaozuliang/liaozl-app
/liaozl-utils/src/main/java/com/liaozl/utils/http/HttpClientUtil.java
UTF-8
6,373
2.578125
3
[]
no_license
package com.liaozl.utils.http; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; public class HttpClientUtil { private static final Logger log = Logger.getLogger(HttpClientUtil.class); public static String doGet(String url) { String content = null; HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpGet httpGet = new HttpGet(url); System.out.println(httpGet.getRequestLine()); try { HttpResponse httpResponse = closeableHttpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); System.out.println("status:" + httpResponse.getStatusLine()); if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) { // System.out.println("contentEncoding:" + entity.getContentEncoding()); content = EntityUtils.toString(entity); } } catch (IOException e) { log.error("doGet error: ", e); } finally { try { closeableHttpClient.close(); } catch (Exception e) { log.error("doGet error: ", e); } } return content; } public static String doGet(String url, Map<String, String> headerMap) { String content = null; HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // closeableHttpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // closeableHttpClient.getParams().setParameter("http.protocol.single-cookie-header", true); HttpGet httpGet = new HttpGet(url); if (headerMap != null) { for (String key : headerMap.keySet()) { if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(headerMap.get(key))) { httpGet.addHeader(key, headerMap.get(key)); } } } System.out.println(httpGet.getRequestLine()); try { HttpResponse httpResponse = closeableHttpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); System.out.println("status:" + httpResponse.getStatusLine()); if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) { // System.out.println("contentEncoding:" + entity.getContentEncoding()); content = EntityUtils.toString(entity); } } catch (IOException e) { log.error("doGet error: ", e); } finally { try { closeableHttpClient.close(); } catch (Exception e) { log.error("doGet error: ", e); } } return content; } public static String doPost(String url) { String content = null; HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(url); System.out.println(httpPost.getRequestLine()); try { HttpResponse httpResponse = closeableHttpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); System.out.println("status:" + httpResponse.getStatusLine()); if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) { // System.out.println("contentEncoding:" + entity.getContentEncoding()); content = EntityUtils.toString(entity); } } catch (IOException e) { log.error("doGet error: ", e); } finally { try { closeableHttpClient.close(); } catch (Exception e) { log.error("doGet error: ", e); } } return content; } public static String doPost(String url, Map<String, String> headerMap) { String content = null; HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(url); if (headerMap != null) { for (String key : headerMap.keySet()) { if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(headerMap.get(key))) { httpPost.addHeader(key, headerMap.get(key)); } } } System.out.println(httpPost.getRequestLine()); try { HttpResponse httpResponse = closeableHttpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); System.out.println("status:" + httpResponse.getStatusLine()); if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) { // System.out.println("contentEncoding:" + entity.getContentEncoding()); content = EntityUtils.toString(entity); } } catch (IOException e) { log.error("doGet error: ", e); } finally { try { closeableHttpClient.close(); } catch (Exception e) { log.error("doGet error: ", e); } } return content; } public static void main(String[] args) { String url = "http://www.baidu.com/"; // System.out.println(doGet(url)); url = "http://shanghai.qfang.com/"; // System.out.println(doGet(url)); Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Host", "www.91160.com"); headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0"); headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); headerMap.put("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); headerMap.put("Accept-Encoding", "gzip, deflate"); headerMap.put("Cookie", "testcookie=yes; __guid=YDuanf575e69da814115.03459441; ip_city=sz; PHPSESSID=0ir0tb5kc2rv8e5v43jfj26383; __jsluid=131c257435d6ca378b008166e8f50eba; NY_VALIDATE_KEY=8761377fcb05c80d0eb72e48cb8a4b53; _ga=GA1.2.1611631694.1465805230; _gat=1; Hm_lvt_c4e8e5b919a5c12647962ea08462e63b=1465805230; Hm_lpvt_c4e8e5b919a5c12647962ea08462e63b=1465805296; vlstatId=vlstat-1465805230000-472772089"); headerMap.put("Connection", "keep-alive"); headerMap.put("Cache-Control", "max-age=0"); url = "http://www.91160.com/doctors/index/docid-9833.html"; System.out.println(doGet(url)); System.out.println(doGet(url, headerMap)); System.out.println(doPost(url, headerMap)); url = "http://www.91160.com/doctors/index/docid-14683.html"; //System.out.println(doGet(url, headerMap)); } }
true
202dcd6e9fd7601b0267cbeaa1840b7535f4c51f
Java
arifkarabayir/Cryptology
/src/arifkarabayir/general/Message.java
UTF-8
455
2.84375
3
[]
no_license
package arifkarabayir.general; import java.math.BigInteger; public class Message { String binary; public Message(String str) { String result = ""; char[] messChar = str.toCharArray(); for (int i = 0; i < messChar.length; i++) { result += Integer.toBinaryString(messChar[i]) + ""; } this.binary = result; } public BigInteger toBigInteger() { return new BigInteger(this.binary); } }
true
731edf603a8738463d74a126810bdf1625008848
Java
wukw/lcncopy
/lcn-copy-client/src/main/java/com/lcn/copy/util/ConditionUtils.java
UTF-8
1,100
2.5625
3
[]
no_license
package com.lcn.copy.util; import com.lcn.copy.task.Task; import com.lcn.copy.task.TxTask; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConditionUtils { private static ConditionUtils instance = null; private Map<String, Task> taskMap = new ConcurrentHashMap<String, Task>(); /** * 单列 * @return */ public static ConditionUtils getInstance(){ if (instance == null) { synchronized (ConditionUtils.class) { if(instance==null){ instance = new ConditionUtils(); } } } return instance; } public Task createTask(String key){ TxTask task = new TxTask(); task.setKey(key); taskMap.put(key,task); return task; } public Task getTask(String key){ return taskMap.get(key); } public void removeTask(String key){ if(key != null) taskMap.remove(key); } public boolean hasKey(String key) { return taskMap.containsKey(key); } }
true
6b263bf3432591ed955a441f6f6cbe61d1ba2287
Java
zilvinasj/FxApi
/src/test/java/com/demo/TestUtils.java
UTF-8
1,099
2.28125
2
[]
no_license
package com.demo; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class TestUtils { private static ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()); public static String getSamplesJsonString(String jsonFileName) throws IOException { Resource resource = new ClassPathResource(jsonFileName); InputStream inputStream = resource.getInputStream(); return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } public static <T> T getSamplesJsonBean(String jsonFileName, Class<T> returnType) throws IOException { Resource resource = new ClassPathResource(jsonFileName); InputStream inputStream = resource.getInputStream(); return mapper.readValue(inputStream, returnType); } }
true
448bff92b75d2c687e210972ef6f7a64475ad10d
Java
zhouxiang-710/test
/src/main/java/digit/algorithm/AlgorithmTest.java
UTF-8
534
2.328125
2
[]
no_license
package digit.algorithm; import org.junit.Test; /** * @ Author :zhouxiang. * @ Date :Created in 15:42 2020/12/9 * @ Description:${description} * @ Modified By: * @Version: $version$ */ public class AlgorithmTest { /** * 功能描述: <br> * @Param: 二分法查找 * @Return: void * @Author: zhouxiang * @Date: 2020/12/9 15:43 */ @Test public void test(){ int[] a= new int[]{1,2,4,5,8,9,110}; System.out.println( AlgorithmEg.biSearch(a,4)); } }
true
333d5d6fc226b0b134ef5c52f485c121cfc9cbb2
Java
syampillai/SODevelopment
/src/main/java/com/storedobject/telegram/Bot.java
UTF-8
1,218
2.453125
2
[]
no_license
package com.storedobject.telegram; import com.storedobject.core.*; import com.storedobject.core.annotation.*; public final class Bot extends StoredObject { private String name; private String key; public Bot() { } public static void columns(Columns columns) { columns.add("Name", "text"); columns.add("Key", "text"); } public static void indices(Indices indices) { indices.add("lower(Name), T_Family", true); } public void setName(String name) { this.name = name; } @Column(order = 100) public String getName() { return name; } public void setKey(String key) { if (!loading()) { throw new Set_Not_Allowed("Key"); } this.key = key; } @SetNotAllowed @Column(style = "(secret)", order = 200) public String getKey() { return key; } @Override public void validateData(TransactionManager tm) throws Exception { if (StringUtility.isWhite(name)) { throw new Invalid_Value("Name"); } if (StringUtility.isWhite(key)) { throw new Invalid_Value("Key"); } super.validateData(tm); } }
true
69c64f2b944f0aec473ee8d1f308dd024df5628f
Java
jsimjava/j-sim
/dev/script/drcl/inet/socket/HelloClient4.java
UTF-8
2,158
2.609375
3
[ "BSD-3-Clause" ]
permissive
import java.net.*; import java.io.*; import drcl.comp.*; import drcl.inet.socket.SocketMaster; import drcl.inet.socket.InetSocket; // same as HelloClient3 except now is RestartableComponent public class HelloClient4 extends drcl.inet.socket.SocketApplication implements RestartableComponent { int remoteport; long localAddress, remoteAddress; public HelloClient4() { super(); } public HelloClient4(String id_) { super(id_); } public String info() { return "peer: " + remoteAddress + "/" + remoteport + "\n" + super.info(); } public void setup(long localAddr_, long remoteAddr_, int remotePort_) { localAddress = localAddr_; remoteAddress = remoteAddr_; remoteport = remotePort_; } protected void _start() { try { InetSocket s_ = socketMaster.newSocket(); socketMaster.bind(s_, localAddress, 0); socketMaster.aConnect(s_, remoteAddress, remoteport, this); } catch (Exception e_) { e_.printStackTrace(); } } public void connectFinished(InetSocket socket_) { try { BufferedReader is_ = new BufferedReader( new InputStreamReader(socket_.getInputStream())); OutputStream os_ = socket_.getOutputStream(); for (int i=0; i<HelloServer3.END; i++) { String line_ = is_.readLine(); System.out.println(line_ + " from " + socket_.getRemoteAddress() + "/" + socket_.getRemotePort()); // uncomment the following line blocks the thread at the server // from receiving the last line of messages, used to test // cancelling blocked receiving //if (i < HelloServer3.END-1) os_.write((getTime() + ": Hello Back" + i + "!\n").getBytes()); } socketMaster.aClose(socket_, this); } catch (Exception e_) { e_.printStackTrace(); } } public void closeFinished(InetSocket socket_) { //System.out.println("End with server: " + socket_.getRemoteAddress() // + "/" + socket_.getRemotePort()); System.out.println("End with server: " + socket_); } }
true
08769d9b19dce3f3931e6b7e2947a51c561b3a95
Java
MiyaJ/wxWork
/src/main/java/com/miya/wx/controller/TestController.java
UTF-8
1,212
1.976563
2
[]
no_license
package com.miya.wx.controller; import com.alibaba.fastjson.JSONObject; import com.miya.wx.model.Result; import com.miya.wx.service.IApprovalService; import com.miya.wx.service.IMessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author Caixiaowei * @ClassName TestController.java * @Description 测试api * @createTime 2020年06月18日 13:23:00 */ @RestController @RequestMapping("/test") public class TestController { @Autowired private IApprovalService approvalService; @Autowired private IMessageService messageService; @GetMapping("/getAccessToken") public Result getAccessToken() { return Result.success("success", approvalService.getAccessToken()); } @PostMapping("/applyEvent") public Result applyEvent(@RequestBody Map<String, Object> params) { JSONObject jsonObject = approvalService.applyEvent(params); return Result.success("success", jsonObject); } @PostMapping("/sendMsg") public Result sendMsg(@RequestBody JSONObject msg) { return Result.success("success", messageService.sendMsg(msg)); } }
true
adb02b3077cff0144198fab8e771547a9af166a2
Java
chenxiaoyu11/robolectric_androidunittest_demo
/app/src/main/java/com/changxiying/myapplication/activity/NextActivity.java
UTF-8
422
1.953125
2
[]
no_license
package com.changxiying.myapplication.activity; import android.app.Activity; import android.os.Bundle; import com.example.changxiying.myapplication.R; public class NextActivity extends Activity{ private static final String TAG="NextActivity"; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.next_activity); } }
true
322c8af597928f90353c9c1d5ed3f34fb505c733
Java
aioc/phais
/src/com/ausinformatics/phais/server/commands/SchedulePause.java
UTF-8
843
2.40625
2
[]
no_license
package com.ausinformatics.phais.server.commands; import java.io.PrintStream; import com.ausinformatics.phais.common.Config; import com.ausinformatics.phais.common.Config.Mode; import com.ausinformatics.phais.common.commander.Command; import com.ausinformatics.phais.server.Director; public class SchedulePause implements Command { private Director d; public SchedulePause(Director d) { this.d = d; } @Override public void execute(PrintStream out, String[] args) { Config config = d.getConfig(); config.mode = Mode.PAUSE; d.updateConfig(config); } @Override public String shortHelpString() { return "Pauses games being created"; } @Override public String detailedHelpString() { // TODO Auto-generated method stub return null; } }
true
79feca2b2944b08393e9515f1022bd73f871eb90
Java
Ametisss/HomeWork2
/HomeWork2.java
UTF-8
1,077
3.3125
3
[]
no_license
import java.sql.SQLOutput; public class HomeWork2 { public static void main(String[] args) { within10and20(125, 2); isPositiveOrNegative(-1); isNegative(5); printLine(5, "java"); } public static void within10and20(int a, int b) { int sum = a + b; if (sum >= 10 && sum <=20) { System.out.println("true"); } else { System.out.println("false"); } } public static void isPositiveOrNegative (int a) { if (a < 0) { System.out.println("Negative"); } else { System.out.println("Positive"); } } public static boolean isNegative(int a) { if (a < 0) { System.out.println("true"); return true; } else { System.out.println("false"); return false; } } public static void printLine(int a, String word) { for (int i = 0; i < a; i++) { System.out.println(word); } } }
true
f48eb2574bc37aa69638e20e2a0ba00eeabc1c9e
Java
Joy-byte/DA101G1
/TeamAceMVC_0801/src/com/game_detail/model/Game_detailDAO.java
UTF-8
6,438
2.6875
3
[]
no_license
package com.game_detail.model; import java.util.*; import java.sql.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class Game_detailDAO implements Game_detailDAO_interface { private static DataSource ds = null; static { try { Context ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB"); } catch (NamingException e) { e.printStackTrace(); } } private static final String GET_ALL_STMT = "SELECT * FROM Game_detail order by Gameroom_no"; private static final String INSERT_STMT = "INSERT INTO Game_detail (gameroom_no,mem_no,lens_status,topic_no,room_num)" + " VALUES ( ?, ?,?,?,?)"; private static final String GET_ONE_STMT = "SELECT * from Game_detail where Gameroom_no = ? And mem_no=?"; private static final String UPDATE = "UPDATE Game_detail set lens_status=?, topic_no=?,room_num=? where gameroom_no = ? And mem_no=?"; private static final String DELETE = "DELETE FROM Game_detail where gameroom_no = ? And mem_no=? "; @Override public void insert(Game_detailVO game_detailVO) { Connection con = null; PreparedStatement pstmt = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(INSERT_STMT); pstmt.setString(1, game_detailVO.getGameroom_no()); pstmt.setString(2, game_detailVO.getMem_no()); pstmt.setString(3, game_detailVO.getLens_status()); pstmt.setString(4, game_detailVO.getTopic_no()); pstmt.setInt(5, game_detailVO.getRoom_num()); pstmt.executeUpdate(); // Handle any SQL errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public List<Game_detailVO> getAll() { List<Game_detailVO> list = new ArrayList<Game_detailVO>(); Game_detailVO game_detailVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(GET_ALL_STMT); rs = pstmt.executeQuery(); while (rs.next()) { // game_detailVO Domain objects game_detailVO = new Game_detailVO(); game_detailVO.setGameroom_no(rs.getString("gameroom_no")); game_detailVO.setMem_no(rs.getString("mem_no")); game_detailVO.setLens_status(rs.getString("lens_status")); game_detailVO.setTopic_no(rs.getString("topic_no")); game_detailVO.setRoom_num(rs.getInt("room_num")); list.add(game_detailVO); // Store the row in the list } } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } return list; } public Game_detailVO findByPrimaryKey(String gameroom_no ,String mem_no) { Game_detailVO game_detailVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(GET_ONE_STMT); pstmt.setString(1, gameroom_no); pstmt.setString(2, mem_no); rs = pstmt.executeQuery(); while (rs.next()) { game_detailVO = new Game_detailVO(); game_detailVO.setGameroom_no(gameroom_no); game_detailVO.setMem_no(mem_no); game_detailVO.setLens_status(rs.getString("lens_status")); game_detailVO.setTopic_no(rs.getString("topic_no")); game_detailVO.setRoom_num(rs.getInt("room_num")); } } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } return game_detailVO; } @Override public void update(Game_detailVO game_detailVO) { Connection con = null; PreparedStatement pstmt = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(UPDATE); pstmt.setString(1, game_detailVO.getLens_status()); pstmt.setString(2, game_detailVO.getTopic_no()); pstmt.setInt(3, game_detailVO.getRoom_num()); pstmt.setString(4, game_detailVO.getGameroom_no()); pstmt.setString(5, game_detailVO.getMem_no()); pstmt.executeUpdate(); // Handle any driver errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public void delete(String gameroom_no,String mem_no) { Connection con = null; PreparedStatement pstmt = null; try { con = ds.getConnection(); pstmt = con.prepareStatement(DELETE); pstmt.setString(1, gameroom_no); pstmt.setString(2, mem_no); pstmt.executeUpdate(); // Handle any driver errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); // Clean up JDBC resources } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } }
true
aab083e31a60776c2d92533ea90a775747285e68
Java
KPI-Testing/Testing2017-18
/OleksandrChyslov Lab5/src/vtoroe.java
UTF-8
1,326
3.140625
3
[]
no_license
import java.io.FileWriter; import java.io.IOException; import java.lang.Math; import java.util.*; public class vtoroe { public static void main(String[] args) { List<Integer> Alpha = new ArrayList<>(150); List<Integer> Beta = new ArrayList<>(15); for (int i = 0; i < 150; i++) { Alpha.add((int)Math.floor(1 + Math.random() * 200)); } System.out.println("Alpha"); System.out.println(Alpha); for (int i = 0; i < 15; i++) { Beta.add(Alpha.get(i)); } for (int i = 15; i < 150; i++){ boolean B = false; int j = 0; Collections.sort(Beta); do { if (Alpha.get(i) > Beta.get(j)){ B = true; Beta.set(j,Alpha.get(i)); } j++; }while ((!B) && (j < 15)); } System.out.println("Beta"); System.out.println(Beta); try(FileWriter writer = new FileWriter("file.txt", false)) { for (int i : Beta) { writer.write(i + " "); } writer.flush(); } catch(IOException ex){ System.out.println(ex.getMessage()); } } }
true
57ecdd20067bcad95ae9a5dcf6f6f234a46e856f
Java
leonardogolfeto/apirestfotos
/src/main/java/com/info2b/api/apirest/controllers/ImagensController.java
UTF-8
1,269
2.15625
2
[]
no_license
package com.info2b.api.apirest.controllers; import com.info2b.api.apirest.models.Imagens; import com.info2b.api.apirest.repository.ImagensRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/api") public class ImagensController { @Autowired private ImagensRepository imagensRepository; @CrossOrigin @GetMapping("/imagens") public List<Imagens> listaImagens() { return imagensRepository.findAll(); } @CrossOrigin @GetMapping("/imagens/{id}") public Imagens listaImagens(@PathVariable(value = "id") long id) { return imagensRepository.findById(id); } @CrossOrigin @PostMapping("/imagens") public Imagens inserirImagens(@RequestBody Imagens imagem) { return imagensRepository.save(imagem); } @CrossOrigin @PutMapping("/imagens") public Imagens alterarImagens(@RequestBody Imagens imagem) { return imagensRepository.save(imagem); } @CrossOrigin @DeleteMapping("/imagens/delete/{id}") public void deletarImagens(@PathVariable(value = "id") long id) { imagensRepository.deleteById(id); } }
true
ea12b4c9f47b1a07957cd5c5811e5e2e325c3cb5
Java
nickbobo/sshe
/src/main/java/sy/action/base/ActivityuserAction.java
UTF-8
1,583
1.851563
2
[]
no_license
package sy.action.base; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.springframework.beans.factory.annotation.Autowired; import sy.action.BaseAction; import sy.model.base.ActivityUser; import sy.model.base.SessionInfo; import sy.model.easyui.Json; //import sy.model.easyui.Grid; import sy.service.base.ActivityUserServiceI; import sy.service.base.SyorganizationServiceI; import sy.util.base.ConfigUtil; import sy.util.base.HqlFilter; @SuppressWarnings("serial") @Namespace("/base") @Action public class ActivityuserAction extends BaseAction<ActivityUser> { // @Autowired // private ActivityUserServiceI userService; @Autowired public void setService(ActivityUserServiceI service){ this.service = service; } public void save(){ Json json = new Json(); if (data != null) { SessionInfo sessionInfo = (SessionInfo) getSession().getAttribute(ConfigUtil.getSessionInfoName()); ((ActivityUserServiceI) service).saveActivityUser(data, sessionInfo.getUser().getId()); json.setSuccess(true); } writeJson(json); } public void getActivityUser(){ List<ActivityUser> list= ((ActivityUserServiceI)service).find(); writeJson(list); } public void getActivityUserId(){ HqlFilter hqlFilter = new HqlFilter(getRequest()); hqlFilter.addFilter("QUERY_activityUser#id_S_EQ",id); ActivityUser activityUser = ((ActivityUserServiceI)service).getById(id); writeJson(activityUser); } }
true
4ebc2e2e19d7a4f3f39e4c3ff345808a402dec2f
Java
Sudhanshu127/FakeJsonServer
/src/main/java/research/MyHttpHandler.java
UTF-8
4,607
2.703125
3
[]
no_license
package research; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; // TODO: Implement request parameters class MyHttpHandler implements HttpHandler { private final Response response; private static final Logger logger = LogManager.getLogger(HttpHandler.class); public MyHttpHandler(Response value) { this.response = value; } @Override public void handle(HttpExchange httpExchange) throws IOException { Map<String,String> requestParamValue = new HashMap<>(); String finalResponse = ""; logger.trace("Fetching request parameters"); if("GET".equalsIgnoreCase(httpExchange.getRequestMethod())) { requestParamValue = handleGetRequest(httpExchange); finalResponse = response.getGetResponse(); } else if("POST".equalsIgnoreCase(httpExchange.getRequestMethod())){ logger.trace("Fetching request parameters"); requestParamValue = handlePostRequest(httpExchange); finalResponse = response.getPostResponse(); } // else if("PUT".equals(httpExchange.getRequestMethod())){ // requestParamValue = "Put"; // } // else if("DELETE".equals(httpExchange.getRequestMethod())){ // requestParamValue = "Delete"; // } logger.trace("Handling Response"); handleResponse(httpExchange,requestParamValue, finalResponse); } private Map<String, String> handleGetRequest(HttpExchange httpExchange) { Map<String,String> requestParameters = new HashMap<>(); for(NameValuePair value: URLEncodedUtils.parse(httpExchange.getRequestURI(),StandardCharsets.UTF_8)){ requestParameters.put(value.getName(),value.getValue()); } return requestParameters; } private Map<String, String> handlePostRequest(HttpExchange httpExchange) throws IOException { Map<String,String> requestParameters = new HashMap<>(); InputStream stream = httpExchange.getRequestBody(); StringBuilder myString = new StringBuilder(); int num; while( (num = stream.read()) != -1){ myString.append((char) num); } String contentType = httpExchange.getRequestHeaders().get("Content-Type").toString(); if(contentType.contains("application/x-www-form-urlencoded")){ return urlEncodedPost(myString.toString()); } else if(contentType.contains("multipart/form-data")){ return formDataPost(myString.toString()); } return requestParameters; } private Map<String, String> formDataPost(String myString) { Map<String, String> requestParameters = new HashMap<>(); String[] parameters = myString.split("\\r?\\n"); String key = null; for(int i = 0; i < parameters.length; i++){ if(i%4 == 1){ key = URLDecoder.decode(parameters[i].split(";")[1].split("=")[1], StandardCharsets.UTF_8); } else if(i%4 == 3){ requestParameters.put(key, URLDecoder.decode(parameters[i], StandardCharsets.UTF_8)); } } return requestParameters; } private Map<String, String> urlEncodedPost(String myString) { Map<String, String> requestParameters = new HashMap<>(); String[] parameters = myString.split("&"); for(String parameter : parameters){ requestParameters.put(URLDecoder.decode(parameter.split("=")[0],StandardCharsets.UTF_8), URLDecoder.decode(parameter.split("=")[1],StandardCharsets.UTF_8)); } return requestParameters; } private void handleResponse(HttpExchange httpExchange, Map<String, String> requestParamValue, String finalResponse) throws IOException { OutputStream outputStream = httpExchange.getResponseBody(); // encode HTML content // this line is a must httpExchange.getResponseHeaders().set("Content-Type", "application/json"); httpExchange.sendResponseHeaders(200, finalResponse.length()); outputStream.write(finalResponse.getBytes()); outputStream.flush(); outputStream.close(); } }
true
fb2f6fbc8e5bd0224dbec802fa7962392a684f8b
Java
Chrispol/projectJEE
/src/main/java/pl/dmcs/zai/service/UsufructuaryService.java
UTF-8
2,458
2.25
2
[]
no_license
package pl.dmcs.zai.service; import java.util.Collections; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import pl.dmcs.zai.dao.UsufructuaryRepository; import pl.dmcs.zai.domain.Usufructuary; public class UsufructuaryService implements UserDetailsService { @Autowired private UsufructuaryRepository usufructuaryRepository; private static final Logger log = LoggerFactory.getLogger(UsufructuaryService.class); @PostConstruct protected void initialize() { Usufructuary user = new Usufructuary("KrzysztofTumicki27@gmail.com", "admin","Krzysztof","Tumicki","603325711", "ROLE_ADMIN"); usufructuaryRepository.save(user); usufructuaryRepository.save(new Usufructuary("AndrzejSuchara@gmail.com", "admin","Andrzej","Suchara","603325711", "ROLE_ADMIN")); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Usufructuary usufructuary = usufructuaryRepository.findByEmail(username); if(usufructuary == null) { throw new UsernameNotFoundException("user not found"); } return createUser(usufructuary); } public void signin(Usufructuary usufructuary) { SecurityContextHolder.getContext().setAuthentication(authenticate(usufructuary)); } private Authentication authenticate(Usufructuary usufructuary) { return new UsernamePasswordAuthenticationToken(createUser(usufructuary), null, Collections.singleton(createAuthority(usufructuary))); } private User createUser(Usufructuary usufructuary) { return new User(usufructuary.getEmail(), usufructuary.getPassword(), Collections.singleton(createAuthority(usufructuary))); } private GrantedAuthority createAuthority(Usufructuary usufructuary) { return new SimpleGrantedAuthority(usufructuary.getTypeUser()); } }
true
e5c955c2d545b388d074b950fb581739990df66b
Java
inventionzhang/myeclipse
/src/org/lmars/network/neuralNetwork/ANNInputVector.java
UTF-8
1,178
2.609375
3
[]
no_license
package org.lmars.network.neuralNetwork; public class ANNInputVector { private int linkID;//路段编号 private int direction;//GPS行驶方向与路段方向关心 private int hour;//时 private int preHalfHour;//是否前半小时:1表示前半小时 private int workDay;//是否工作日:1表示工作日 private double travelTime;//路段通行时间 public void setLinkID(int linkID){ this.linkID = linkID; } public int getLinkID(){ return linkID; } public void setDirection(int direction){ this.direction = direction; } public int getDirection(){ return direction; } public void setHour(int hour){ this.hour = hour; } public int getHour(){ return hour; } public void setPreHalfHour(int preHalfHour){ this.preHalfHour = preHalfHour; } public int getPreHalfHour(){ return preHalfHour; } public void setWorkDay(int workDay){ this.workDay = workDay; } public int getWorkDay(){ return workDay; } public void setTravelTime(double travelTime){ this.travelTime = travelTime; } public double getTravelTime(){ return travelTime; } }
true
01dc6b9633bb1a97879028258ca233e78e43d418
Java
Anjitha-M/eWallet
/src/entities/CustomerWallet.java
UTF-8
1,175
2.796875
3
[]
no_license
package entities; import java.util.Objects; public class CustomerWallet { private String phoneNo; private String name; private double balance; public CustomerWallet() { } public CustomerWallet(String phoneNo, String name, double balance) { this.phoneNo = phoneNo; this.name = name; this.balance = balance; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof CustomerWallet)) { return false; } CustomerWallet that = (CustomerWallet) o; return that.phoneNo.equals(this.phoneNo); } @Override public int hashCode() { return phoneNo.hashCode(); } }
true
63efcbddfd3e5282fae6e69d08a889f3860c978e
Java
SirCodes-A-Lot/quizManager
/src/main/java/com/quiz/services/QuizService.java
UTF-8
3,741
2.609375
3
[]
no_license
package com.quiz.services; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import com.quiz.quizObjects.Question; import com.quiz.quizObjects.QuestionList; import com.quiz.quizObjects.Quiz; import com.quiz.statics.QuizConstants; @Service public class QuizService { private static int nextAvailableQuizId = 0; private QuizRepositoryService quizRepositoryService; @Autowired public QuizService (QuizRepositoryService quizRepositoryService) { this.quizRepositoryService = quizRepositoryService; } public static int getNextAvailableQuizId() { nextAvailableQuizId +=1; return nextAvailableQuizId; } public void addAllQuizesToModel(Model model) { model.addAttribute(QuizConstants.QUIZES, quizRepositoryService.getAllQuizes()); } public void addQuizDataToModel(Model model, String quizId) { model.addAttribute("questions",quizRepositoryService.getQuizById(Integer.parseInt(quizId)).getQuestions()); model.addAttribute(QuizConstants.SELECTED_QUIZ, quizRepositoryService.getQuizById(Integer.parseInt(quizId))); } public void saveQuizChangesToDatabase(HashMap<String,Object>submittedQuestionData) { int quizId = Integer.parseInt((String) submittedQuestionData.get("quizId")); Quiz quiz = quizRepositoryService.getQuizById(quizId); QuestionList questionList = new QuestionList(); ArrayList<Object> submittedQuestions = (ArrayList<Object>) submittedQuestionData.get("questions"); ArrayList<Question> newQuestions = new ArrayList<>(); for (int i=0; i <submittedQuestions.size(); i++) { HashMap<String,Object> questionData = (HashMap<String, Object>) submittedQuestions.get(i); String[] answerOptions = ((ArrayList<String>) questionData.get("answers")).toArray(new String[0]); String questionText= (String) questionData.get("question"); String correctAnswer = (String) questionData.get("correctAnswer"); Question newQuestion = new Question(answerOptions, correctAnswer, questionText, questionList); newQuestions.add(newQuestion); } quiz.setQuestions(questionList); quiz.setTitle((String) submittedQuestionData.get("title")); quiz.setDescription((String) submittedQuestionData.get("description")); questionList.setQuestions(newQuestions); quizRepositoryService.update(quiz); } public void makeNewDefaultQuiz() { QuestionList questionList = new QuestionList(); String[] questionAnswers = {"answer 1","answer 2"}; Question question = new Question(questionAnswers, "answer 1", "Type your question here", questionList); questionList.setQuestions(new ArrayList<Question>(Arrays.asList(question))); Quiz quiz = new Quiz( getNextAvailableQuizId(), "New Quiz", "description", questionList ); quizRepositoryService.save(quiz); } public void deleteQuiz(HashMap<String, Object> requestData) { int quizId = Integer.parseInt((String) requestData.get("quizId")); quizRepositoryService.deleteQuizById(quizId); } public int markQuiz(HashMap<String, Object> requestData) { int quizId = Integer.parseInt((String) requestData.get("quizId")); ArrayList<String> submittedAnswers = (ArrayList<String>) requestData.get("answers"); Quiz quiz = quizRepositoryService.getQuizById(quizId); List<Question> quizQuestions = quiz.getQuestions().getQuestions(); int score = 0; for (int i=0; i<submittedAnswers.size(); i++) { String providedAnswer = submittedAnswers.get(i); String correctAnswer = quizQuestions.get(i).getCorrectAnswer(); if (providedAnswer.contentEquals(correctAnswer)) { score +=1; } } return score; } }
true
e2dae7b66720f619f163503e609c6e4139a7e59a
Java
adamLangsti/Photo-Gallery
/app/src/main/java/com/example/photogallery/ImageItem.java
UTF-8
1,055
2.328125
2
[]
no_license
package com.example.photogallery; import android.net.Uri; import org.json.JSONException; import org.json.JSONObject; public class ImageItem { private String mTitle; private Uri mImg; public void setmTitle(String mTitle) { this.mTitle = mTitle; } private static final String JSON_TITLE = "title"; public String bitMap; public ImageItem(String bitMap, String mTitle) { this.mTitle = mTitle; this.bitMap = bitMap; } public String getTitle() { return mTitle; } public void setTitle(String title) { this.mTitle = title; } public Uri getImg() { return mImg; } public void setImg(Uri img) { this.mImg = img; } public ImageItem(JSONObject jo) throws JSONException { mTitle = jo.getString(JSON_TITLE); } public ImageItem(){} public JSONObject convertToJSON() throws JSONException { JSONObject jo = new JSONObject(); jo.put(JSON_TITLE, mTitle); return jo; } }
true
b5c5be17e7333935a2203e0498651fd4c14a3c6c
Java
Areya-y/graduation_IDEA
/.idea/src/main/java/com/xmut/project/service/userService.java
UTF-8
631
2.09375
2
[]
no_license
package com.xmut.project.service; import com.xmut.project.entity.user; import java.util.List; public interface userService { /** * 列出用户列表 * * @return userList */ List<user> queryUser(); /** * 根据openid列出用户具体信息 * * @return user */ user queryUserById(String openid); /** * 插入用户信息 * * @param user * @return */ boolean insertUser(user user); /** * 更新用户昵称 * * @param user * @return */ boolean updateUser(user user); }
true
df9c4c6c5cee9a613ea33791989b6dd3b4dc3641
Java
felipesere/tic-tac-toe
/src/test/java/de/fesere/tictactoe/players/UnbeatableAITest.java
UTF-8
2,362
2.6875
3
[ "MIT" ]
permissive
package de.fesere.tictactoe.players; import de.fesere.tictactoe.Board; import de.fesere.tictactoe.BoardBuilder; import de.fesere.tictactoe.Player; import org.junit.Test; import static de.fesere.tictactoe.Marker.O; import static de.fesere.tictactoe.Marker.X; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class UnbeatableAITest { private final UnbeatableAI player = new UnbeatableAI(X); @Test public void testSimpleDirectWin() { Board initial = new BoardBuilder().row("[X][X][ ]").build(); Board result = player.performMove(initial); assertThat(result.hasWinner(), is(true)); } @Test public void testAvoidDirectDefeat() { Board initial = new BoardBuilder().row("[O][O][ ]").build(); Board result = player.performMove(initial); Player opponent = new UnbeatableAI(O); result = opponent.performMove(result); assertThat(result.hasWinner(), is(false)); } @Test public void testShouldWinDirectlyWithColumn() { Board initial = new BoardBuilder() .row("[O][X][O]") .row("[X][X][O]") .row("[O][ ][ ]").build(); Board result = player.performMove(initial); assertThat(result.hasWinner(), is(true)); } @Test public void testShouldWinDirectlyWithDiagonal() { Board initial = new BoardBuilder() .row("[X][O][O]") .row("[O][X][O]") .row("[X][ ][ ]").build(); Board result = player.performMove(initial); assertThat(result.hasWinner(), is(true)); } @Test public void testShouldwinDirectlyRatherThanDefend() { Board initial = new BoardBuilder() .row("[X][O][O]") .row("[ ][X][O]") .row("[X][ ][ ]").build(); Board result = player.performMove(initial); assertThat(result.hasWinner(), is(true)); } @Test public void test_XshouldWinDirectlyAtTheBottomCenter() { Board initial = new BoardBuilder().row("[O][X][ ]") .row("[ ][X][ ]") .row("[O][ ][ ]").build(); Board result = player.performMove(initial); assertThat(result.hasWinner(), is(true)); } }
true
2d27942b473a7acfac11c520c16bc0d108353ae7
Java
yp19991017/BookManager
/src/service/BookService.java
UTF-8
232
1.96875
2
[]
no_license
package service; import java.util.List; import pojo.Book; public interface BookService { boolean saveBook(Book b); boolean updateBook(Book b); boolean deleteBookById(int id); List<Book> getbookList(); }
true
2ed307d8d2448cb46771726fc65ba96fc0f46770
Java
Hoolligan/GitHubTest
/src/Main.java
UTF-8
360
2.8125
3
[]
no_license
/** * Created by Администратор on 23.11.2016. */ public class Main { //Простой класс, чисто для проверки public static void main(String[] args) { System.out.println("Hello World!!!"); //Теперь внесём чуть изменений. System.out.println("Some changes"); } }
true
2af6ae0cb8a1f21acb2680ed2b0ae20cc58e70e0
Java
linxin1126/Master-Hotel
/hotel/src/main/java/cn/linxin/hotel/service/WorkerService.java
UTF-8
497
1.929688
2
[]
no_license
package cn.linxin.hotel.service; import cn.linxin.hotel.entity.Worker; import java.util.List; public interface WorkerService { int insert(Worker worker); int delete(int workerId); int updateById(Worker worker); Worker selectById(int workerId); Worker selectByUsername(String username); List<Worker> findAll(); List<Worker> selectByRole(String role); Worker login(String username,String password,String role); Worker login(String username,String password); }
true
ecd295d0fe14e0bc6ff9bd00a7418cb0c84c5e1f
Java
LeonMonster/student-educational-management-system
/src/com/scy/bean/Stu.java
UTF-8
1,407
2.53125
3
[]
no_license
package com.scy.bean; //一开始数据库没有设计好,stu类对应数据库的学生表,student类对应数据库的一张由学生-班级-专业连接起来的视图 public class Stu { private String sno; private String sname; private String spassword; private String ssex; private int sage; private int syear; private String saddress; private double scredit; private String clno; public String getSno() { return sno; } public void setSno(String sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSpassword() { return spassword; } public void setSpassword(String spassword) { this.spassword = spassword; } public String getSsex() { return ssex; } public void setSsex(String ssex) { this.ssex = ssex; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public int getSyear() { return syear; } public void setSyear(int syear) { this.syear = syear; } public String getSaddress() { return saddress; } public void setSaddress(String saddress) { this.saddress = saddress; } public double getScredit() { return scredit; } public void setScredit(double scredit) { this.scredit = scredit; } public String getClno() { return clno; } public void setClno(String clno) { this.clno = clno; } }
true
b91fb26aa454c5d5ab2188f5a6174d81ccbd6bd9
Java
kuali-student/cm-contribution
/ks-lum/ks-lum-rice/src/main/java/org/kuali/rice/student/lookup/keyvalues/AllOrgsValuesFinder.java
UTF-8
2,740
2.03125
2
[]
no_license
/** * Copyright 2010 The Kuali Foundation Licensed under the * Educational Community 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.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.kuali.rice.student.lookup.keyvalues; import java.util.ArrayList; import java.util.List; import org.kuali.rice.core.api.util.KeyValue; import org.kuali.student.r2.core.search.dto.SearchRequestInfo; import org.kuali.student.r2.core.search.dto.SearchResultCellInfo; import org.kuali.student.r2.core.search.dto.SearchResultRowInfo; import org.kuali.student.r2.common.util.ContextUtils; public class AllOrgsValuesFinder extends StudentKeyValuesBase { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(AllOrgsValuesFinder.class); public List<KeyValue> getKeyValues() { List<KeyValue> departments = new ArrayList<KeyValue>(); SearchRequestInfo searchRequest = new SearchRequestInfo(); searchRequest.setSearchKey("org.search.generic"); try { for (SearchResultRowInfo result : getOrganizationService().search(searchRequest, ContextUtils.getContextInfo()).getRows()) { String orgId = ""; String orgShortName = ""; String orgOptionalLongName = ""; String orgType = ""; for (SearchResultCellInfo resultCell : result.getCells()) { if ("org.resultColumn.orgId".equals(resultCell.getKey())) { orgId = resultCell.getValue(); } else if ("org.resultColumn.orgShortName".equals(resultCell.getKey())) { orgShortName = resultCell.getValue(); } else if ("org.resultColumn.orgOptionalLongName".equals(resultCell.getKey())) { orgOptionalLongName = resultCell.getValue(); } else if ("org.resultColumn.orgType".equals(resultCell.getKey())) { orgType = resultCell.getValue(); } } departments.add(buildKeyLabelPair(orgId, orgShortName, orgOptionalLongName, orgType)); } return departments; } catch (Exception e) { LOG.error("Error building KeyValues List", e); throw new RuntimeException(e); } } }
true
c68e738cccc1aa4cdb19267095e0e74b212c5ba6
Java
Kappa-Web/KappaCRM
/src/KappaCRM/Model/CModelIncident.java
UTF-8
1,913
2.15625
2
[]
no_license
package KappaCRM.Model; import java.util.Date; public class CModelIncident { private long id; private String libelle; private String description; private Date dateAjout; private Date dateModification; private Date dateFin; private String lieu; private String statut; private long fkIdEntiteSuperviseur; private long fkIdEntiteDeclarant; private long fkIdMission; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getLibelle() { return libelle; } public void setLibelle(String libelle) { this.libelle = libelle; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDateAjout() { return dateAjout; } public void setDateAjout(Date dateAjout) { this.dateAjout = dateAjout; } public Date getDateModification() { return dateModification; } public void setDateModification(Date dateModification) { this.dateModification = dateModification; } public Date getDateFin() { return dateFin; } public void setDateFin(Date dateFin) { this.dateFin = dateFin; } public String getLieu() { return lieu; } public void setLieu(String lieu) { this.lieu = lieu; } public String getStatut() { return statut; } public void setStatut(String statut) { this.statut = statut; } public long getFkIdEntiteSuperviseur() { return fkIdEntiteSuperviseur; } public void setFkIdEntiteSuperviseur(long fkIdEntiteSuperviseur) { this.fkIdEntiteSuperviseur = fkIdEntiteSuperviseur; } public long getFkIdEntiteDeclarant() { return fkIdEntiteDeclarant; } public void setFkIdEntiteDeclarant(long fkIdEntiteDeclarant) { this.fkIdEntiteDeclarant = fkIdEntiteDeclarant; } public long getFkIdMission() { return fkIdMission; } public void setFkIdMission(long fkIdMission) { this.fkIdMission = fkIdMission; } }
true
3bd0af2c82cbbd74f30caf989c35f35ea8a60be9
Java
icpmoviles/icp_commons
/core/src/main/java/es/icp/icp_commons/Utils/Utils.java
UTF-8
4,512
2.25
2
[]
no_license
package es.icp.icp_commons.Utils; import android.app.Activity; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Point; import android.media.ExifInterface; import android.util.DisplayMetrics; import android.view.Display; import androidx.core.app.ActivityCompat; import java.io.File; import es.icp.icp_commons.Helpers.Constantes; public class Utils { public static int dpToPx(Context context, int dp) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); } public static int pxToDp(Context context, int px) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); } public static boolean isDebuggable(Context context) { String packageName = context.getPackageName(); PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(packageName, PackageManager.GET_SIGNATURES); if (packageInfo != null) { ApplicationInfo applicationInfo = packageInfo.applicationInfo; return (0 != (applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE)); } return false; } public static int getCameraPhotoOrientation(String imagePath) { int rotate = 0; try { File imageFile = new File(imagePath); ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath()); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_270: rotate = 270; break; case ExifInterface.ORIENTATION_ROTATE_180: rotate = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90; break; } } catch (Exception e) { e.printStackTrace(); } return rotate; } public static Bitmap.CompressFormat getFormatFromFile(String path) { String[] pathSplit = path.split("\\."); String extension = pathSplit[pathSplit.length - 1]; switch (extension.toLowerCase()) { case "jpg": case "jpeg": return Bitmap.CompressFormat.JPEG; case "png": return Bitmap.CompressFormat.PNG; default: return Bitmap.CompressFormat.JPEG; } } public static boolean hasPermissions(Context context, String... permissions) { if (context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } public static boolean comprobarPermisos(Context context, String[] permisos) { if (!Utils.hasPermissions(context, permisos)) { ActivityCompat.requestPermissions(((Activity) context), permisos, Constantes.CODE_PERMISSIONS); return false; } else return true; } public static int pixelsHeightPercent(Context context) { return pixelsHeightPercent(context, 1f); } public static int pixelsHeightPercent(Context context, float percent) { if (percent < 0f || percent > 1f) return 0; Display display = ((Activity) context).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int height = size.y; return (int)(height * percent); } public static int pixelsWidthPercent(Context context) { return pixelsWidthPercent(context, 1f); } public static int pixelsWidthPercent(Context context, float percent) { if (percent < 0f || percent > 1f) return 0; Display display = ((Activity) context).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; return (int)(width * percent); } }
true
6f85add078b6e4177110f7224d8a36264d2c5e8b
Java
shuklasan78/spring-boot-microservice-2020
/src/main/java/com/opleiding/dms2/headers/RestHeaders.java
UTF-8
2,173
2.734375
3
[]
no_license
package com.opleiding.dms2.headers; import java.net.InetSocketAddress; import java.util.Map; import java.util.stream.Collectors; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/header") public class RestHeaders { @GetMapping("/greeting") public ResponseEntity<String> greeting(@RequestHeader("accept-language") String language) { // code that uses the language variable return new ResponseEntity<String>("Greeting, I received the header value = " + language, HttpStatus.OK); } @GetMapping("/listHeaders") public ResponseEntity<Map<String, String>> listAllHeaders( @RequestHeader Map<String, String> headers) { headers.forEach((key, value) -> { System.out.println("Header Value are :" + (String.format("Header '%s' = %s", key, value))); }); return new ResponseEntity<Map<String, String>>(headers, HttpStatus.OK); } @GetMapping("/multiValue") public ResponseEntity<String> multiValue( @RequestHeader MultiValueMap<String, String> headers) { headers.forEach((key, value) -> { System.out.println("Header Value are :" + (String.format( "Header '%s' = %s", key, value.stream().collect(Collectors.joining("|"))))); }); return new ResponseEntity<String>( String.format("Listed %d headers", headers.size()), HttpStatus.OK); } @GetMapping("/getBaseUrl") public ResponseEntity<String> getBaseUrl(@RequestHeader HttpHeaders headers) { InetSocketAddress host = headers.getHost(); String url = "http://" + host.getHostName() + ":" + host.getPort(); return new ResponseEntity<String>(String.format("Base URL = %s", url), HttpStatus.OK); } }
true
5c6ad2f2bcb5edd8e2c2947815afc19c26db76f4
Java
hmcts/unspec-service
/src/main/java/uk/gov/hmcts/reform/unspec/service/Time.java
UTF-8
130
1.78125
2
[ "MIT" ]
permissive
package uk.gov.hmcts.reform.unspec.service; import java.time.LocalDateTime; public interface Time { LocalDateTime now(); }
true
177eaee666c3835d9f004e5ee226d9b38cf92b1a
Java
julioizidoro/systm-eclipse
/src/br/com/travelmate/model/Pacotesfornecedor.java
UTF-8
4,407
2.078125
2
[]
no_license
package br.com.travelmate.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; /** * * @author wolverine */ @Entity @Table(name = "pacotesfornecedor") public class Pacotesfornecedor implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idpacotesfornecedor") private Integer idpacotesfornecedor; @Column(name = "datapagamento") @Temporal(TemporalType.DATE) private Date datapagamento; @Column(name = "idprodutotrecho") private Integer idprodutotrecho; @Size(max = 45) @Column(name = "tipoprodutotrecho") private String tipoprodutotrecho; @Column(name = "comprovante") private boolean comprovante; @Column(name = "emailenviado") private boolean emailenviado; @Column(name = "valor") private float valor; @Column(name = "numeroreserva") private String numeroreserva; @JoinColumn(name = "pacotes_idpacotes", referencedColumnName = "idpacotes") @ManyToOne(optional = false) private Pacotes pacotes; @JoinColumn(name = "fornecedor_idfornecedor", referencedColumnName = "idfornecedor") @ManyToOne(optional = false) private Fornecedor fornecedor; public Pacotesfornecedor() { valor = 0f; } public Pacotesfornecedor(Integer idpacotesfornecedor) { this.idpacotesfornecedor = idpacotesfornecedor; } public Integer getIdpacotesfornecedor() { return idpacotesfornecedor; } public void setIdpacotesfornecedor(Integer idpacotesfornecedor) { this.idpacotesfornecedor = idpacotesfornecedor; } public Date getDatapagamento() { return datapagamento; } public void setDatapagamento(Date datapagamento) { this.datapagamento = datapagamento; } public Integer getIdprodutotrecho() { return idprodutotrecho; } public void setIdprodutotrecho(Integer idprodutotrecho) { this.idprodutotrecho = idprodutotrecho; } public String getTipoprodutotrecho() { return tipoprodutotrecho; } public void setTipoprodutotrecho(String tipoprodutotrecho) { this.tipoprodutotrecho = tipoprodutotrecho; } public Pacotes getPacotes() { return pacotes; } public void setPacotes(Pacotes pacotes) { this.pacotes = pacotes; } public Fornecedor getFornecedor() { return fornecedor; } public void setFornecedor(Fornecedor fornecedor) { this.fornecedor = fornecedor; } public boolean isComprovante() { return comprovante; } public void setComprovante(boolean comprovante) { this.comprovante = comprovante; } public boolean isEmailenviado() { return emailenviado; } public void setEmailenviado(boolean emailenviado) { this.emailenviado = emailenviado; } public float getValor() { return valor; } public void setValor(float valor) { this.valor = valor; } public String getNumeroreserva() { return numeroreserva; } public void setNumeroreserva(String numeroreserva) { this.numeroreserva = numeroreserva; } @Override public int hashCode() { int hash = 0; hash += (idpacotesfornecedor != null ? idpacotesfornecedor.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof Pacotesfornecedor)) { return false; } Pacotesfornecedor other = (Pacotesfornecedor) object; if ((this.idpacotesfornecedor == null && other.idpacotesfornecedor != null) || (this.idpacotesfornecedor != null && !this.idpacotesfornecedor.equals(other.idpacotesfornecedor))) { return false; } return true; } @Override public String toString() { return "br.com.travelmate.model.Pacotesfornecedor[ idpacotesfornecedor=" + idpacotesfornecedor + " ]"; } }
true
284ade786b33cd5bcb788ec18f01f6239b78f78a
Java
jmmorillocolz/direct_printing_service
/src/DirectPrintingService.java
UTF-8
14,693
3.015625
3
[]
no_license
/** * Alternative to an applet to print tickets on any printer available on the client.  * Run as Java Web Start application. Prints directly without displaying dialog box.  *  * In this version pass parameters like: printer name, print values, scale, and text to be printed.  * In future versions will be added other features.  *  * This JAVA application only works when it's invoked from a .jnlp file  *  * Main requirements:  * Customer Side:  * - Mozilla Firefox browser (recommended)  * - Java 1.7 or higher  * - OS: Windows 7 or higher, and Linux  *  * Server Side:  * - Apache Server 2  * - jnlp file with the proper configuration  *  * Remarks: Compile and sign required to run properly.  *  * @author José Miguel Morillo jmmorillocolz@gmail.com  * @since 2017-09-05  * @version 1.0.0  *  * @bugs In browsers google chrome, Microsoft Edge and Opera show window download dialog * */ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PageFormat; import java.awt.print.PrinterJob; import java.util.*; import javax.print.PrintService; import javax.swing.JOptionPane; import javax.swing.JEditorPane; import java.net.URLDecoder; public class DirectPrintingService { /** * HTML content of the page to be printed */ static String HTML_CONTENT; /** * Map with the definition of message types */ private Map<String, Integer> TYPE_MESSAGES = new HashMap<String, Integer>(); /** * Contains printing services */ Map<String, PrintService> PRINTING_SERVICES = null; /** * Name of printer */ private String printerName = null; /** * Scale of printing, format: 0.00;0.00 */ private String printerScale = null; /** * Print settings. Format: x; y; width; height.      * where:      * x = print point in the X coordinate      * y = print point in the Y coordinate      * width = wide print area      * height = print area at the top * */ private String printerValues = null; /** * Stores the name of the printer * @param name */ protected void setPrinterName(String name){ this.printerName = URLDecoder.decode(name); } /** * Return Printer Name * @return printerName */ public String getPrinterName(){ return this.printerName; } /** * Stores print settings * @param values */ protected void setPrinterValues(String values){ this.printerValues = URLDecoder.decode(values); } /** * Returns the print settings * @return printerValues */ public String getPrinterValues(){ return this.printerValues; } /** * Stores the printing scale * @param scale */ protected void setPrinterScale(String scale){ this.printerScale = URLDecoder.decode(scale); } /** * Returns the value of the print scale * @return printerScale */ public String getPrinterScale(){ return this.printerScale; } /** * Class Construct */ public DirectPrintingService() { try { TYPE_MESSAGES = this.TypeMessages(); PRINTING_SERVICES = this.getPrintServices(); } catch (Exception e) { ShowMessage("Application error", e.getMessage(), "error"); } } /** * Main class method. Arguments are obtained from property      * <argument> of the .jnlp file that invokes this class. It's character      * required to pass the arguments in the following order:      *      * @param args the command line arguments: * 0 - HTML CONTENT (encoded with encode () or its equivalent in any language) * 1 - PRINTER NAME * 2 - PRINTER VALUES (X;Y;WIDTH;HEIGHT) * 3 - SCALE (1.00;1.00) */ public static void main(String[] args) { DirectPrintingService printdirect = new DirectPrintingService(); try { String content = args[0]; printdirect.setPrinterName(args[1]); printdirect.setPrinterValues(args[2]); printdirect.setPrinterScale(args[3]); if (content.isEmpty()) { throw new Exception("A required argument has not been found"); } HTML_CONTENT = URLDecoder.decode(content, "UTF-8"); printdirect.doPrint(); } catch (Exception e) { printdirect.ShowMessage("Application error", e.getMessage(), "error"); } } /** * Displays a message to the user. This message can be of several types.      *      * @param title Title corresponding to the message      * @param msg Content of the message to be displayed      * @param typeMessage Message Type * (plain,information,question,error,warning) */ private void ShowMessage(String title, String msg, String typeMessage) { JOptionPane.showMessageDialog(null, msg, title, TYPE_MESSAGES.get(typeMessage)); } /** * Create a Map with the types of messages that can be displayed to the user * * @return Map<String, Integer> */ private Map<String, Integer> TypeMessages() { Map<String, Integer> types = new HashMap<String, Integer>(); types.put("plain", JOptionPane.PLAIN_MESSAGE); types.put("information", JOptionPane.INFORMATION_MESSAGE); types.put("question", JOptionPane.QUESTION_MESSAGE); types.put("error", JOptionPane.ERROR_MESSAGE); types.put("warning", JOptionPane.WARNING_MESSAGE); return types; } /** * Gets the set of available printers. The returned map associates      * an object name representing the printer. * * @return Map<String, PrintService> */ private Map<String, PrintService> getPrintServices() { Map<String, PrintService> servicesMap = null; try { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPrintJobAccess(); } PrintService[] services = PrinterJob.lookupPrintServices(); if (services.length == 0) { throw new Exception("Print service not available"); } servicesMap = new HashMap<String, PrintService>(); for (PrintService service : services) { servicesMap.put(service.getName(), service); } } catch (Exception e) { this.ShowMessage("Application error", e.getMessage(), "error"); System.exit(0); } return servicesMap; } /** * Separates all the tickets contained in the HTML and places them in a list      *      * @return List <MatchInfo> List with ticket information and name      * of the printer associated with them */ private List<MatchInfo> setPrintSettings() { List<MatchInfo> matches = new ArrayList<MatchInfo>(); MatchInfo match = new MatchInfo( 0, this.getPrinterName(), parseMargins(this.getPrinterValues()), parseScale(this.getPrinterScale()) ); matches.add(match); return matches; } /** * Prepare the HTML for printing. Scroll through each ticket stored in the List * List<MatchInfo> * * @param List<MatchInfo> matches * @param Map<String, PrintService> printServices * @return Boolean * @throws PrinterException */ private Boolean prepareToPrintHTML(List<MatchInfo> matches) { List<String> errores = new ArrayList<String>(); Boolean printed = true; try { for (int i = 0; i < matches.size(); i++) { MatchInfo match = matches.get(i); boolean last = i == matches.size() - 1; int nextPos = last ? HTML_CONTENT.length() : matches.get(i + 1).fStart; String sub = HTML_CONTENT.substring(match.fStart, nextPos); printed = printContent(sub, match, PRINTING_SERVICES); if (!printed) { if (!errores.contains("\"" + match.printerName + "\" " + "Printer not found")) { errores.add("\"" + match.printerName + "\" " + "Printer not found"); } continue; } } if (!errores.isEmpty()) { printed = false; throw new Exception("Failed to load exceptions list"); } } catch (Exception e) { String nl = System.getProperty("line.separator"); String messageError = ""; for (String item : errores) { messageError += item + nl; } messageError = messageError.isEmpty() ? e.getMessage().toString() : messageError; this.ShowMessage("Could not print a document", messageError, "error"); } return printed; } /** * Print a ticket on the printer that corresponds.      *      * @param sub string with ticket information to print.      * @param match information with the print settings for the ticket.      * @param printServices Map with print services. * @return Boolean * @throws PrinterException */ private Boolean printContent(String sub, MatchInfo match, Map<String, PrintService> printServices) { try { PrintService service = getPrinter(printServices, match.printerName); if (service == null) { return false; } HTMLPrinter target = new HTMLPrinter(sub, match.fMargins, match.fScale.getX(), match.fScale.getY()); PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintService(service); printJob.setPrintable(target); printJob.print(); } catch (PrinterException e) { this.ShowMessage("Application error", "Aborted print service", "error"); } return true; } /** * Executes the necessary tasks to be able to print the document */ private void doPrint() { try { List<MatchInfo> matches = setPrintSettings(); prepareToPrintHTML(matches); } catch (Exception e) { this.ShowMessage("Application error", e.getMessage(), "error"); } } /** * Parser of the information of the margins to Rectangle2D format * * @param aMargins * @return Object Rectangle2D */ private static Rectangle2D parseMargins(String aMargins) { if ("default".equals(aMargins)) { return null; } else { String[] parts = aMargins.split(";"); return new Rectangle2D.Double( Double.parseDouble(parts[0]), Double.parseDouble(parts[1]), Double.parseDouble(parts[2]), Double.parseDouble(parts[3])); } } /** * Parsea la información de la escala a formato Point2D * * @param aScale * @return Object Point2D */ private static Point2D parseScale(String aScale) { String[] parts = aScale.split(";"); return new Point2D.Double( Double.parseDouble(parts[0]), Double.parseDouble(parts[1])); } /** * Contains the printing information */ private static class MatchInfo { public final int fStart; public final String printerName; public final Rectangle2D fMargins; public final Point2D fScale; public MatchInfo(int aStart, String aprinterName, Rectangle2D aMargins, Point2D aScale) { fStart = aStart; printerName = aprinterName; fMargins = aMargins; fScale = aScale; } } /** * Search for a printer by name on the map of detected printers. If he      * name is type "\\ Machine \ Printer" and can not find the printer, it does      * another search with only the name of the printer. */ private PrintService getPrinter(Map<String, PrintService> aServices, String aName) { PrintService service = aServices.get(aName); int index = aName.lastIndexOf('\\'); String lastName = aName.substring(index + 1); try { if (service != null) { return service; } if (index == -1) { return null; } service = aServices.get(lastName); } catch (Exception e) { System.out.println("Eroor"); } return service; } /** * This class represents a printable document. * Use a JEditorPane to render HTML rendering */ private class HTMLPrinter implements Printable { private JEditorPane printPane; private Rectangle2D fMargins; private double fScaleX; private double fScaleY; public HTMLPrinter(String aContent, Rectangle2D aMargins, double aScaleX, double aScaleY) { printPane = new JEditorPane(); printPane.setContentType("text/html"); printPane.setText(aContent); fMargins = aMargins; fScaleX = aScaleX; fScaleY = aScaleY; } @Override public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { if (pageIndex >= 1) { return Printable.NO_SUCH_PAGE; } double imgX; double imgY; double imgW; double imgH; if (fMargins == null) { imgX = pageFormat.getImageableX(); imgY = pageFormat.getImageableY(); imgW = pageFormat.getImageableWidth(); imgH = pageFormat.getImageableHeight(); } else { imgX = fMargins.getX(); imgY = fMargins.getY(); imgW = fMargins.getWidth(); imgH = fMargins.getHeight(); } Graphics2D g2d = (Graphics2D) graphics; g2d.translate(imgX, imgY); g2d.setClip(new Rectangle2D.Double(0, 0, imgW, imgH)); g2d.scale(fScaleX, fScaleY); printPane.setSize((int) imgW, 1); printPane.print(g2d); return Printable.PAGE_EXISTS; } } }
true
ec9014cd77314dceb2d908c328d05f3fafab90f4
Java
wdEffort/java8-study
/ex14/LoopSample04.java
UHC
713
3.921875
4
[]
no_license
package com.ezen.example; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * ݺ * for - 01 * * @author yoman * * 2019. 09. 25 * * Է ڸŭ '*' ϴ */ public class LoopSample04 { public static void main(String[] args) throws IOException { System.out.println(" * Ͻðڽϱ?"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int num = Integer.parseInt(str); // Է ŭ ݺؼ '*' մϴ. for (int i = 1; i <= num; i++) { System.out.print("*"); } } }
true
f2a83334cf26920bed4369f8a673d389ad4dd458
Java
deane163/springmvc-apiframework
/src/main/java/com/xiaoshu/exception/BussinessExceptionHandler.java
UTF-8
1,568
2.34375
2
[]
no_license
package com.xiaoshu.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * * code is far away from bug with the animal protecting * ┏┓   ┏┓ * ┏┛┻━━━┛┻┓ * ┃       ┃ * ┃   ━   ┃ * ┃ ┳┛ ┗┳ ┃ * ┃       ┃ * ┃   ┻   ┃ * ┃       ┃ * ┗━┓   ┏━┛ *   ┃   ┃神兽保佑 *   ┃   ┃代码无BUG! *   ┃   ┗━━━┓ *   ┃       ┣┓ *   ┃       ┏┛ *   ┗┓┓┏━┳┓┏┛ *    ┃┫┫ ┃┫┫ *    ┗┻┛ ┗┻┛ * * * @Description : 统一对定义的业务异常进行处理 * --------------------------------- * @Author : deane.administrator * @Date : Create in 2018年1月3日下午1:51:51 * * Copyright (C)2013-2018 小树盛凯科技 All rights reserved. */ @RestControllerAdvice public class BussinessExceptionHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler() public R handlerBussinessException(BussinessException exception){ logger.info("开始统一处理业务异常信息"); R r = new R(); r.put("code", exception.getCode()); r.put("msg", exception.getMessage()); return r; } }
true
99b520ba261d6bbb8c0e62d778f888028a47146e
Java
BhavnaBhamare/Foodee
/com/model/BLmanger.java
UTF-8
13,145
1.851563
2
[]
no_license
package com.model; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import com.pojo.Addhotel; import com.pojo.Nvegbiryanees; import com.pojo.Nvegchickenmaincourse; import com.pojo.Nvegeggmaincourse; import com.pojo.Nvegmenu; import com.pojo.Nvegmuttonmaincourse; import com.pojo.Nvegstarter; import com.pojo.Registration; import com.pojo.Role; import com.pojo.Roti; import com.pojo.Sweets; import com.pojo.Vegmenu; import com.pojo.Vegrice; import com.pojo.Vegsabji; import com.pojo.Vegstarter; public class BLmanger { SessionFactory factory = new Configuration().configure().buildSessionFactory(); public void Register(Registration r) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(r); transaction.commit(); session.close(); } public Role searchbyid(String rolltype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Role.class); criteria.add(Restrictions.eq("rolltype", rolltype)); Role ro = (Role) criteria.uniqueResult(); session.close(); return ro; } public Registration searchbyrollid(String emailid) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("emailid", emailid)); Registration ro = (Registration) criteria.uniqueResult(); return ro; } public Boolean searchemailpasswordforuser(String emailid, String password) { Registration r = searchbyepforuser(emailid, password); if (r != null && r.getEmailid().equals(emailid) && r.getPassword().equals(password)) { return true; } else { return null; } } private Registration searchbyepforuser(String emailid, String password) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("emailid", emailid)); criteria.add(Restrictions.eq("password", password)); Registration ro = (Registration) criteria.uniqueResult(); return ro; } public Boolean searchemailpasswordforhowner(String emailid, String password) { Registration r = searchbyepforhowner(emailid, password); if (r != null && r.getEmailid().equals(emailid) && r.getPassword().equals(password)) { return true; } else { return null; } } private Registration searchbyepforhowner(String emailid, String password) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("emailid", emailid)); criteria.add(Restrictions.eq("password", password)); Registration ro = (Registration) criteria.uniqueResult(); return ro; } public Registration searchId(String str) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("firstname", str)); Registration r2 = (Registration) criteria.uniqueResult(); return r2; } public void hoteldays(Addhotel h) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(h); transaction.commit(); session.close(); } public void savevegstater(Vegstarter st) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(st); transaction.commit(); session.close(); } public void saveveroti(Roti rt) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(rt); transaction.commit(); session.close(); } public void savesabji(Vegsabji sb) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(sb); transaction.commit(); session.close(); } public void saveverice(Vegrice ri) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(ri); transaction.commit(); session.close(); } public void savesweet(Sweets sw) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(sw); transaction.commit(); session.close(); } public void savenvegstater(Nvegstarter st1) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(st1); transaction.commit(); session.close(); } public void saaveegg(Nvegeggmaincourse egg) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(egg); transaction.commit(); session.close(); } public void savechicken(Nvegchickenmaincourse ch) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(ch); transaction.commit(); session.close(); } public void savemutton(Nvegmuttonmaincourse mu) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(mu); transaction.commit(); session.close(); } public void savebiryanee(Nvegbiryanees bir) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(bir); transaction.commit(); session.close(); } public Addhotel searchbyId(String str1) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Addhotel.class); criteria.add(Restrictions.eq("hotelname", str1)); Addhotel h1 = (Addhotel) criteria.uniqueResult(); return h1; } public List<Vegstarter> searchlist() { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Vegstarter.class); List<Vegstarter> s = criteria.list(); return s; } public Boolean searchemailpasswordforadmin(String emailid, String password) { Registration r = searchbyepforadmin(emailid, password); if (r != null && r.getEmailid().equals(emailid) && r.getPassword().equals(password)) { return true; } else { return null; } } private Registration searchbyepforadmin(String emailid, String password) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("emailid", emailid)); criteria.add(Restrictions.eq("password", password)); Registration ro = (Registration) criteria.uniqueResult(); return ro; } public void savevegmenu(Vegmenu ve) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(ve); transaction.commit(); session.close(); } public List<Addhotel> searchhotellist() { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Addhotel.class); List<Addhotel> s1 = criteria.list(); return s1; } public Vegstarter searchvegstarterid(String vegstatermenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Vegstarter.class); criteria.add(Restrictions.eq("vegstatermenutype", vegstatermenutype)); Vegstarter st = (Vegstarter) criteria.uniqueResult(); return st; } public Vegrice searchvegricebyid(String vegmenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Vegrice.class); criteria.add(Restrictions.eq("vegmenutype", vegmenutype)); Vegrice ri = (Vegrice) criteria.uniqueResult(); return ri; } public Vegsabji searchvegsbjibyid(String sabjimenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Vegsabji.class); criteria.add(Restrictions.eq("sabjimenutype", sabjimenutype)); Vegsabji sb = (Vegsabji) criteria.uniqueResult(); return sb; } public Roti searchrotibyid(String roticategory) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Roti.class); criteria.add(Restrictions.eq("roticategory", roticategory)); Roti rt = (Roti) criteria.uniqueResult(); return rt; } public Sweets searchsweetbyid(String sweetmenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Sweets.class); criteria.add(Restrictions.eq("sweetmenutype", sweetmenutype)); Sweets sw = (Sweets) criteria.uniqueResult(); return sw; } public Nvegstarter seachnonstater(String nvegstartermenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Nvegstarter.class); criteria.add(Restrictions.eq("nvegstartermenutype", nvegstartermenutype)); Nvegstarter str1 = (Nvegstarter) criteria.uniqueResult(); return str1; } public Nvegeggmaincourse sercheggbyid(String eggmenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Nvegeggmaincourse.class); criteria.add(Restrictions.eq("eggmenutype", eggmenutype)); Nvegeggmaincourse egg = (Nvegeggmaincourse) criteria.uniqueResult(); return egg; } public Nvegchickenmaincourse searchchickenbyid(String chickenmenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Nvegchickenmaincourse.class); criteria.add(Restrictions.eq("chickenmenutype", chickenmenutype)); Nvegchickenmaincourse ch = (Nvegchickenmaincourse) criteria.uniqueResult(); return ch; } public Nvegmuttonmaincourse searchmuttonid(String muttonmenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Nvegmuttonmaincourse.class); criteria.add(Restrictions.eq("muttonmenutype", muttonmenutype)); Nvegmuttonmaincourse mu = (Nvegmuttonmaincourse) criteria.uniqueResult(); return mu; } public Nvegbiryanees searchbirid(String biryaneemenutype) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Nvegbiryanees.class); criteria.add(Restrictions.eq("biryaneemenutype", biryaneemenutype)); Nvegbiryanees bir = (Nvegbiryanees) criteria.uniqueResult(); return bir; } public void savenonvegdata(Nvegmenu non) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.save(non); transaction.commit(); session.close(); } public Addhotel searchhotel(String hotelname) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Addhotel.class); criteria.add(Restrictions.eq("hotelname", hotelname)); Addhotel h1 = (Addhotel) criteria.uniqueResult(); return h1; } public List<Vegmenu> searchvegmenu(Addhotel h) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Vegmenu.class); criteria.add(Restrictions.eq("addhotel", h)); List<Vegmenu> veg = criteria.list(); return veg; } public Vegmenu searchhotal(String hotelname) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Vegmenu.class); criteria.add(Restrictions.eq("hotelname", hotelname)); Vegmenu ve = (Vegmenu) criteria.uniqueResult(); return ve; } public List<Nvegmenu> searchnonvegmenu(Addhotel h) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Nvegmenu.class); criteria.add(Restrictions.eq("addhotel", h)); List<Nvegmenu> nonveg = criteria.list(); return nonveg; } public List<Registration> searchreglist() { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); List<Registration> k = criteria.list(); return k; } public void updateuserprofile(Registration r) { Session session = factory.openSession(); Transaction transaction = session.beginTransaction(); session.update(r); transaction.commit(); session.close(); } public Registration searchuserp(String emailid) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("emailid", emailid)); Registration r1 = (Registration) criteria.uniqueResult(); return r1; } public Role searchroleid2(String user) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Role.class); criteria.add(Restrictions.eq("rolltype", user)); Role r2 = (Role) criteria.uniqueResult(); return r2; } public List<Registration> searchuser(Role role2) { Session session = factory.openSession(); Criteria criteria = session.createCriteria(Registration.class); criteria.add(Restrictions.eq("role", role2)); List<Registration> r = criteria.list(); return r; } }
true
3f51bf17c645479fc51ce42bc9fea5e2d930a210
Java
rubendarioramirez/PlotGenerator
/app/src/main/java/com/plotgen/rramirez/plotgenerator/Guides/GuideRoleFragment.java
UTF-8
2,191
1.898438
2
[]
no_license
package com.plotgen.rramirez.plotgenerator.Guides; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.plotgen.rramirez.plotgenerator.Common.Common; import com.plotgen.rramirez.plotgenerator.MainActivity; import com.plotgen.rramirez.plotgenerator.R; import java.util.ArrayList; import java.util.Arrays; /** * A simple {@link Fragment} subclass. */ public class GuideRoleFragment extends Fragment { TextView char_guide_content_tv; private AdView mAdView; public GuideRoleFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment ((MainActivity)getActivity()).setActionBarTitle("Roles"); View myFragmentView = inflater.inflate(R.layout.fragment_guide_role, container, false); if(!Common.isPAU) { mAdView = (AdView) myFragmentView.findViewById(R.id.adView_charguide); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); } char_guide_content_tv = myFragmentView.findViewById(R.id.char_guide_content_tv); ArrayList<String> titles = new ArrayList<String>(); ArrayList<String> descriptions = new ArrayList<String>(); titles.addAll(Arrays.asList(myFragmentView.getResources().getStringArray(R.array.char_guide_types_titles))); descriptions.addAll(Arrays.asList(myFragmentView.getResources().getStringArray(R.array.char_guide_types_desc))); StringBuffer sb=new StringBuffer(); for(int i =0; i<titles.size(); i++){ sb.append("<b>" + titles.get(i) + "</b><br>"); sb.append(descriptions.get(i) + "<br><br>"); } char_guide_content_tv.setText(Html.fromHtml(sb.toString())); return myFragmentView; } }
true
6c273b91061bee1e141701de0e16bc6e46ecb84c
Java
bhuvan080682/org-uhc-pharma
/src/test/java/org/uhc/ws/service/test/AbstractControllerTest.java
UTF-8
1,087
1.648438
2
[]
no_license
package org.uhc.ws.service.test; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvcBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.uhc.ws.api.DrugsController; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @WebAppConfiguration public abstract class AbstractControllerTest extends AbstractTest { @Autowired protected WebApplicationContext context; protected MockMvc mvc; protected void setup(){ mvc = MockMvcBuilders.webAppContextSetup(context).build(); } protected void setup(DrugsController controller){ mvc = MockMvcBuilders.standaloneSetup(controller).build(); } }
true
32a3fc126e315a7f73c14c8cedb03da546b2c4fa
Java
danja/2001
/citnames/backup/iou/src/com/isacat/iou/database/DBCPTest.java
UTF-8
2,405
2.671875
3
[]
no_license
/* * DBCPTest.java * * Created on 08 January 2001, 11:25 */ package com.isacat.iou.database; import java.util.*; import java.sql.*; import javax.sql.*; /** * @author Danny Ayers * @created 26 March 2001 * @version */ public class DBCPTest { DBConnectionPool pool = null; /** * Creates new DBCPTest */ public DBCPTest() { pool = new DBConnectionPool(getPoolProperties()); query(); } public void query() { java.sql.Connection con = null; // pool = new DBConnectionPool(getPoolProperties()); con = pool.getConnection(); System.out.println(pool.getStatus()); try { Statement stmt = con.createStatement(); java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM sysusers"); printResultSet(rs); con.close(); con = null; } catch (Exception e) { e.printStackTrace(); } } // end run // print the Resultset to the PrintStream (by default the console) void printResultSet(ResultSet rs) throws SQLException { int i; ResultSetMetaData rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); StringBuffer buffer = new StringBuffer(); for (i = 1; i <= count; i++) { if (i > 1) { buffer.append("\t\t"); } buffer.append(rsmd.getColumnName(i)); } System.out.println(buffer.toString()); while (rs.next()) { buffer = new StringBuffer(); for (i = 1; i <= count; i++) { if (i > 1) { buffer.append("\t\t"); } String obj = rs.getString(i); buffer.append(String.valueOf(obj)); } System.out.println(buffer.toString()); } } public static Properties getPoolProperties() { Properties properties = new Properties(); properties.setProperty("pool.database", "jdbc:odbc:iou"); properties.setProperty("pool.driver", "sun.jdbc.odbc.JdbcOdbcDriver"); properties.setProperty("pool.catalog", ""); properties.setProperty("pool.user", "wrox"); properties.setProperty("pool.password", "xorw"); properties.setProperty("pool.size", "10"); properties.setProperty("pool.timeout", "10"); return properties; } /** * @param args the command line arguments */ public static void main(String args[]) { new DBCPTest(); } }
true
e7e397c5f697d6d571b2628fe9f5739aec1b383d
Java
zeeegeee/projectBark
/src/classes/animal.java
UTF-8
2,574
2.953125
3
[ "MIT" ]
permissive
/* Authors: Moe, Sakshi, Olivia, Yui, and Caity Date: 6/26/2018 Purpose: This is the Animal class */ package classes; import java.util.ArrayList; public class animal { public String aID; public String aSpecies; public String aName; public String aAge; public String aGender; public String aDescription; public String aPic; public static ArrayList<animal> animalArray = new ArrayList<>(); public static int animalCount = 0; // Constructors public animal(String aid, String aName, String aSpecies, String aAge, String aGender, String aDescription, String aPic) { this.aSpecies = aSpecies; this.aAge = aAge; this.aGender = aGender; this.aName = aName; this.aDescription = aDescription; this.aID = aid; this.aPic = aPic; } public animal(String aid, String aName, String aSpecies, String aAge, String aGender, String aDescription) { this.aSpecies = aSpecies; this.aAge = aAge; this.aGender = aGender; this.aName = aName; this.aDescription = aDescription; this.aID = aid; } // create getter public String getAID() { return aID; } // create setter public void setAID(String aID) { this.aID = aID; } // create getter public String getASpecies() { return aSpecies; } // create getter public void setASpecies(String aSpecies) { this.aSpecies = aSpecies; } // create getter public String getAName() { return aName; } // create setter public void setAName(String aName) { this.aName = aName; } // create getter public String getAAge() { return aAge; } // create getter public void setAAge(String aAge) { this.aAge = aAge; } // create getter public String getAGender() { return aGender; } // create setter public void setAGender(String aGender) { this.aGender = aGender; } // create getter public String getADescription() { return aDescription; } // create setter public void setADescription(String aDescription) { this.aDescription = aDescription; } // create getter public String getAPic() { return aPic; } // create setter public void setAPic(String aPic) { this.aPic = aPic; } public String toString() { return aName; } }
true
a1bed43e24a3354f2a4c47fbb3a40bd23c95b1e4
Java
Ryze-Zhao/JavaSeStudy
/java8_new_features/src/main/java/com/zhaolearn/lambda/deep/study2/ConstructorRefTest.java
UTF-8
2,416
3.828125
4
[]
no_license
package com.zhaolearn.lambda.deep.study2; import org.junit.Test; import java.util.Arrays; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; /** * 一、构造器引用 * 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。 * 抽象方法的返回值类型即为构造器所属的类的类型 * * 二、数组引用 * 大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。 * * Created by shkstart */ public class ConstructorRefTest { //构造器引用 //Supplier中的T get() //Staff的空参构造器:Staff() @Test public void test1(){ Supplier<Staff> sup = new Supplier<Staff>() { @Override public Staff get() { return new Staff(); } }; System.out.println("*******************"); Supplier<Staff> sup1 = () -> new Staff(); System.out.println(sup1.get()); System.out.println("*******************"); Supplier<Staff> sup2 = Staff :: new; System.out.println(sup2.get()); } //Function中的R apply(T t) @Test public void test2(){ Function<Integer,Staff> func1 = id -> new Staff(id); Staff Staff = func1.apply(1001); System.out.println(Staff); System.out.println("*******************"); Function<Integer,Staff> func2 = Staff :: new; Staff Staff1 = func2.apply(1002); System.out.println(Staff1); } //BiFunction中的R apply(T t,U u) @Test public void test3(){ BiFunction<Integer,String,Staff> func1 = (id,name) -> new Staff(id,name); System.out.println(func1.apply(1001,"Tom")); System.out.println("*******************"); BiFunction<Integer,String,Staff> func2 = Staff :: new; System.out.println(func2.apply(1002,"Tom")); } //数组引用 //Function中的R apply(T t) @Test public void test4(){ Function<Integer,String[]> func1 = length -> new String[length]; String[] arr1 = func1.apply(5); System.out.println(Arrays.toString(arr1)); System.out.println("*******************"); Function<Integer,String[]> func2 = String[] :: new; String[] arr2 = func2.apply(10); System.out.println(Arrays.toString(arr2)); } }
true