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
6acbcfc46c557c223777fce97e5a147fdd8389d1
Java
marceloluisr/Inteligencia-Artifical
/Algoritmos de Busca_Java/src/com/marcelo/mapa/Cidade.java
UTF-8
1,470
3.28125
3
[]
no_license
package com.marcelo.mapa; import java.util.ArrayList; public class Cidade implements Comparable<Cidade>{ private String nome; private boolean visitado; private ArrayList<Adjacente> adjacentes; private int custo; public Cidade(String nome) { this.nome = nome; this.visitado = false; this.adjacentes = new ArrayList<>(); } public Cidade(String nome, int custo) { this.nome = nome; this.visitado = false; this.adjacentes = new ArrayList<>(); this.custo = custo; } public void addCidadeAdjacente(Adjacente c) { this.adjacentes.add(c); } public String getNome() { return nome; } public boolean isVisitado() { return visitado; } public ArrayList<Adjacente> getAdjacentes() { return adjacentes; } public void setVisitado(boolean visitado) { this.visitado = visitado; } public int getCusto() { return custo; } @Override public int compareTo(Cidade c) { if (this.getCusto() > c.getCusto()) { return 1; } else if(this.getCusto() < c.getCusto()) { return -1; } return 0; } @Override public String toString() { return "Cidade{" + "nome='" + nome + '\'' + ", custo=" + custo + '}'; } }
true
f3518ca279a89475de6a8ecfa7628a581d207c76
Java
eusoon/Mobile-Catalog
/soa-rest-sec/src/main/java/ong/eu/soon/security/web/authentication/NoRedirectStrategy.java
UTF-8
445
2.25
2
[]
no_license
package ong.eu.soon.security.web.authentication; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.web.RedirectStrategy; public class NoRedirectStrategy implements RedirectStrategy { @Override public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) { // Forget about redirecting, there is no need! } }
true
7021949db905f116a26bba378a199b36d08dcfae
Java
wingRexx98/SpringProject
/src/main/java/com/restaurant/controller/BaseController.java
UTF-8
9,304
2.265625
2
[]
no_license
package com.restaurant.controller; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.restaurant.dao.FoodDAO; import com.restaurant.dao.OrderDAO; import com.restaurant.form.CustomerForm; import com.restaurant.model.Customer; import com.restaurant.model.Food; import com.restaurant.model.FoodInfo; import com.restaurant.model.Order; import com.restaurant.model.OrderInfo; import com.restaurant.model.ShoppingCart; import com.restaurant.util.Utils; @Controller public class BaseController { @Autowired private FoodDAO foodDAO; @Autowired private OrderDAO orderDAO; @Autowired public JavaMailSender emailSender; @RequestMapping("/403") public String accessDenied(Principal principal) { return "/403"; } @RequestMapping("/") public String home() { return "index"; } ////////////////////////////////// Shopping cart /** * Add the product into the cart * * @param request * @param model * @param id * @return */ @RequestMapping({ "/buyProduct" }) public String listProductHandler(HttpServletRequest request, Model model, // @RequestParam(value = "id", defaultValue = "") int id) { Food product = null; if (id != 0) { product = foodDAO.findFood(id); } if (product != null) { FoodInfo info = new FoodInfo(product); ShoppingCart cartInfo = Utils.getCartInSession(request); cartInfo.addProductIntoCart(info, 1); } return "redirect:/shoppingCart"; } /** * Remove product from cart * * @param request * @param model * @param id * @return */ @RequestMapping({ "/shoppingCartRemoveProduct" }) public String removeProductHandler(HttpServletRequest request, Model model, // @RequestParam(value = "id", defaultValue = "") int id) { Food product = null; if (id != 0) { product = foodDAO.findFood(id); } if (product != null) { FoodInfo info = new FoodInfo(product); ShoppingCart cartInfo = Utils.getCartInSession(request); cartInfo.removeProduct(info); } return "redirect:/shoppingCart"; } /** * Update the quantity of a product in a order * * @param request * @param model * @param cartForm * @return */ @RequestMapping(value = { "/shoppingCart" }, method = RequestMethod.POST) public String shoppingCartUpdateQty(HttpServletRequest request, // Model model, // @ModelAttribute("cartForm") ShoppingCart cartForm) { ShoppingCart cartInfo = Utils.getCartInSession(request); cartInfo.updateQuantity(cartForm); return "redirect:/shoppingCart"; } /** * Handle the cart by storing it into the session * * @param request * @param model * @return */ @RequestMapping(value = { "/shoppingCart" }, method = RequestMethod.GET) public String shoppingCartHandler(HttpServletRequest request, Model model) { ShoppingCart myCart = Utils.getCartInSession(request); model.addAttribute("cartForm", myCart); return "shoppingCart"; } /** * Input customer info */ @RequestMapping(value = { "/shoppingCartCustomer" }, method = RequestMethod.GET) public String shoppingCartCustomerForm(HttpServletRequest request, Model model) { ShoppingCart cartInfo = Utils.getCartInSession(request); if (cartInfo.isEmpty()) { return "redirect:/shoppingCart"; } Customer customer = cartInfo.getCustomer(); CustomerForm customerForm = new CustomerForm(); if (customer != null) { customerForm.setCustName(customer.getCustName()); customerForm.setEmail(customer.getEmail()); customerForm.setPhone(customer.getPhone()); customerForm.setAddress(customer.getAddress()); } model.addAttribute("customerForm", customerForm); return "shoppingCartCustomer"; } /** * Save the input customer info * * @param request * @param model * @param customerForm * @param result * @param redirectAttributes * @return */ @RequestMapping(value = { "/shoppingCartCustomer" }, method = RequestMethod.POST) public String shoppingCartCustomerSave(HttpServletRequest request, // Model model, // @ModelAttribute("customerForm") CustomerForm customerForm, BindingResult result, // final RedirectAttributes redirectAttributes) { if (result.hasErrors()) { customerForm.setValid(false); return "shoppingCartCustomer"; } customerForm.setValid(true); ShoppingCart cartInfo = Utils.getCartInSession(request); Customer customer = new Customer(); if (customerForm != null) { customer.setCustName(customerForm.getCustName()); customer.setEmail(customerForm.getEmail()); customer.setPhone(customerForm.getPhone()); customer.setAddress(customerForm.getAddress()); } cartInfo.setCustomer(customer); model.addAttribute("customer", customer); return "redirect:/shoppingCartConfirmation"; } /** * Confirm form * * @param request * @param model * @return */ @RequestMapping(value = { "/shoppingCartConfirmation" }, method = RequestMethod.GET) public String shoppingCartConfirmationReview(HttpServletRequest request, Model model) { ShoppingCart cartInfo = Utils.getCartInSession(request); // if the cart has no items if (cartInfo == null || cartInfo.isEmpty()) { // go back to cart to add items return "redirect:/shoppingCart"; } else if (!cartInfo.isValidCustomer()) { // the customer is not valid return "redirect:/shoppingCartCustomer"; } model.addAttribute("myCart", cartInfo); return "shoppingCartConfirmation"; } /** * Complete the purchase * * @param request * @param model * @return */ @RequestMapping(value = { "/completeConfirmation" }, method = RequestMethod.POST) public String shoppingCartConfirmationSave(HttpServletRequest request, Model model) { ShoppingCart cartInfo = Utils.getCartInSession(request); if (cartInfo == null || cartInfo.isEmpty()) { return "redirect:/shoppingCart"; } else if (!cartInfo.isValidCustomer()) { return "redirect:/shoppingCartCustomer"; } try { orderDAO.saveOrder(cartInfo); sendSimpleEmail(orderDAO.toOrderInfo(cartInfo)); } catch (Exception e) { return "shoppingCartConfirmation"; } return "redirect:/confirmPurchaseForm"; } /** * Confirm the order * * @param model * @return */ @RequestMapping(value = { "/confirmPurchaseForm" }, method = RequestMethod.GET) public String completePurChaseForm(Model model) { return "confirmPurchase"; } /** * Confirm code validate * * @param request * @param model * @param conCode * @return */ @RequestMapping(value = { "/confirmPurchase" }, method = RequestMethod.POST) public String completePurChase(HttpServletRequest request, Model model, @RequestParam("conCode") String conCode) { try { String message = orderDAO.confirmPurchase(conCode); model.addAttribute("message", message); } catch (Exception e) { model.addAttribute("message", e.getMessage()); return "confirmPurchase"; } ShoppingCart cartInfo = Utils.getCartInSession(request); // store lastest order for finalization Utils.storeLastOrderedCartInSession(request, cartInfo); // Delete cart from session Utils.removeCartInSession(request); return "redirect:/shoppingCartFinalize"; } /** * Cancel/change status the order * * @param request * @param model * @return */ @RequestMapping(value = { "/cancelOrder" }) public String cancelOrder(HttpServletRequest request, Model model) { orderDAO.cancelOrder(); ShoppingCart cartInfo = Utils.getCartInSession(request); // store lastest order for finalization Utils.storeLastOrderedCartInSession(request, cartInfo); // Delete cart from session Utils.removeCartInSession(request); return "redirect:/productList"; } /** * Send the order detail via email * * @param order */ public void sendSimpleEmail(OrderInfo order) { // Create a Simple MailMessage. SimpleMailMessage message = new SimpleMailMessage(); Order o = orderDAO.findOrder(order.getId()); message.setTo(order.getEmail()); message.setSubject("Japanese Restaurant"); message.setText("Hello, this is the receive for your order:\n " + order.toString2() + "\n\n This is the confirm code: " + o.getConCode()); // Send Message! this.emailSender.send(message); } /** * Finalize the cart * * @param request * @param model * @return */ @RequestMapping(value = { "/shoppingCartFinalize" }, method = RequestMethod.GET) public String shoppingCartFinalize(HttpServletRequest request, Model model) { ShoppingCart lastOrderedCart = Utils.getLastOrderedCartInSession(request); if (lastOrderedCart == null) { return "redirect:/shoppingCart"; } model.addAttribute("lastOrderedCart", lastOrderedCart); return "shoppingCartFinalize"; } }
true
84532083c32b048b57ee2f10c1ae4e79f93e8251
Java
Tompparella/CiviVPlanner
/app/src/main/java/com/example/javaharkka/MainActivity.java
UTF-8
4,547
2.546875
3
[]
no_license
/* CiviVPlanner; Android Studio; Tommi Kunnari; MainActivity.class; This is the main menu after logging in. It has buttons that begin different processes within the app. It also reads the user's id and user- name from the database. */ package com.example.javaharkka; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; 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; public class MainActivity extends AppCompatActivity { private FirebaseAuth fbAuth; private TextView txtCurrentUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setButtons(); try { setUIText(); } catch (Exception e){ Log.wtf("Database error: ", e); } } // Sets the UI's buttons to their listeners and adds functions when a button is pressed. // Similar methods are used in almost every activity-class of the program. private void setButtons(){ Button browseBtn = findViewById(R.id.browseBtn); browseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openBrowse(); } }); Button btnLogout = findViewById(R.id.btnLogout); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logout(); } }); Button orientation_button = findViewById(R.id.Newplan); orientation_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openNewPlan(); } }); Button aboutBtn = findViewById(R.id.aboutBtn); aboutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openAbout(); } }); } private void openAbout(){ Intent intent = new Intent(MainActivity.this, About.class); startActivity(intent); } private void openNewPlan(){ Intent intent = new Intent(MainActivity.this,OrientationActivity.class); startActivity(intent); } private void openBrowse(){ Intent intent = new Intent(MainActivity.this,BrowsePlans.class); startActivity(intent); } private void logout(){ try { fbAuth.signOut(); finish(); Toast.makeText(MainActivity.this, "Logged out", Toast.LENGTH_SHORT).show(); startActivity(new Intent(MainActivity.this, Login.class)); } catch (Exception e){ Log.wtf("Database error:", e); } } // This method loads the user's data from database and sets the activity's views accordingly. private void setUIText(){ fbAuth = FirebaseAuth.getInstance(); FirebaseDatabase fbData = FirebaseDatabase.getInstance(); DatabaseReference dbRef = fbData.getReference("Users").child(fbAuth.getUid()); // Gets a reference of the user's info from the "Users" branch of the database. txtCurrentUser = findViewById(R.id.txtCurrentUser); dbRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // Reads data from the reference. Users currentuser; String currentUserName; currentuser = dataSnapshot.getValue(Users.class); currentUserName = currentuser.getUserName(); txtCurrentUser.setText(" Logged in as " + currentUserName); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { System.out.println("Disconnected user"); } }); TextView txtUid = findViewById(R.id.txtUid); txtUid.setText(" UserID: " + fbAuth.getUid()); } }
true
34bb5686dc06df6c80288331c0f026a869e68d5f
Java
tijunoi/ReadIsWhatILove
/app/src/main/java/com/example/bertiwi/readiswhatilove/activities/SplashScreenActivity.java
UTF-8
2,465
2.125
2
[]
no_license
package com.example.bertiwi.readiswhatilove.activities; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.example.bertiwi.readiswhatilove.R; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class SplashScreenActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); int SPLASH_TIME_OUT = 3000; new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(SplashScreenActivity.this, MainActivity.class); startActivity(i); finish(); } }, SPLASH_TIME_OUT); /* OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("grant_type", "http://oauth.net/grant_type/device/1.0") .add("client_id", "426405697865-luhj6dst71rbmml1ne5gldnebk4u1ksc.apps.googleusercontent.com") .add("client_secret", "oYFOpCbrDESnNBte1KUldA_U") .add("redirect_uri","") .add("code", "4/4-GMMhmHCXhWEzkobqIHGG_EnNYYsAkukHspeYUk9E8") .build(); final Request request = new Request.Builder() .url("https://www.googleapis.com/oauth2/v4/token") .post(requestBody) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("CACACACACA", e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONObject jsonObject = new JSONObject(response.body().string()); final String message = jsonObject.toString(5); Log.i("okokokokok", message); } catch (JSONException e) { e.printStackTrace(); } } });*/ } }
true
0d7a7c0ce929d2dae259f34a7c5ac95917a8c4ab
Java
thinkshihang/algorithms
/src/test/java/string/CC150_1_3_PermutationCheckTest.java
UTF-8
838
2.65625
3
[]
no_license
package string; import org.junit.Test; import static string.CC150_1_3_PermutationCheck.isPermutation_1; import static string.CC150_1_3_PermutationCheck.isPermutation_2; import static org.junit.Assert.*; public class CC150_1_3_PermutationCheckTest { @Test public void testIsPermutation_1_withCorrectData() throws Exception { assertTrue(isPermutation_1("abcdd", "dadbc")); } @Test public void testIsPermutation_1_withInCorrectData() throws Exception { assertFalse(isPermutation_1("abcd", "aabc")); } @Test public void testIsPermutation_2_withCorrectData() throws Exception { assertTrue(isPermutation_2("aabbcd", "cbdaba")); } @Test public void testIsPermutation_2_withInCorrectData() throws Exception { assertTrue(isPermutation_2("abcdd", "ddacb")); } }
true
5956ab8301850da01b39c0b795e7088e8b3400aa
Java
yybear/JetGameSever
/src/main/java/com/handwin/entity/User.java
UTF-8
2,585
2
2
[]
no_license
package com.handwin.entity; import org.codehaus.jackson.annotate.JsonIgnoreProperties; /** * User: qgan([email protected]) * Date: 14-5-16 下午4:11 */ @JsonIgnoreProperties(ignoreUnknown = true) public class User { private String id; private String nickname; private String mobile; private Integer sex; private String avatar_url; private String countrycode; private String[] tcpServer; private int gameStatus; private Integer levet; private Integer stars; private Integer experience; private Integer threeStarNum; public Integer getLevet() { return levet; } public void setLevet(Integer levet) { this.levet = levet; } public Integer getStars() { return stars; } public void setStars(Integer stars) { this.stars = stars; } public Integer getExperience() { return experience; } public void setExperience(Integer experience) { this.experience = experience; } public Integer getThreeStarNum() { return threeStarNum; } public void setThreeStarNum(Integer threeStarNum) { this.threeStarNum = threeStarNum; } public String getAvatar_url() { return avatar_url; } public void setAvatar_url(String avatar_url) { this.avatar_url = avatar_url; } private String sessionId; public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String[] getTcpServer() { return tcpServer; } public void setTcpServer(String[] tcpServer) { this.tcpServer = tcpServer; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getCountrycode() { return countrycode; } public void setCountrycode(String countrycode) { this.countrycode = countrycode; } public int getGameStatus() { return gameStatus; } public void setGameStatus(int gameStatus) { this.gameStatus = gameStatus; } }
true
5857e84ea722a1dccf8953d8741dc7cc90d868cd
Java
Pwang-je/find_word
/src/main/java/com/test/find_word/repository/WordDao.java
UTF-8
232
1.78125
2
[]
no_license
package com.test.find_word.repository; import com.test.find_word.model.WordModel; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface WordDao { List<WordModel> getWord(); }
true
88db45d6f8c8928253ac1589c5b247acf31916eb
Java
IdentityChain/APP
/project-isc-server/src/main/java/com/project/isc/iscdbserver/viewentity/achieve/AchievementVO.java
UTF-8
5,956
1.96875
2
[]
no_license
package com.project.isc.iscdbserver.viewentity.achieve; import java.util.Date; public class AchievementVO { private static final long serialVersionUId = 1L; private String aaid; //成就ID private double aaaddiscValue; //给ISC数目 private int aacalculateValue; //给成就点数目 private String aacontent; //成就完成规则 private Date caareateTime; //创建时间 private String aacreateUserId; //创建用户ID private String aacreateUserName; //创建用户名称 private String aagrayImgPath; //成就图片-未完成 private String aaimg_path; //成就图片-完成 private int aasteps; //完成条件-步骤,如100次,10000次 private String aatitle; //成就标题 private boolean aavailable; //是否可用 private String aatype; //成就类型-每日成就,成就 private Date aaupdateTime; //更新时间 private String auid; //进度ID private String auachId; //成就任务ID private String auuserId; //用户ID private int auuserSteps; //用户进度 private int aucompleteRate; //完成率 private Date auaucreateTime; //创建时间 private Date aufinishTime; //完成时间 private boolean auis_create; //是否领取 private boolean auavailable; //是否可用 //toolType: 'button', // toolEvent: 'checkin', // toolText: '签到' public String toolType; //button text public String toolEvent; //checkin public String toolText; //'签到' +10 public String getToolType() { return toolType; } public void setToolType(String toolType) { this.toolType = toolType; } public String getToolEvent() { return toolEvent; } public void setToolEvent(String toolEvent) { this.toolEvent = toolEvent; } public String getToolText() { return toolText; } public void setToolText(String toolText) { this.toolText = toolText; } public static long getSerialVersionUId() { return serialVersionUId; } public String getAaid() { return aaid; } public void setAaid(String aaid) { this.aaid = aaid; } public double getAaaddiscValue() { return aaaddiscValue; } public void setAaaddiscValue(double aaaddiscValue) { this.aaaddiscValue = aaaddiscValue; } public int getAacalculateValue() { return aacalculateValue; } public void setAacalculateValue(int aacalculateValue) { this.aacalculateValue = aacalculateValue; } public String getAacontent() { return aacontent; } public void setAacontent(String aacontent) { this.aacontent = aacontent; } public Date getCaareateTime() { return caareateTime; } public void setCaareateTime(Date caareateTime) { this.caareateTime = caareateTime; } public String getAacreateUserId() { return aacreateUserId; } public void setAacreateUserId(String aacreateUserId) { this.aacreateUserId = aacreateUserId; } public String getAacreateUserName() { return aacreateUserName; } public void setAacreateUserName(String aacreateUserName) { this.aacreateUserName = aacreateUserName; } public String getAagrayImgPath() { return aagrayImgPath; } public void setAagrayImgPath(String aagrayImgPath) { this.aagrayImgPath = aagrayImgPath; } public String getAaimg_path() { return aaimg_path; } public void setAaimg_path(String aaimg_path) { this.aaimg_path = aaimg_path; } public int getAasteps() { return aasteps; } public void setAasteps(int aasteps) { this.aasteps = aasteps; } public String getAatitle() { return aatitle; } public void setAatitle(String aatitle) { this.aatitle = aatitle; } public boolean isAavailable() { return aavailable; } public void setAavailable(boolean aavailable) { this.aavailable = aavailable; } public String getAatype() { return aatype; } public void setAatype(String aatype) { this.aatype = aatype; } public Date getAaupdateTime() { return aaupdateTime; } public void setAaupdateTime(Date aaupdateTime) { this.aaupdateTime = aaupdateTime; } public String getAuid() { return auid; } public void setAuid(String auid) { this.auid = auid; } public String getAuachId() { return auachId; } public void setAuachId(String auachId) { this.auachId = auachId; } public String getAuuserId() { return auuserId; } public void setAuuserId(String auuserId) { this.auuserId = auuserId; } public int getAuuserSteps() { return auuserSteps; } public void setAuuserSteps(int auuserSteps) { this.auuserSteps = auuserSteps; } public int getAucompleteRate() { return aucompleteRate; } public void setAucompleteRate(int aucompleteRate) { this.aucompleteRate = aucompleteRate; } public Date getAuaucreateTime() { return auaucreateTime; } public void setAuaucreateTime(Date auaucreateTime) { this.auaucreateTime = auaucreateTime; } public Date getAufinishTime() { return aufinishTime; } public void setAufinishTime(Date aufinishTime) { this.aufinishTime = aufinishTime; } public boolean isAuis_create() { return auis_create; } public void setAuis_create(boolean auis_create) { this.auis_create = auis_create; } public boolean isAuavailable() { return auavailable; } public void setAuavailable(boolean auavailable) { this.auavailable = auavailable; } }
true
3e4ccc10f3ab274d951cee73498397910eb69ff0
Java
Ztianyu/HealthyPlus1
/app/src/main/java/com/zty/healthy/healthyplus/model/ChartDataModel.java
UTF-8
2,378
2.5
2
[]
no_license
package com.zty.healthy.healthyplus.model; import java.util.List; /** * 健康数据趋势数据 * Created by zty on 2016/10/21. */ public class ChartDataModel { private XAxis xAxis; private List<Series> series; public XAxis getxAxis() { return xAxis; } public void setxAxis(XAxis xAxis) { this.xAxis = xAxis; } public List<Series> getSeries() { return series; } public void setSeries(List<Series> series) { this.series = series; } public class XAxis { private List<String> categories; public List<String> getCategories() { return categories; } public void setCategories(List<String> categories) { this.categories = categories; } } public class Series { private String name; private NormalRange normalRange; private List<Data> data; public String getName() { return name; } public void setName(String name) { this.name = name; } public NormalRange getNormalRange() { return normalRange; } public void setNormalRange(NormalRange normalRange) { this.normalRange = normalRange; } public List<Data> getData() { return data; } public void setData(List<Data> data) { this.data = data; } } public class NormalRange { private String normalBeg; private String normalEnd; public String getNormalBeg() { return normalBeg; } public void setNormalBeg(String normalBeg) { this.normalBeg = normalBeg; } public String getNormalEnd() { return normalEnd; } public void setNormalEnd(String normalEnd) { this.normalEnd = normalEnd; } } public class Data { private String value; private int remark;// remark:(0:正常,1:偏高,2:偏低) public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getRemark() { return remark; } public void setRemark(int remark) { this.remark = remark; } } }
true
fbfff739f63d63ccfc212b9628d1d9968741ff82
Java
Rachita333/SeleniumLearning
/MSelPractice/src/test/java/javaBasics/IfElseConcept.java
UTF-8
401
3.703125
4
[]
no_license
package javaBasics; public class IfElseConcept { public static void main(String[] args) { // TODO Auto-generated method stub int a=50; int b=90; int c=25; if(a>b & a>c ) { System.out.println("A is gretaer"); } else if (b > c & b>a) { System.out.println("B is greater"); } else { System.out.println("C is greater"); } } }
true
cf27ace4cdd28cf0ee98ba09b74eabc7fbc7f0d4
Java
p-yang/Saints-Robotics-Programming
/FRC/2011/Other Teams/Team 341/DigitalFilter.java
UTF-8
2,991
3.25
3
[]
no_license
package edu.missdaisy; import java.util.Vector; /** * * @author jrussell */ public class DigitalFilter { private class CircularBuffer { private double[] data; private int front; public CircularBuffer(int size) { data = new double[size]; front = 0; } public void increment() { front++; if( front >= data.length ) { front = 0; } } public void reset() { for( int d = 0; d < data.length; d++ ) { data[d] = 0; } } public int size() { return data.length; } public double elementAt(int position) { return data[ (position+front) % data.length ]; } public void setElementAt(double value, int position) { data[ (position+front) % data.length ] = value; } } private CircularBuffer inputs; private CircularBuffer outputs; private Vector inputGains; private Vector outputGains; public DigitalFilter(Vector inputGains, Vector outputGains) { this.inputGains = inputGains; this.outputGains = outputGains; inputs = new CircularBuffer( inputGains.size() ); outputs = new CircularBuffer( outputGains.size() ); } public static DigitalFilter SinglePoleIIRFilter(double gain) { Vector inputGain = new Vector(); Vector outputGain = new Vector(); inputGain.addElement(new Double(gain)); outputGain.addElement(new Double(1.0f - gain)); return new DigitalFilter(inputGain, outputGain); } public static DigitalFilter MovingAverageFilter(int taps) { if( taps < 1 ) { taps = 1; } Double gain = new Double(1.0/taps); Vector gains = new Vector(); for( int i = 0; i < taps; i++ ) { gains.addElement(gain); } return new DigitalFilter(gains, new Vector()); } public void reset() { inputs.reset(); outputs.reset(); } public double calculate(double value) { double retVal = 0.0; // Rotate the inputs if( inputs.size() > 0 ) { inputs.increment(); inputs.setElementAt(value, 0); } // Calculate the new output for( int i = 0; i < inputs.size(); i++ ) { retVal += inputs.elementAt(i) * ((Double)inputGains.elementAt(i)).doubleValue(); } for( int i = 0; i < outputs.size(); i++ ) { retVal += outputs.elementAt(i) * ((Double)outputGains.elementAt(i)).doubleValue(); } // Rotate the outputs if( outputs.size() > 0 ) { outputs.increment(); outputs.setElementAt(retVal, 0); } return retVal; } }
true
3f40f8a6bfb446b9a35932d9475af6ceed7e91fb
Java
vivianluomin/CollectionElfin
/app/src/main/java/com/example/asus1/collectionelfin/models/UniApiReuslt.java
UTF-8
576
2.03125
2
[]
no_license
package com.example.asus1.collectionelfin.models; import com.google.gson.annotations.SerializedName; /** * Created by asus1 on 2017/9/27. */ public class UniApiReuslt<T>{ //数据 @SerializedName("status") protected int mStatus; @SerializedName("data") protected T mData; public int getmStatus() { return mStatus; } public void setmStatus(int mStatus) { this.mStatus = mStatus; } public T getmData() { return mData; } public void setmData(T mData) { this.mData = mData; } }
true
5da55526dd8be792f11cd3334561e5537bb89310
Java
hasone/pdata
/common/src/main/java/com/cmcc/vrp/province/model/ProductChangeDetail.java
UTF-8
3,212
1.867188
2
[]
no_license
package com.cmcc.vrp.province.model; /** * <p>Title: </p> * <p>Description: </p> * @author lgk8023 * @date 2017年1月22日 下午3:06:28 */ public class ProductChangeDetail { private Long id; private Long requestId; private Long productId; private Integer operate; private Integer discount; private Integer deleteFlag; private Long oldProductTemplateId; //旧产品模板id private Long newProductTemplateId; //新产品模板id //extended private String prdName; private String prdCode; private int price; private String isp; //产品运营商 private Long productSize; //产品大小 private String ownershipRegion; // private String roamingRegion; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getRequestId() { return requestId; } public void setRequestId(Long requestId) { this.requestId = requestId; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Integer getOperate() { return operate; } public void setOperate(Integer operate) { this.operate = operate; } public Integer getDiscount() { return discount; } public void setDiscount(Integer discount) { this.discount = discount; } public Integer getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(Integer deleteFlag) { this.deleteFlag = deleteFlag; } public Long getOldProductTemplateId() { return oldProductTemplateId; } public void setOldProductTemplateId(Long oldProductTemplateId) { this.oldProductTemplateId = oldProductTemplateId; } public Long getNewProductTemplateId() { return newProductTemplateId; } public void setNewProductTemplateId(Long newProductTemplateId) { this.newProductTemplateId = newProductTemplateId; } public String getPrdName() { return prdName; } public void setPrdName(String prdName) { this.prdName = prdName; } public String getPrdCode() { return prdCode; } public void setPrdCode(String prdCode) { this.prdCode = prdCode; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getIsp() { return isp; } public void setIsp(String isp) { this.isp = isp; } public Long getProductSize() { return productSize; } public void setProductSize(Long productSize) { this.productSize = productSize; } public String getOwnershipRegion() { return ownershipRegion; } public void setOwnershipRegion(String ownershipRegion) { this.ownershipRegion = ownershipRegion; } public String getRoamingRegion() { return roamingRegion; } public void setRoamingRegion(String roamingRegion) { this.roamingRegion = roamingRegion; } }
true
f0ca378ae22fa6c21003ffdab90811734271def3
Java
dfraga/mobile
/Weather/src/main/java/com/weather/acquisition/MapOverlayImageInfo.java
UTF-8
1,240
1.914063
2
[]
no_license
package com.weather.acquisition; import java.io.Serializable; import android.graphics.Bitmap; import com.weather.populate.Class3X01Y192; import com.weather.populate.Populator; public class MapOverlayImageInfo implements Serializable { private static final long serialVersionUID = 3478447513121319792L; private Bitmap imBitmap; private long downloadTarFileSize; private Populator<Class3X01Y192> imageGeneralData; public MapOverlayImageInfo(final Bitmap imBitmap, final long downloadTarFileSize, final Populator<Class3X01Y192> imageGeneralData) { this.imBitmap = imBitmap; this.downloadTarFileSize = downloadTarFileSize; this.imageGeneralData = imageGeneralData; } public Bitmap getImBitmap() { return imBitmap; } public void setImBitmap(final Bitmap imBitmap) { this.imBitmap = imBitmap; } public long getDownloadTarFileSize() { return downloadTarFileSize; } public void setDownloadTarFileSize(final long downloadTarFileSize) { this.downloadTarFileSize = downloadTarFileSize; } public Populator<Class3X01Y192> getImageGeneralData() { return imageGeneralData; } public void setImageGeneralData(final Populator<Class3X01Y192> imageGeneralData) { this.imageGeneralData = imageGeneralData; } }
true
1dea1e1cdc57329c044f7fc61a1c1c168780fc66
Java
aymanalgebaly/BloodBank
/app/src/main/java/com/example/android/fa3el5eer/donationRequestList/DonationRequestList_Api.java
UTF-8
361
1.890625
2
[]
no_license
package com.example.android.fa3el5eer.donationRequestList; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Url; public interface DonationRequestList_Api { @GET() Call<DonationListResponse> getDonationListResponse(@Url String url,@Query("api_token")String api_token); }
true
e9527ea0aed042f487be7e65dd30dabd175df239
Java
victorylord/WORK
/panda-rcs-trade/panda-rcs-mgr-trade/src/main/java/com/panda/sport/rcs/trade/wrapper/impl/StandardSportMarketServiceImpl.java
UTF-8
10,220
1.921875
2
[]
no_license
package com.panda.sport.rcs.trade.wrapper.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.panda.merge.dto.StandardMarketOddsDTO; import com.panda.sport.rcs.mapper.StandardSportMarketMapper; import com.panda.sport.rcs.pojo.StandardSportMarket; import com.panda.sport.rcs.pojo.StandardSportMarketOdds; import com.panda.sport.rcs.pojo.cache.RcsCacheContant; import com.panda.sport.rcs.pojo.dto.StandardMarketPlaceDto; import com.panda.sport.rcs.trade.wrapper.StandardSportMarketService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * <p> * 盘口服务类 * </p> * * @author CodeGenerator * @since 2019-09-03 */ @Slf4j @Service public class StandardSportMarketServiceImpl extends ServiceImpl<StandardSportMarketMapper, StandardSportMarket> implements StandardSportMarketService { @Autowired private StandardSportMarketMapper standardSportMarketMapper; @Override public Map<Long, List<StandardSportMarket>> getEffectiveMarket(Long matchId, List<Long> playIds) { LambdaQueryWrapper<StandardSportMarket> wrapper = Wrappers.lambdaQuery(); wrapper.eq(StandardSportMarket::getStandardMatchInfoId, matchId) .in(StandardSportMarket::getMarketCategoryId, playIds) .in(StandardSportMarket::getThirdMarketSourceStatus, Lists.newArrayList(0, 1)); List<StandardSportMarket> list = this.list(wrapper); if (CollectionUtils.isEmpty(list)) { return Maps.newHashMap(); } Map<Long, List<StandardSportMarket>> map = list.stream().collect(Collectors.groupingBy(StandardSportMarket::getChildMarketCategoryId)); map.values().forEach(values -> { for (int i = 0; i < values.size(); i++) { values.get(i).setPlaceNum(i + 1); } }); return map; } @Override public Map<Integer, Long> getOddsFieldsTemplateId(Long playId) { return RcsCacheContant.ODDS_FIELDS_TEMPLATE_ID_CACHE.get(playId, id -> { List<StandardMarketOddsDTO> list = this.baseMapper.selectOddsFieldsTempletId(playId); if (CollectionUtils.isEmpty(list)) { return Maps.newHashMap(); } return list.stream().collect(Collectors.toMap(StandardMarketOddsDTO::getOrderOdds, StandardMarketOddsDTO::getOddsFieldsTemplateId)); }); } @Override public StandardSportMarket getStandardSportMarketById(long id) { return standardSportMarketMapper.selectById(id); } @Override public List<StandardSportMarket> getStandardSportMarketByMatchId(Long matchId) { if (matchId == null) { return null; } QueryWrapper<StandardSportMarket> standardSportMarketQueryWrapper = new QueryWrapper<>(); standardSportMarketQueryWrapper.lambda().eq(StandardSportMarket::getStandardMatchInfoId, matchId); return standardSportMarketMapper.selectList(standardSportMarketQueryWrapper); } @Override public Long selectStandardSportMarketIdByMarketValue(Long matchId, Long playId, String marketValue) { return standardSportMarketMapper.selectStandardSportMarketIdByMarketValue(matchId, playId, marketValue); } @Override public List<StandardSportMarket> selectStandardSportMarketByMap(Map<String, Object> columnMap) { return standardSportMarketMapper.selectByMap(columnMap); } @Override public List<Long> selectPlayIdByMatchId(Long matchId) { return standardSportMarketMapper.selectPlayIdByMatchId(matchId); } @Override public List<StandardSportMarketOdds> selectStandardSportMarketByGiveWay(Long matchId, Long playId) { return standardSportMarketMapper.selectStandardSportMarketByGiveWay(matchId, playId); } @Override public StandardSportMarket selectById(Long id) { return standardSportMarketMapper.selectById(id); } @Override public List<StandardSportMarket> list(Long matchId) { return this.list(new LambdaQueryWrapper<StandardSportMarket>() .eq(StandardSportMarket::getStandardMatchInfoId, matchId)); } @Override public List<StandardSportMarket> list(Long matchId, Long categoryId) { return this.list(new LambdaQueryWrapper<StandardSportMarket>() .eq(StandardSportMarket::getStandardMatchInfoId, matchId) .eq(StandardSportMarket::getMarketCategoryId, categoryId)); } @Override public List<StandardSportMarket> list(Long matchId, Collection<Long> categoryIds) { return this.list(new LambdaQueryWrapper<StandardSportMarket>() .eq(StandardSportMarket::getStandardMatchInfoId, matchId) .in(StandardSportMarket::getMarketCategoryId, categoryIds)); } @Override public StandardSportMarket get(Long matchId, Long marketId) { return this.getOne(new LambdaQueryWrapper<StandardSportMarket>() .eq(StandardSportMarket::getId, marketId) .eq(StandardSportMarket::getStandardMatchInfoId, matchId)); } @Override public List<StandardSportMarket> queryMarketInfo(Long matchId, Long playId) { return this.baseMapper.queryMarketInfo(matchId, Lists.newArrayList(playId)); } @Override public List<StandardSportMarket> queryMarketInfo(Long matchId, Collection<Long> playIds) { return this.baseMapper.queryMarketInfo(matchId, playIds); } @Override public StandardSportMarket queryMainMarketInfo(Long matchId, Long playId) { return this.baseMapper.queryMainMarketInfo(matchId, playId); } @Override public Map<Long, Map<Long, StandardSportMarket>> listMainMarketInfo(Long matchId, Collection<Long> playIds) { List<StandardSportMarket> list = this.baseMapper.listMainMarketInfo(matchId, playIds); if (CollectionUtils.isEmpty(list)) { return Maps.newHashMap(); } Map<Long, Map<Long, StandardSportMarket>> resultMap = Maps.newHashMap(); Map<Long, List<StandardSportMarket>> groupMap = list.stream().collect(Collectors.groupingBy(StandardSportMarket::getMarketCategoryId)); groupMap.forEach((playId, subPlayList) -> { Map<Long, StandardSportMarket> map = subPlayList.stream().collect(Collectors.toMap(StandardSportMarket::getChildMarketCategoryId, Function.identity())); resultMap.put(playId, map); }); return resultMap; } @Override public StandardSportMarket selectMainMarketInfo(Long matchId, Long categoryId,String subPlayId) { return this.baseMapper.selectMainMarketInfo(matchId, categoryId,subPlayId); } @Override public StandardMarketPlaceDto getMainMarketPlaceInfo(Long matchId, Long playId) { List<StandardMarketPlaceDto> list = this.baseMapper.selectMarketPlaceInfo(matchId, Lists.newArrayList(playId), 1); if (CollectionUtils.isEmpty(list)) { return null; } return list.get(0); } @Override public List<StandardSportMarket> list(Long matchId, Long playId, Integer marketType) { LambdaQueryWrapper<StandardSportMarket> wrapper = Wrappers.lambdaQuery(); wrapper.eq(StandardSportMarket::getStandardMatchInfoId, matchId) .eq(StandardSportMarket::getMarketCategoryId, playId) .eq(StandardSportMarket::getMarketType, marketType); return this.list(wrapper); } @Override public boolean updatePaStatus(Long marketId, Integer paStatus) { LambdaUpdateWrapper<StandardSportMarket> wrapper = Wrappers.lambdaUpdate(); wrapper.eq(StandardSportMarket::getId, marketId) .set(StandardSportMarket::getPaStatus, paStatus); return this.update(wrapper); } @Override public List<Long> getMarketIdList(Long matchId, Long playId) { LambdaQueryWrapper<StandardSportMarket> wrapper = Wrappers.lambdaQuery(); wrapper.eq(StandardSportMarket::getStandardMatchInfoId, matchId) .eq(StandardSportMarket::getMarketCategoryId, playId) .select(StandardSportMarket::getId); List<StandardSportMarket> list = this.list(wrapper); if (CollectionUtils.isEmpty(list)) { return Lists.newArrayList(); } return list.stream().map(StandardSportMarket::getId).collect(Collectors.toList()); } @Override public Map<Long, List<Long>> getSubPlayId(Long matchId, Collection<Long> playIds) { LambdaQueryWrapper<StandardSportMarket> wrapper = Wrappers.lambdaQuery(); wrapper.eq(StandardSportMarket::getStandardMatchInfoId, matchId) .in(StandardSportMarket::getMarketCategoryId, playIds) .select(StandardSportMarket::getMarketCategoryId, StandardSportMarket::getChildMarketCategoryId); List<StandardSportMarket> list = this.list(wrapper); if (CollectionUtils.isEmpty(list)) { return Maps.newHashMap(); } Map<Long, List<Long>> resultMap = Maps.newHashMap(); list.forEach(market -> { Long playId = market.getMarketCategoryId(); Long subPlayId = market.getChildMarketCategoryId(); if (resultMap.containsKey(playId)) { resultMap.get(playId).add(subPlayId); } else { List<Long> subPlayIdList = Lists.newArrayList(); subPlayIdList.add(subPlayId); resultMap.put(playId, subPlayIdList); } }); return resultMap; } }
true
e0eb871941c743d62953873126ea06407e246c6b
Java
WasteOfOxygen/minecraft123
/src/minmaxprumer2/MinMaxPrumer.java
UTF-8
899
3.34375
3
[]
no_license
package minmaxprumer2; import java.util.Scanner; public class MinMaxPrumer2 { public static void main(String[] args) { // TODO code application logic here Scanner sc = new Scanner(System.in, "CP1250"); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int soucet = 0, pocet = 0; while (true) { pocet++; System.out.print("vlož"+pocet+ ". číslo: "); int vstup = sc.nextInt(); if (vstup == 0) break; soucet = soucet + vstup; if (vstup < min) min = vstup; if (vstup > max) max = vstup; System.out.println("Maximum: " + max); System.out.println("Minimum: " + min); System.out.println("průměr: "+((float) soucet/pocet)); } } }
true
483d8e0300c9e89ce790287b8bd0d846f88afef4
Java
ketchuprima/BackEndProyecto3
/src/main/java/com/back/app/modelos/User.java
UTF-8
1,441
2.140625
2
[]
no_license
package com.back.app.modelos; import java.io.Serializable; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonBackReference; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @NoArgsConstructor @Table(name = "user") public class User implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Size(max = 255) @Email @NotNull private String email; @Size(max = 255) @NotNull @JsonBackReference(value = "userPass") private String pass; @Size(max = 50) @NotNull private String nom; @Size(max = 100) @NotNull private String cognoms; @Size(min = 9, max = 9) @NotNull private String telefon; @ManyToMany @JoinTable(name = "rol_user", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "rol_id")) private Set<Rol> roles; public User(String email, String pass) { this.email=email; this.pass=pass; } private static final long serialVersionUID = -2422977159875418682L; }
true
f86768d098ee7e2aedbc876bdf7c4cd0ab5694f7
Java
LRdeath/Test_demo
/app/src/main/java/com/example/administrator/text1/chess/ChessView.java
UTF-8
7,375
2.3125
2
[]
no_license
package com.example.administrator.text1.chess; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.example.administrator.text1.R; import java.util.ArrayList; import java.util.List; /** * Created by WeiZ on 2016/11/21. */ public class ChessView extends View { private int MaxLine = 10;//棋盘行数 private int mPanelWidth; private float mLineHeight; private Paint mPaint = new Paint(); private Bitmap mWithtP; private Bitmap mBlackP; private float ratioPieceOfLineHeight = 3 * 1.0f / 4; private List<Point> mWhiteArray = new ArrayList<Point>(), mBlackArray = new ArrayList<Point>(); private boolean mIsWhite = false; private boolean IsGameOver = false; private int line_num = 10; private String Tag = "CHESSVIEW"; public ChessView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ChessView); line_num = a.getInteger(R.styleable.ChessView_line_num,15); Log.e(Tag,""+line_num); MaxLine = line_num; a.recycle(); setBackgroundColor(Color.parseColor("#BBAD6E")); init(); } private void init() { mPaint.setColor(0x88000000); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setStyle(Paint.Style.STROKE); mWithtP = BitmapFactory.decodeResource(getResources(), R.mipmap.stone_w2); mBlackP = BitmapFactory.decodeResource(getResources(), R.mipmap.stone_b1); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heigthSize = MeasureSpec.getSize(heightMeasureSpec); int heigthMode = MeasureSpec.getMode(heightMeasureSpec); int width = Math.min(widthSize, heigthSize); //父容器是ScorlView时,以防height或width是0 if (widthMode == MeasureSpec.UNSPECIFIED) { width = heigthSize; } else if (heigthMode == MeasureSpec.UNSPECIFIED) width = widthSize; setMeasuredDimension(width, width);//设置View的长宽 } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mPanelWidth = w; mLineHeight = (mPanelWidth * 1.0f) / MaxLine; int pieceWide = (int) (mLineHeight * ratioPieceOfLineHeight); mWithtP = Bitmap.createScaledBitmap(mWithtP, pieceWide, pieceWide, false);//笔记:如果是放大图片,filter决定是否平滑,如果是缩小图片,filter无影响 mBlackP = Bitmap.createScaledBitmap(mBlackP, pieceWide, pieceWide, false); } @Override public boolean onTouchEvent(MotionEvent event) { if(IsGameOver) return false; int action = event.getAction(); if(action == MotionEvent.ACTION_UP) { int x = (int) event.getX(); int y = (int) event.getY(); Point p = makeSurePiece(x, y); if(mWhiteArray.contains(p) || mBlackArray.contains(p)) return false; if(mIsWhite) mWhiteArray.add(p); else mBlackArray.add(p); invalidate(); // 请求重绘 checkIsGameOver(p); mIsWhite = !mIsWhite; } return true; } private void checkIsGameOver(Point p) { if(mIsWhite){ if(dfsCheck(mWhiteArray,p)){ IsGameOver =true; showAlertDialog("白棋胜利!"); } } else if (dfsCheck(mBlackArray, p)) { IsGameOver =true; showAlertDialog("黑棋胜利!"); } } private void showAlertDialog(String s) { new AlertDialog.Builder(getContext()) .setMessage(s) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).show(); } private boolean dfsCheck(List<Point> mWhiteArray, Point p) { int a=1,s=1; //横向判断 while(mWhiteArray.contains(new Point(p.x-a,p.y))){ a++; s++; } a=1; while(mWhiteArray.contains(new Point(p.x+a,p.y))){ a++; s++; } if(s==5)return true; //竖向判断 a=1;s=1; while(mWhiteArray.contains(new Point(p.x,p.y-a))){ a++; s++; } a=1; while(mWhiteArray.contains(new Point(p.x,p.y+a))){ a++; s++; } if(s==5)return true; //右斜向判断 a=1;s=1; while(mWhiteArray.contains(new Point(p.x-a,p.y-a))){ a++; s++; } a=1; while(mWhiteArray.contains(new Point(p.x+a,p.y+a))){ a++; s++; } if(s==5)return true; //左斜向判断 a=1;s=1; while(mWhiteArray.contains(new Point(p.x-a,p.y+a))){ a++; s++; } a=1; while(mWhiteArray.contains(new Point(p.x+a,p.y-a))){ a++; s++; } if(s==5)return true; return false; } private Point makeSurePiece(int x, int y) { return new Point((int) (x / mLineHeight), (int) (y / mLineHeight)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //画棋盘 int w = mPanelWidth; float lineHeight = mLineHeight; float startX, x, y; x = (float) (w - 0.5 * lineHeight); startX = (float) (0.5 * lineHeight); for (int i = 0; i < MaxLine; i++) { y = (float) (0.5 * lineHeight + i * lineHeight); canvas.drawLine(startX, y, x, y, mPaint);//画横线 canvas.drawLine(y, startX, y, x, mPaint);//竖线 } //画棋子 //为了效率,mWhitePoint.size()直接提前获取,不用每次获取 for(int i = 0, n = mWhiteArray.size(); i < n; i++ ) { Point whitePoint = mWhiteArray.get(i); canvas.drawBitmap(mWithtP, (whitePoint.x + (1-ratioPieceOfLineHeight)/2)*mLineHeight, (whitePoint.y + (1-ratioPieceOfLineHeight)/2)*mLineHeight, null); } for(int i = 0, n = mBlackArray.size(); i < n; i++ ) { Point blackPoint = mBlackArray.get(i); canvas.drawBitmap(mBlackP, (blackPoint.x + (1-ratioPieceOfLineHeight)/2)*mLineHeight, (blackPoint.y + (1-ratioPieceOfLineHeight)/2)*mLineHeight, null); } } }
true
07d78a0d085c5eb127fdaa53f15ba7b721d5af0f
Java
yuxiaohui78/java-matrix-market
/src/main/java/ge/vakho/matrix_market/part/IPart.java
UTF-8
265
2.1875
2
[]
no_license
package ge.vakho.matrix_market.part; import java.io.OutputStream; import java.io.PrintWriter; public interface IPart { String asText(); default void writeTo(OutputStream os) { try (PrintWriter pw = new PrintWriter(os)) { pw.println(asText()); } } }
true
f15d53efce676d6e8be1bd959206195f42abe031
Java
Rebel-Illich/ClassroomApp
/app/src/main/java/com/hunter/myclassroommap/model/Student.java
UTF-8
2,479
2.5625
3
[]
no_license
package com.hunter.myclassroommap.model; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.PrimaryKey; @Entity(tableName = "student_table") public class Student { @PrimaryKey(autoGenerate = true) long studentId; String firstName; String lastName; String middleName; String studentGender; Integer studentAge; @ColumnInfo(name = "classroomId") Long classroomId; public Student(long studentId, String firstName, String lastName, String middleName, String studentGender, Integer studentAge, Long classroomId) { this.studentId = studentId; this.firstName = firstName; this.lastName = lastName; this.middleName = middleName; this.studentGender = studentGender; this.studentAge = studentAge; this.classroomId = classroomId; } public long getStudentId() { return studentId; } public void setStudentId(long studentId) { this.studentId = studentId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getStudentGender() { return studentGender; } public void setStudentGender(String studentGender) { this.studentGender = studentGender; } public Integer getStudentAge() { return studentAge; } public void setStudentAge(Integer studentAge) { this.studentAge = studentAge; } public Long getClassroomId() { return classroomId; } public void setClassroomId(Long classroomId) { this.classroomId = classroomId; } @Override public String toString() { return "Student{" + "studentId=" + studentId + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", middleName='" + middleName + '\'' + ", studentGender='" + studentGender + '\'' + ", studentAge=" + studentAge + ", classroomId=" + classroomId + '}'; } }
true
37e75cff3536239fd1e96f2fb7811114b478418b
Java
grayShi/sdzb
/backserver/src/main/java/com/zibo/controller/UserController.java
UTF-8
828
2.0625
2
[]
no_license
package com.zibo.controller; import com.zibo.entity.Account; import com.zibo.response.BaseResponse; import com.zibo.response.SuccessResponse; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("api/users") public class UserController extends BaseController { @GetMapping("/me") public BaseResponse me() { return new SuccessResponse<>(getCurrentAccount()); } @PostMapping public BaseResponse create(@RequestBody Account account) { return new SuccessResponse<>(userService.saveOrUpdate(account)); } }
true
e74c0172752dcd591297b0b64168597b8017a4ab
Java
neorayer/SkyJLib
/src/com/skymiracle/tcp/CmdTimeoutChecker.java
UTF-8
1,911
2.984375
3
[]
no_license
package com.skymiracle.tcp; import java.io.IOException; import java.net.Socket; import com.skymiracle.logger.Logger; public class CmdTimeoutChecker extends Thread { private Socket socket; private int cmdTimeoutSeconds; private boolean checkEnabled = false; private boolean checking = false; public CmdTimeoutChecker(Socket socket, int cmdTimeoutSeconds) { this.socket = socket; this.cmdTimeoutSeconds = cmdTimeoutSeconds; setName("CmdTimeoutChecker Thread"); } public void setSeconds(int cmdTimeoutSeconds) { this.cmdTimeoutSeconds = cmdTimeoutSeconds; } public int getSeconds() { return this.cmdTimeoutSeconds; } @Override public void run() { int millSeconds = this.cmdTimeoutSeconds * 1000; while (true) { long curTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis(); while (this.checkEnabled) { this.checking = true; if (curTime - startTime > millSeconds) { try { this.socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Logger.info(new StringBuffer("Connection timeout.")); return; } try { sleep(1); } catch (InterruptedException e) { return; } curTime = System.currentTimeMillis(); } this.checking = false; try { sleep(1); } catch (InterruptedException e) { return; } } } public void startCheck() { this.checkEnabled = true; while (true) if (!this.checking) try { sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } else break; } public void stopCheck() { this.checkEnabled = false; while (true) if (this.checking) try { sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } else break; } }
true
649162d46aca9e0aedfb5ede238cb578c07cdd32
Java
garrett92895/CustomExtensions
/src/com/fox/collections/MapExtension.java
UTF-8
2,280
3.375
3
[]
no_license
package com.fox.collections; import com.fox.general.IterableExtension; import java.util.HashMap; import java.util.Map; import java.util.function.Function; /** * Created by stephen on 4/15/15. */ public class MapExtension { public static <T extends Comparable, U extends Comparable> void printKeyValuePairs( Map<T, U> dict ) { for ( Map.Entry<T, U> keyValPair : dict.entrySet() ) { System.out.printf("%s: %s", keyValPair.getKey(), keyValPair.getValue()); } } /** * Haskell's Map.fromList is to thank for this idea. * [(a,b)] -> Map a b, where the last key->value wins, overwriting any previous * entries * @param tuples or key-value pairs * @param <K> type of the key * @param <V> type of the value * @return non-null {@code Map<K, V>}, where K is the type of {@link Tuple#item1} * and V is the type of {@link Tuple#item2} */ public static <K, V> Map<K, V> fromList( Iterable<Tuple<K, V>> tuples ) { HashMap<K, V> hashMap = new HashMap<>(); tuples.forEach(kvTuple -> hashMap.put(kvTuple.item1, kvTuple.item2)); return hashMap; } public static <K, V, E extends Iterable<V>> Map<K, Iterable<V>> fromConcatableList( Iterable<Tuple<K, E>> tuples ) { HashMap<K, Iterable<V>> hashMap = new HashMap<>(); tuples.forEach(kvPair -> { K key = kvPair.item1; E iterValue = kvPair.item2; Iterable<V> concat = IterableExtension.concat(hashMap.get(key), iterValue); hashMap.put(key, concat); }); return hashMap; } public static <K, V, E extends Iterable<V>, R> Map<K, R> fromConcatableList( Iterable<Tuple<K, E>> tuples, Function<E, R> transform ) { HashMap<K, Iterable<V>> hashMap = new HashMap<>(); tuples.forEach(kvPair -> { K key = kvPair.item1; E iterValue = kvPair.item2; Iterable<V> concat = IterableExtension.concat(hashMap.get(key), iterValue); hashMap.put(key, concat); }); HashMap<K, R> trueRet = new HashMap<>(); hashMap.entrySet().forEach(entry -> trueRet.put(entry.getKey(), transform.apply((E)entry.getValue()))); return trueRet; } }
true
dbe9319dad9b77a59176eff809aca83a835fa436
Java
irasurckova2013/OOP
/src/DuplicateSubjectException.java
UTF-8
218
2.640625
3
[]
no_license
public class DuplicateSubjectException extends RuntimeException { public DuplicateSubjectException() { super(); } public DuplicateSubjectException(String message) { super(message); } }
true
368763c8ef0964246a2b4c5bdbf7eca3ded911d1
Java
Vladislav7776/JD2020-01-20
/src/by/it/_examples_/jd02_06/p11_mediator/Colleague.java
UTF-8
312
2.75
3
[]
no_license
package by.it._examples_.jd02_06.p11_mediator; abstract class Colleague { private Mediator mediator; Colleague(Mediator mediator) { this.mediator = mediator; } void send(String message) { mediator.send(message, this); } public abstract void notify(String message); }
true
6040af4220bd3023bf1cf457da6b4439994385e5
Java
mmbase/didactor
/components/education/src/main/java/nl/didactor/education/builders/MCQuestionBuilder.java
UTF-8
3,054
3.03125
3
[]
no_license
package nl.didactor.education.builders; import org.mmbase.module.core.MMObjectBuilder; import org.mmbase.module.core.MMObjectNode; import java.util.Vector; /** * This builder class can score the answer given to a Multiple-choice * question. */ public class MCQuestionBuilder extends QuestionBuilder { /** * Get the score for the given answer to a question. This method only * delegates: if a score wsa already present in MMBase then that score is * returned. Otherwise either the 'GetScoreSingle' or 'GetScoreMultiple' method is * called. */ public int getScore(MMObjectNode questionNode, MMObjectNode givenAnswer) { int score = givenAnswer.getIntValue("score"); if (score != -1) { return score; } int type = questionNode.getIntValue("type"); switch(type) { case 0: // only 1 answer selected score = getScoreSingle(questionNode, givenAnswer); givenAnswer.setValue("score", score); givenAnswer.commit(); return score; case 1: // multiple answers selected score = getScoreMultiple(questionNode, givenAnswer); givenAnswer.setValue("score", score); givenAnswer.commit(); return score; default: break; } return 1; } /** * Return true if the related 'mcanswers' object has a 'correct' field set to '1'. */ private int getScoreSingle(MMObjectNode questionNode, MMObjectNode givenAnswer) { Vector relatedAnswers = givenAnswer.getRelatedNodes("mcanswers"); if (relatedAnswers.size() != 1) { return 0; } MMObjectNode mcanswer = (MMObjectNode)relatedAnswers.get(0); if (mcanswer.getIntValue("correct") == 1) { return 1; } else { return 0; } } /** * Return true if all related 'mcanswers' objects have a 'correct' field set to '1', * and all these possible mcanswers with correct=1 have been chosen. */ private int getScoreMultiple(MMObjectNode questionNode, MMObjectNode givenAnswer) { Vector givenAnswers = givenAnswer.getRelatedNodes("mcanswers"); Vector goodAnswers = questionNode.getRelatedNodes("mcanswers"); // First check if all the given answers are correct for (int i=0; i<givenAnswers.size(); i++) { if (((MMObjectNode)givenAnswers.get(i)).getIntValue("correct") != 1) { return 0; } } // Secondly check if all the correct answers are given for (int i=0; i<goodAnswers.size(); i++) { if (((MMObjectNode)goodAnswers.get(i)).getIntValue("correct") == 1) { if (!givenAnswers.contains(goodAnswers.get(i))) { return 0; } } } // ALl tests succeeded: answer is correct return 1; } }
true
aa74196fe57b782fa2de29e661a4927ef556285c
Java
ysjava/qingge
/App/app/src/main/java/com/qingge/yangsong/qingge/fragments/main/ContactFragment.java
UTF-8
3,384
2.15625
2
[]
no_license
package com.qingge.yangsong.qingge.fragments.main; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.bumptech.glide.Glide; import com.qingge.yangsong.common.app.PresenterFragment; import com.qingge.yangsong.common.widget.PortraitView; import com.qingge.yangsong.common.widget.recycler.RecyclerAdapter; import com.qingge.yangsong.factory.model.db.User; import com.qingge.yangsong.factory.presenter.contact.ContactContract; import com.qingge.yangsong.factory.presenter.contact.ContactPresenter; import com.qingge.yangsong.qingge.R; import com.qingge.yangsong.qingge.activity.SearchActivity; import butterknife.BindView; /** * Created by White paper on 2019/10/16 * Describe :] */ public class ContactFragment extends PresenterFragment<ContactContract.Presenter> implements ContactContract.View,RecyclerAdapter.AdapterListener<User> { @BindView(R.id.recycler) RecyclerView mRecyclerView; @BindView(R.id.toolbar) Toolbar mToolbar; private RecyclerAdapter<User> adapter; @Override protected int getContentLayoutId() { return R.layout.fragment_contacts; } @Override protected void initWidget(View root) { super.initWidget(root); mToolbar.inflateMenu(R.menu.search_menu); mToolbar.setOnMenuItemClickListener(menuItem ->{ SearchActivity.show(getContext()); return false; }); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); adapter = new RecyclerAdapter<User>(this) { @Override protected int getItemViewType(int position, User user) { return R.layout.cell_contacts; } @Override protected ViewHolder<User> onCreateViewHolder(View view, int viewType) { return new ContactFragment.ViewHolder(view); } }; mRecyclerView.setAdapter(adapter); } @Override protected void initData() { super.initData(); mPresenter.start(); } @Override protected ContactPresenter initPresenter() { return new ContactPresenter(this); } @Override public RecyclerAdapter<User> getRecyclerAdapter() { return adapter; } @Override public void onAdapterDataChanged() { } @Override public void onItemClick(RecyclerAdapter.ViewHolder holder, User user) { } @Override public void onItemLongClick(RecyclerAdapter.ViewHolder holder, User user) { } class ViewHolder extends RecyclerAdapter.ViewHolder<User> { @BindView(R.id.im_portrait) PortraitView mPortraitView; @BindView(R.id.txt_contacts_name) TextView mName; @BindView(R.id.txt_contacts_desc) TextView mDesc; ViewHolder(@NonNull View itemView) { super(itemView); } @Override protected void onBind(User user) { mPortraitView.setup(Glide.with(getContext()), user); mName.setText(user.getName()); mDesc.setText(user.getDesc()); } } }
true
c125849ceab56a1b339b83d9bbafff3ec329ed90
Java
dineshk628/XYZ
/EasyAlert/mobile/src/main/java/com/example/dell/easyalert/TasksAdapter.java
UTF-8
2,265
2.453125
2
[]
no_license
package com.example.dell.easyalert; import android.content.Context; import android.database.Cursor; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.ShapeDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.LinearLayout; import android.widget.TextView; /** * Created by DELL on 15-04-2016. */ public class TasksAdapter extends CursorAdapter { Utility utility=new Utility(); public TasksAdapter(Context context, Cursor c, int flags) { super(context, c, flags); } @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { return LayoutInflater.from(context).inflate(R.layout.list_item_task, viewGroup, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView taskDistance = (TextView) view.findViewById(R.id.task_dist_textView); TextView taskNameView = (TextView) view.findViewById(R.id.task_name_textView); TextView taskLoc = (TextView) view.findViewById(R.id.task_location_textView); LinearLayout listItemLayout = (LinearLayout) view.findViewById(R.id.list_item_layout); //TODO: what is this? TasksFragment.distance = cursor.getInt(Constants.COL_MIN_DISTANCE); String task = cursor.getString(Constants.COL_TASK_NAME); String taskLocation = cursor.getString(Constants.COL_LOCATION_NAME); taskNameView.setText(task); taskLoc.setText(taskLocation); taskDistance.setText(utility.getDistanceDisplayString(context,TasksFragment.distance)); //If task is marked as Done, then strikethrough the text. if(cursor.getString(Constants.COL_DONE).equals("true")) { taskNameView.setPaintFlags(taskNameView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); taskDistance.setVisibility(View.INVISIBLE); } else { taskNameView.setPaintFlags(taskNameView.getPaintFlags()&(~Paint.STRIKE_THRU_TEXT_FLAG)); taskDistance.setVisibility(View.VISIBLE); } } }
true
d504c9e8a8f94592ba4f7110485ecf018a1a7de1
Java
XiaojieDing/bookstore-prototype
/src/main/java/bookstore/services/BookstoreJaxWS.java
UTF-8
3,700
2.359375
2
[]
no_license
package bookstore.services; import static java.text.MessageFormat.format; import java.math.BigDecimal; import javax.jws.WebService; import bookstore.Bookstore; import bookstore.Customer; import bookstore.CustomerManagement; import bookstore.InformationReporter; import bookstore.Item; import bookstore.NotificationMessage; import bookstore.Order; import bookstore.ProductAvailability; import bookstore.ShippingService; import bookstore.Supplier; import bookstore.Warehouse; // @formatter:off @WebService(endpointInterface = "bookstore.Bookstore", serviceName = "BookstoreService", targetNamespace = "http://infosys.tuwien.ac.at/aic10/ass1/dto/bookstore", portName = "BookstorePT") public class BookstoreJaxWS implements Bookstore { // @formatter:on public static final String SUCCESS_MESSAGE = "Successfully shipped all items to address: \"{0}\""; private Order order; private Customer aCustomer; private BigDecimal totalPrice = new BigDecimal(0); private Warehouse warehouse; private CustomerManagement customerService; private ShippingService shippingService; private Supplier supplier; private InformationReporter reporter; public BookstoreJaxWS(CustomerManagement customerService, Warehouse warehouse, ShippingService shippingService, Supplier supplier, InformationReporter reporter) { this.customerService = customerService; this.warehouse = warehouse; this.shippingService = shippingService; this.supplier = supplier; this.reporter = reporter; } // @formatter:off @Override public void requestOrder(Order anOrder) { this.order = anOrder; reporter.notifyNewOrderRequest(anOrder); aCustomer = customerService.getCustomer(anOrder.getCustomerId()); try { orderItemsOf(anOrder); } catch (RuntimeException orderError) { customerService.notify(aCustomer.getId(), toNotificationMessage(orderError.getMessage())); return; } try { shippingService.shipItems(itemsToArry(anOrder), aCustomer.getShippingAddress()); } catch (RuntimeException shippingError) { customerService.notify(aCustomer.getId(), toNotificationMessage(shippingError.getMessage())); return; } customerService.updateAccount(aCustomer.getId(), newCustomerBalance()); customerService.notify(aCustomer.getId(), toNotificationMessage(format(SUCCESS_MESSAGE, aCustomer.getShippingAddress()))); } // @formatter:on private void orderItemsOf(Order anOrder) { System.out.println("Orders"+ anOrder.toString()); for (Item each : anOrder.getItems()) { order(each); System.out.println(each.toString()); } } private void order(Item anItem) { if (availableInWarehouse(anItem)) { addToTotalPrice(orderFromWarehouse(anItem)); } else { addToTotalPrice(orderFromSupplier(anItem)); } } private BigDecimal orderFromWarehouse(Item anItem) { System.out.println(anItem.toString()); return warehouse.order(anItem.getProduct(), anItem.getQuantity()); } private void addToTotalPrice(BigDecimal price) { totalPrice = totalPrice.add(price); } private BigDecimal orderFromSupplier(Item anItem) { return supplier.order(anItem.getProduct(), anItem.getQuantity()); } private boolean availableInWarehouse(Item anItem) { ProductAvailability item = warehouse.checkAvailability(anItem.getProduct(), anItem.getQuantity()); return item.isAvailable(); } private Item[] itemsToArry(Order order) { return order.getItems().toArray(new Item[] {}); } private BigDecimal newCustomerBalance() { return aCustomer.getOpenBalance().subtract(totalPrice); } private NotificationMessage toNotificationMessage(String message) { return new NotificationMessage(message); } public Order getOrder() { return order; } }
true
55848acd264374bbc01c35b451f48fee6cf3c811
Java
kamalOrganization/JavaConcept
/src/main/java/com/StringJava/App.java
UTF-8
590
2.46875
2
[]
no_license
package com.StringJava; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Hello world! * */ public class App { @BeforeClass public static void hello( ) { System.out.println( "Hello World!" ); FirefoxDriver driver= new FirefoxDriver(); driver.get("http://google.com"); String title=driver.getTitle(); System.out.println("welcome"); } @Test public static void method2() { System.out.println("harish"); } }
true
634d3832bbad9fba34d731dee42e922edef26210
Java
saurabh1396/Book
/app/src/main/java/com/example/dellpc/book/BooksAdapter.java
UTF-8
1,948
2.46875
2
[]
no_license
package com.example.dellpc.book; import com.bumptech.glide.Glide; import android.content.Context; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class BooksAdapter extends RecyclerView.Adapter<BooksAdapter.MyViewHolder> { private Context mContext; private List<Books> booksList; public class MyViewHolder extends RecyclerView.ViewHolder{ public TextView title,price; public ImageView thumbnail, overflow; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.title); price = (TextView) view.findViewById(R.id.count); thumbnail = (ImageView) view.findViewById(R.id.thumbnail); overflow = (ImageView) view.findViewById(R.id.overflow); } } public BooksAdapter(Context mContext, List<Books> booksList) { this.mContext = mContext; this.booksList = booksList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.book_card, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { Books books = booksList.get(position); holder.title.setText(books.getName()); holder.price.setText(books.getPrice() + " pages"); // loading album cover using Glide library Glide.with(mContext).load(books.getThumbnail()).into(holder.thumbnail); } @Override public int getItemCount() { return booksList.size(); } }
true
ed7130e3c84a7ec52cc9da465825189fa1a17ffd
Java
marembo2008/tafsiri
/tafsiri-domain/src/main/java/de/tafsiri/domain/TranslationRequest.java
UTF-8
757
1.976563
2
[]
no_license
package de.tafsiri.domain; import java.util.List; import javax.annotation.Nonnull; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Singular; /** * * @author marembo */ @Getter @Builder @EqualsAndHashCode @AllArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PROTECTED) public final class TranslationRequest { /** * The key we request translation for. */ @Nonnull private TranslationKey key; /** * List of at least one translation locale, to translate the key to. */ @Nonnull @Singular private List<TranslationLocale> locales; }
true
6160ec3451eab690324e606a0b4cfc79478be1fe
Java
cevrard-unamur/slip-compiler
/src/test/java/be/unamur/info/b314/compiler/main/SlipSemanticsFunctionsTest.java
UTF-8
4,028
2.34375
2
[ "MIT" ]
permissive
package be.unamur.info.b314.compiler.main; import org.junit.Test; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SlipSemanticsFunctionsTest { private static final Logger LOG = LoggerFactory.getLogger(SlipSemanticsFunctionsTest.class); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); // Create a temporary folder for outputs deleted after tests @Rule public TestRule watcher = new TestWatcher() { // Prints message on logger before each test @Override protected void starting(Description description) { LOG.info(String.format("Starting test: %s()...", description.getMethodName())); }; }; // tests OK @Test public void test_void_function_ok() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ok/void_function.slip", testFolder.newFile(), true, "semantics::functions: void_function.slip"); } @Test public void test_function_with_array_ok() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ok/function_with_array.slip", testFolder.newFile(), true, "semantics::functions: function_with_array.slip"); } @Test public void test_funct_with_var_ok() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ok/funct_with_var.slip", testFolder.newFile(), true, "semantics::functions: funct_with_var.slip"); } @Test public void test_valid_name_ok() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ok/valid_name.slip", testFolder.newFile(), true, "semantics::functions: valid_name.slip"); } // tests KO @Test public void test_duplicate_fct_name_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/duplicate_fct_name.slip", testFolder.newFile(), false, "semantics::functions: duplicate_fct_name.slip"); } @Test public void test_variable_with_name_parameter_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/variable_with_name_parameter.slip", testFolder.newFile(), false, "semantics::functions: variable_with_name_parameter.slip"); } @Test public void test_void_function_assign_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/void_function_assign.slip", testFolder.newFile(), false, "semantics::functions: void_function_assign.slip"); } @Test public void test_invalid_name_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/invalid_name.slip", testFolder.newFile(), false, "semantics::functions: invalid_name.slip"); } @Test public void test_function_with_same_parameters_name_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/function_with_same_parameters_name.slip", testFolder.newFile(), false, "semantics::functions: function_with_same_parameters_name.slip"); } @Test public void test_void_function_return_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/void_function_return.slip", testFolder.newFile(), false, "semantics::functions: void_function_return.slip"); } @Test public void test_duplicate_param_name_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/duplicate_param_name.slip", testFolder.newFile(), false, "semantics::functions: duplicate_param_name.slip"); } @Test public void test_param_name_as_function_ko() throws Exception{ CompilerTestHelper.launchCompilation("/semantics/functions/ko/param_name_as_function.slip", testFolder.newFile(), false, "semantics::functions: param_name_as_function.slip"); } }
true
1dfe5ab72c16f5593de9b05cc71ea2b5409f7c40
Java
ik6cgsg/UniqueCircle
/app/src/main/java/edu/amd/spbstu/uniquecircle/game/Timer.java
UTF-8
1,777
2.546875
3
[]
no_license
package edu.amd.spbstu.uniquecircle.game; import android.util.Log; import edu.amd.spbstu.uniquecircle.ViewGame; import edu.amd.spbstu.uniquecircle.engine.BitmapRenderer; import edu.amd.spbstu.uniquecircle.engine.GameObject; import edu.amd.spbstu.uniquecircle.engine.TextRenderer; import edu.amd.spbstu.uniquecircle.support.event.Event; public class Timer { private static final String TAG = "Timer"; private GameObject back; private GameObject text; private TimerController timerController; private static final int BACK_SPRITE_WIDTH = 128; private static final String BACK_SPRITE_NAME = "circle"; private Timer(GameObject back, GameObject text, TimerController timerController) { this.back = back; this.text = text; this.timerController = timerController; } public static Timer create(GameObject parent, String name, float endTime) { if (parent == null) { Log.e(TAG, "null game object"); return null; } GameObject back = parent.addChild(name); GameObject text = back.addChild("timer_text"); BitmapRenderer.addComponent(back, BACK_SPRITE_NAME); TextRenderer.addComponent(text, "timer", ViewGame.dp2Px(BACK_SPRITE_WIDTH) * 0.30f); TimerController timerController = TimerController.addComponent(text, endTime); return new Timer(back, text, timerController); } public void start() { timerController.start(); } public void stop() { timerController.stop(); } public void reset() { timerController.reset(); } public Event getOnTimerEnd() { return timerController.getOnTimerEnd(); } public GameObject getGameObject() { return back; } }
true
afc8d784edc711dd773248b23141d42fb30fe609
Java
akankshalonhari/androidRepository
/PostItApp/app/src/main/java/com/codepath/akanksha/postitapp/EditItemActivity.java
UTF-8
1,817
2.59375
3
[ "Apache-2.0" ]
permissive
package com.codepath.akanksha.postitapp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class EditItemActivity extends AppCompatActivity { String valueToEdit = null; int pos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_item); Button btnSave = (Button) findViewById(R.id.btnSave); //retrieving parameters passed from calling method valueToEdit = getIntent().getStringExtra("valueToEdit"); pos = getIntent().getIntExtra("position", 0); EditText editedValue = (EditText) findViewById(R.id.etEditedValue); editedValue.setText(valueToEdit); //setting cursor value to end of the current text editedValue.setSelection(editedValue.getText().length()); //calling listener on Save action btnSave.setOnClickListener(onSaveListener); } /* Setting listener to save the edited list value and send new value back to calling activity */ private OnClickListener onSaveListener = new OnClickListener() { @Override public void onClick(View v){ EditText newVal = (EditText) findViewById(R.id.etEditedValue); String resultNewValue = newVal.getText().toString(); Intent resultData = new Intent(); resultData.putExtra("resultData" , resultNewValue); resultData.putExtra("resultPosition", pos); resultData.putExtra("oldValue", valueToEdit); setResult(RESULT_OK, resultData); finish(); } }; }
true
405dba982839aac4e622be974b8972ed3688e8d0
Java
JackChen-China/leetcode_problems_solution
/src/test/CompareBigDecimalTest.java
UTF-8
731
2.953125
3
[]
no_license
package test; import java.math.BigDecimal; import java.util.HashMap; import java.util.HashSet; import java.util.TreeSet; /** * Created by JackChen on 2017/7/14. */ public class CompareBigDecimalTest { public static void main(String[] args){ BigDecimal b1 = new BigDecimal("1.0"); BigDecimal b2 = new BigDecimal("1.00"); HashSet set = new HashSet(); set.add(b1); set.add(b2); System.out.println(b1); System.out.println(b2); System.out.println(set.size()); TreeSet tset = new TreeSet(); tset.add(b1); tset.add(b2); System.out.println(tset.size()); System.out.println(tset.first()); } }
true
b5b54ce40ed374af8d4770f051fe2fb4494816c4
Java
AnkushNakaskar/SpringTokenExample
/src/main/java/com/token/ankush/controller/UserController.java
UTF-8
2,144
2.296875
2
[]
no_license
package com.token.ankush.controller; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import com.token.ankush.UserEntity; import com.token.ankush.service.UserService; import com.token.ankush.utility.SpringTokenUtitlity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @CrossOrigin(origins = "http://localhost", maxAge = 3600) @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/register", method = RequestMethod.POST) public UserEntity registerUser(@RequestBody UserEntity user) { return userService.save(user); } @RequestMapping(value = "/{userid}", method = RequestMethod.GET) public UserEntity findByEmail(@PathVariable Long userid) { return userService.findByUserID(userid); } @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(@RequestBody UserEntity login, HttpServletResponse response) throws ServletException { String jwtToken = ""; if (login.getEmail() == null || login.getPassword() == null) { throw new ServletException("Please fill in username and password"); } String email = login.getEmail(); String password = login.getPassword(); UserEntity user = userService.findByEmail(email); if (user == null) { throw new ServletException("User email not found."); } String pwd = user.getPassword(); if (!password.equals(pwd)) { throw new ServletException("Invalid login. Please check your name and password."); } String randomToken = SpringTokenUtitlity.generateRandomUserToken(); SpringTokenUtitlity.generateCookiesForresponse(response,randomToken); String subject = SpringTokenUtitlity.generateMessageDigest(randomToken); return SpringTokenUtitlity.generateJWTToken(subject,email); } }
true
eed042744687e91e6ef62caf40aae61469978288
Java
karelnegreira/mongodb1rest
/src/main/java/com/karelcode/repository/PersonaRepository.java
UTF-8
468
1.882813
2
[]
no_license
package com.karelcode.repository; import java.awt.List; //import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.karelcode.model.Persona; @Repository public interface PersonaRepository extends MongoRepository<Persona, Integer>{ public Persona findByName(String name); public java.util.List<Persona> findByLocation(String location); }
true
cfbd1d180c4cc33adff0a54cf4b9af1464fac8a8
Java
Tijana994/PrivacyDSL
/Project/privacycomparator-emf/src/privacymodel/ProcessingReason.java
UTF-8
9,529
2.015625
2
[]
no_license
/** */ package privacymodel; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.AbstractEnumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Processing Reason</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see privacymodel.PrivacymodelPackage#getProcessingReason() * @model * @generated */ public final class ProcessingReason extends AbstractEnumerator { /** * The '<em><b>Research</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Research</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #RESEARCH_LITERAL * @model name="Research" * @generated * @ordered */ public static final int RESEARCH = 0; /** * The '<em><b>Public Health</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Public Health</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PUBLIC_HEALTH_LITERAL * @model name="PublicHealth" * @generated * @ordered */ public static final int PUBLIC_HEALTH = 1; /** * The '<em><b>Out Of Scope</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Out Of Scope</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OUT_OF_SCOPE_LITERAL * @model name="OutOfScope" * @generated * @ordered */ public static final int OUT_OF_SCOPE = 2; /** * The '<em><b>Public Interest</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Public Interest</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PUBLIC_INTEREST_LITERAL * @model name="PublicInterest" * @generated * @ordered */ public static final int PUBLIC_INTEREST = 3; /** * The '<em><b>Statistical Purposes</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Statistical Purposes</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #STATISTICAL_PURPOSES_LITERAL * @model name="StatisticalPurposes" * @generated * @ordered */ public static final int STATISTICAL_PURPOSES = 4; /** * The '<em><b>Exercising Specific Rights</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Exercising Specific Rights</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #EXERCISING_SPECIFIC_RIGHTS_LITERAL * @model name="ExercisingSpecificRights" * @generated * @ordered */ public static final int EXERCISING_SPECIFIC_RIGHTS = 5; /** * The '<em><b>Marketing</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Marketing</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #MARKETING_LITERAL * @model name="Marketing" * @generated * @ordered */ public static final int MARKETING = 6; /** * The '<em><b>Testing</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Testing</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #TESTING_LITERAL * @model name="Testing" * @generated * @ordered */ public static final int TESTING = 7; /** * The '<em><b>Profiling</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Profiling</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PROFILING_LITERAL * @model name="Profiling" * @generated * @ordered */ public static final int PROFILING = 8; /** * The '<em><b>Research</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #RESEARCH * @generated * @ordered */ public static final ProcessingReason RESEARCH_LITERAL = new ProcessingReason(RESEARCH, "Research", "Research"); /** * The '<em><b>Public Health</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PUBLIC_HEALTH * @generated * @ordered */ public static final ProcessingReason PUBLIC_HEALTH_LITERAL = new ProcessingReason(PUBLIC_HEALTH, "PublicHealth", "PublicHealth"); /** * The '<em><b>Out Of Scope</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OUT_OF_SCOPE * @generated * @ordered */ public static final ProcessingReason OUT_OF_SCOPE_LITERAL = new ProcessingReason(OUT_OF_SCOPE, "OutOfScope", "OutOfScope"); /** * The '<em><b>Public Interest</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PUBLIC_INTEREST * @generated * @ordered */ public static final ProcessingReason PUBLIC_INTEREST_LITERAL = new ProcessingReason(PUBLIC_INTEREST, "PublicInterest", "PublicInterest"); /** * The '<em><b>Statistical Purposes</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #STATISTICAL_PURPOSES * @generated * @ordered */ public static final ProcessingReason STATISTICAL_PURPOSES_LITERAL = new ProcessingReason(STATISTICAL_PURPOSES, "StatisticalPurposes", "StatisticalPurposes"); /** * The '<em><b>Exercising Specific Rights</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #EXERCISING_SPECIFIC_RIGHTS * @generated * @ordered */ public static final ProcessingReason EXERCISING_SPECIFIC_RIGHTS_LITERAL = new ProcessingReason(EXERCISING_SPECIFIC_RIGHTS, "ExercisingSpecificRights", "ExercisingSpecificRights"); /** * The '<em><b>Marketing</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #MARKETING * @generated * @ordered */ public static final ProcessingReason MARKETING_LITERAL = new ProcessingReason(MARKETING, "Marketing", "Marketing"); /** * The '<em><b>Testing</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #TESTING * @generated * @ordered */ public static final ProcessingReason TESTING_LITERAL = new ProcessingReason(TESTING, "Testing", "Testing"); /** * The '<em><b>Profiling</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PROFILING * @generated * @ordered */ public static final ProcessingReason PROFILING_LITERAL = new ProcessingReason(PROFILING, "Profiling", "Profiling"); /** * An array of all the '<em><b>Processing Reason</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final ProcessingReason[] VALUES_ARRAY = new ProcessingReason[] { RESEARCH_LITERAL, PUBLIC_HEALTH_LITERAL, OUT_OF_SCOPE_LITERAL, PUBLIC_INTEREST_LITERAL, STATISTICAL_PURPOSES_LITERAL, EXERCISING_SPECIFIC_RIGHTS_LITERAL, MARKETING_LITERAL, TESTING_LITERAL, PROFILING_LITERAL, }; /** * A public read-only list of all the '<em><b>Processing Reason</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Processing Reason</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ProcessingReason get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ProcessingReason result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Processing Reason</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ProcessingReason getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ProcessingReason result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Processing Reason</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ProcessingReason get(int value) { switch (value) { case RESEARCH: return RESEARCH_LITERAL; case PUBLIC_HEALTH: return PUBLIC_HEALTH_LITERAL; case OUT_OF_SCOPE: return OUT_OF_SCOPE_LITERAL; case PUBLIC_INTEREST: return PUBLIC_INTEREST_LITERAL; case STATISTICAL_PURPOSES: return STATISTICAL_PURPOSES_LITERAL; case EXERCISING_SPECIFIC_RIGHTS: return EXERCISING_SPECIFIC_RIGHTS_LITERAL; case MARKETING: return MARKETING_LITERAL; case TESTING: return TESTING_LITERAL; case PROFILING: return PROFILING_LITERAL; } return null; } /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private ProcessingReason(int value, String name, String literal) { super(value, name, literal); } } //ProcessingReason
true
26b830c65ebeae9213818c60352621bb29fdf363
Java
ghavinj/MySQLExampleProject2
/app/src/main/java/com/ghavinj/mysqlexampleproject2/DbStrings.java
UTF-8
301
1.671875
2
[]
no_license
package com.ghavinj.mysqlexampleproject2; public class DbStrings { static final String DATABASE_URL = "72.52.246.254:3306"; static final String DATABASE_NAME = "ittechnician_mhs"; static final String USERNAME = "ittechnician_drdadmin"; static final String PASSWORD = "Super2019$$"; }
true
328fccf7f67492c2c5bf2c07016096a104fedcef
Java
Hennessyan/leetcode
/src/apple/Q923.java
UTF-8
3,309
3.71875
4
[]
no_license
package apple; import java.util.Arrays; // 3Sum With Multiplicity public class Q923 { public static void main(String[] args) { Q923 q = new Q923(); int[] A = {1,1,2,2,3,3,4,4,5,5}; int[] B = {1,1,2,2,2,2}; System.out.println(q.threeSumMulti(A, 8)); //20 System.out.println(q.threeSumMulti(B, 5)); //12 } // O(n^2) O(1) public int threeSumMulti(int[] A, int target) { if(A == null || A.length < 3) { return 0; } Arrays.sort(A); int mod = (int)1e9 + 7; int len = A.length; long ans = 0; for(int i = 0; i < len - 2; i++) { int t = target - A[i]; int l = i + 1, r = len - 1; while(l < r) { int sum = A[l] + A[r]; if(sum < t) { l++; } else if(sum > t) { r--; } else if(A[l] != A[r]) { int cl = 1, cr = 1; while(l + 1< r && A[l] == A[l + 1]) { cl++; l++; } while(l < r - 1 && A[r] == A[r - 1]) { cr++; r--; } ans = (ans + cl * cr) % mod; l++; r--; } else { int count = r - l + 1; ans = (ans + count * (count - 1) / 2) % mod; break; } } } return (int)ans; } // O(n^2) O(n) public int threeSumMulti1(int[] A, int target) { if(A == null || A.length < 3) { return 0; } Arrays.sort(A); long ans = 0; int mod = (int)1e9+7; long[] count = new long[101]; // can't use int, because maximum element in A is 3000 => 3000^3 > Integer.Max_value int unique = 0; for(int a : A) { if(count[a] == 0) { unique++; } count[a]++; } int[] keys = new int[unique]; int index = 0; for(int j = 0; j < 101; j++) { if(count[j] > 0) { keys[index++] = j; } } for(int i = 0; i < unique; i++) { int x = keys[i]; int t = target - x; int j = i, k = unique - 1; while(j <= k) { int y = keys[j], z = keys[k]; if(y + z < t) { j++; } else if(y + z > t) { k--; } else { if(i < j && j < k) { // can use "!=" ans += count[x] * count[y] * count[z]; } else if(i < j && j == k) { ans += count[x] * count[y] * (count[y] - 1) / 2; } else if(i == j && j < k) { ans += count[z] * count[x] * (count[x] - 1) / 2; } else { ans += count[x] * (count[x] - 1) * (count[x] - 2) / 6; } ans %= mod; j++; k--; } } } return (int) ans; } }
true
7de13884f8c1f58208259f8f91843b3191397712
Java
pradeepkumar41/CodingNinjas
/eclipse-workspace/DataStructure/src/DataStructure/BubbleSortLinkedList.java
UTF-8
1,943
3.75
4
[]
no_license
package DataStructure; public class BubbleSortLinkedList { static int length(LinkedListNode<Integer> head) { LinkedListNode<Integer> temp=head; int length=0; while(temp!=null) { temp=temp.next; length++; } return length; } static LinkedListNode<Integer> deleteIth(LinkedListNode<Integer> head,int i) { if(i==0) { head=head.next; return head; } else { LinkedListNode<Integer> node,temp=head; int loop; loop=i-1; while(loop!=0) { temp=temp.next; loop--; } node=temp.next; //saving the address of first Node temp.next=temp.next.next; return node; } } static LinkedListNode<Integer> InsertIth(LinkedListNode<Integer> head,LinkedListNode<Integer> node,int i){ if(i==0) { node.next=head; head=node; return head; } else { LinkedListNode<Integer>temp=head; int loop; loop=i-1; while(loop!=0) { temp=temp.next; loop--; } node.next=temp.next; temp.next=node; return head; } } static LinkedListNode swap(LinkedListNode head,int i,int j) { //delete ith node LinkedListNode node1,node2; node1=deleteIth(head, i); //delete and save i //saving the address of first Node node2=deleteIth(head, j); //delete and save j head=InsertIth(head, node1, i); head=InsertIth(head, node2, i); return head; } static LinkedListNode bubbleSort(LinkedListNode head) { int n=length(head); int k=0,l=0; for(int i=0;i<n;i++) { k=0;l=1; LinkedListNode previous=null,next=head.next,current=head; LinkedListNode first= head; LinkedListNode second=head.next; for(int j=0;j<n-i;j++) { if(first.data.compareTo(second.data)<0) { //update k++; first=second; //update the pointers second=second.next; } else { first=second; //update the pointers second=second.next; k++; } } } } }
true
4a6d5bcf48d16a422a4a2d14df7c3ab71965b606
Java
copperfield013/xfjddata
/src/main/java/com/zhsq/biz/constant/BaseConstant.java
UTF-8
3,007
2.390625
2
[]
no_license
package com.zhsq.biz.constant; import java.util.HashMap; import java.util.Map; public class BaseConstant { public static final Integer LABEL_AUTH_工作任务管理类=30153;//权限标签之工作任务管理类 public static final String TYPE_工作任务="XFJDE379";//工作任务类型 public static final String TYPE_人口信息="XFJDE001";//人口信息类型 public static final String TYPE_家庭信息="XFJDE305";//人口信息类型 public static final String TYPE_四类人员="XFJDE1015";//人员分类统计 /** * 根据枚举和户主关系获取人与人之间的家庭成员的关系 */ private static Map map = new HashMap<>(); static { map.put(EnumKeyValue.ENUM_和户主关系_母亲, RelationType.RR_人口信息_子女_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_父亲, RelationType.RR_人口信息_子女_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_配偶, RelationType.RR_人口信息_夫妻_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_女, RelationType.RR_人口信息_父母_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_子, RelationType.RR_人口信息_父母_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_孙女, RelationType.RR_人口信息_爷爷奶奶_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_孙子, RelationType.RR_人口信息_爷爷奶奶_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_奶奶, RelationType.RR_人口信息_孙子孙女_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_爷爷, RelationType.RR_人口信息_孙子孙女_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_外公, RelationType.RR_人口信息_外孙子和外孙女_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_外婆, RelationType.RR_人口信息_外孙子和外孙女_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_外孙女, RelationType.RR_人口信息_外公和外婆_人口信息); map.put(EnumKeyValue.ENUM_和户主关系_外孙子, RelationType.RR_人口信息_外公和外婆_人口信息); /*map.put(EnumKeyValue.ENUM_和户主关系_户主, RelationType.RR_人口); * map.put(EnumKeyValue.ENUM_和户主关系_孙女, RelationType.RR_人口信息_); map.put(EnumKeyValue.ENUM_和户主关系_孙子, value); map.put(EnumKeyValue.ENUM_和户主关系_外孙女, value); map.put(EnumKeyValue.ENUM_和户主关系_外孙子, value); map.put(EnumKeyValue.ENUM_和户主关系_曾外孙女, value); map.put(EnumKeyValue.ENUM_和户主关系_曾外孙子, value);*/ } public static String getRelationName(String enumRelationName) { if (enumRelationName== null || "".equals(enumRelationName)) { return null; } int parseInt; try { parseInt = Integer.parseInt(enumRelationName); } catch (NumberFormatException e) { return null; } String relationName = (String)map.get(parseInt); return relationName; } }
true
8d89ac0ea998710b59346147b33ea050a09ee920
Java
NiceCodeBro/CSE241_OOP
/HW08/Bigram.java
UTF-8
389
2.71875
3
[]
no_license
/* The base class will be Bigram which will have only pure abstract functions and nothing else. */ /** * @param <T> * * @author MSD */ public interface Bigram<T> { abstract public void readFile(String fileName) throws Exception; abstract public String toString(); abstract public int numGrams() ; abstract public int numOfGrams(T var1, T var2); }
true
59f60f37b03aa93748c485885083a27ef4fdfca0
Java
GoodBoyCoder/opera-system-lab
/lab3-03/src/entity/Command.java
UTF-8
537
2.375
2
[]
no_license
package entity; /** * @author GoodBoy * @date 2021-06-08 */ public class Command { private final long sectionId; private final long pageId; private final long offset; public Command(long sectionId, long pageId, long offset) { this.sectionId = sectionId; this.pageId = pageId; this.offset = offset; } public long getSectionId() { return sectionId; } public long getPageId() { return pageId; } public long getOffset() { return offset; } }
true
5ea271d74bd92666ad216a147ac3da642fb19b7c
Java
aggrey-aggrey/selenium-hybrid
/src/test/java/seleniumhybrid/CourseTest.java
UTF-8
762
2.15625
2
[]
no_license
package seleniumhybrid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.automation.pageobjects.Course; import com.automation.testBase.TestBase; //@Listeners(InvokedMethodListener.class) public class CourseTest extends TestBase{ private static final Logger log = LogManager.getLogger(CourseTest.class.getName()); Course course; @BeforeMethod public void setUp() { driver = getDriver(); } @Test public void verifyCategoryDropDown () throws InterruptedException { log.info("=== Starting VerifyCategoryDropDown Test ==="); course = new Course(driver); course.selectCategoryDropDown(); log.info("End Test"); } }
true
3790fe19692abb6925620bfbdc35b259f0c2ca16
Java
dunwen/JavaMode
/策略模式/src/cn/cqut/edu/Method.java
UTF-8
66
2.09375
2
[]
no_license
package cn.cqut.edu; public interface Method { void method(); }
true
4dca095c36a8b96978650bc5efd10b3fbef7336e
Java
nguyenvancuongit/SampleProjectAndroid
/app/src/main/java/com/app/temp/features/home/repolist/model/post/PostResponse.java
UTF-8
513
2.28125
2
[]
no_license
package com.app.temp.features.home.repolist.model.post; import java.util.LinkedList; import java.util.List; /** * Created by nguyen_van_cuong on 13/11/2017. */ public class PostResponse { private List<Post> posts; public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this.posts = posts; } public void add(Post post) { if (posts == null) { posts = new LinkedList<>(); } posts.add(post); } }
true
20f5f6d56500a957e5f0d9df5af6acf848383a3a
Java
pysmell/git-practice
/javaStudy/src/main/java/LeetCode/Solution.java
UTF-8
2,176
3.46875
3
[ "Apache-2.0" ]
permissive
package LeetCode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 给定一个包含 n 个整数的数组 nums, * 判断 nums 中是否存在三个元素 a,b,c , * 使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 */ public class Solution { public static void main(String[] args) { int[] nums = new int[]{-1, 0, 1, 2, -1, -4}; threeSum(nums); } public static List<List<Integer>> threeSum(int[] nums) { for (int i = 1; i < nums.length; i++) { int j = i - 1; int insert = nums[i]; while (j >= 0 && insert < nums[j]) { nums[j + 1] = nums[j]; j--; } nums[j + 1] = insert; } int len = nums.length; List<List<Integer>> reLists = new ArrayList<List<Integer>>(); for (int i = 0; i < nums.length-2; i++) { if(nums[i]>0 || nums[nums.length-1] <0){ break; } if(((i>0)&&(nums[i-1]==nums[i]))){ continue; } for (int j = i + 1; j < nums.length-1; j++) { int sum = nums[i] + nums[j]; if(sum>0){ break; } if((j>i+1)&&nums[j-1]==nums[j]){ continue; } int start =j+1; int end = len-1; while(start<end){ int middle = (start+(end-start)/2); if(sum+nums[middle]<0){ start = middle; } if(sum+nums[middle]>0){ end = middle; } if(sum+nums[middle]==0){ List<Integer> list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[middle]); reLists.add(list); break; } } } } return reLists; } }
true
b8c1ac7e642387a9498ca3a62c78d28cc2e91aef
Java
techwiki/terracotta-newrelic-plugin
/src/com/newrelic/plugins/terracotta/metrics/data/DifferentialMetricData.java
UTF-8
3,138
2.921875
3
[ "MIT" ]
permissive
package com.newrelic.plugins.terracotta.metrics.data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * This metric calculates the added values during a time window * Helpful to get a total added count + rate/sec */ public class DifferentialMetricData extends SummaryMetricData implements Cloneable { private static Logger log = LoggerFactory.getLogger(DifferentialMetricData.class); private volatile boolean firstPass = true; private volatile double lastValue = Double.NaN; private volatile long startCaptureTimeInMillis = Long.MIN_VALUE; private volatile long lastCaptureTimeInMillis = Long.MIN_VALUE; public DifferentialMetricData() { super(); } protected DifferentialMetricData(DifferentialMetricData metric) { super(metric); if(null != metric){ this.firstPass = metric.firstPass; this.lastValue = metric.lastValue; this.lastCaptureTimeInMillis = metric.lastCaptureTimeInMillis; this.startCaptureTimeInMillis = metric.startCaptureTimeInMillis; } } @Override public void add(Number... newMetricValues){ long timeCapture = System.currentTimeMillis();; //do nothing if the metric is null. Work with only one value here if(null != newMetricValues && newMetricValues.length > 0 && null != newMetricValues[0]){ double newValue = newMetricValues[0].doubleValue(); //only assign the startTime if it is the first pass (and only add to the dataset if it is not the first time) if(firstPass){ if(log.isDebugEnabled()) log.debug(String.format("First pass...capturing start time in millis: %d", timeCapture)); startCaptureTimeInMillis = timeCapture; } else { double diff = newValue - lastValue; if(log.isDebugEnabled()) log.debug(String.format("Adding difference: NewValue[%f]-LastValue[%f]=%f", newValue, lastValue, diff)); //add the difference to the dataset dataset.addValue(diff); lastAddedValue = diff; } lastValue = newValue; // save the value for next lastCaptureTimeInMillis = timeCapture; // save the end time for rate calculation if(log.isDebugEnabled()) log.debug(String.format("Saving new value %f and current time %d for use in next iteration", lastValue, timeCapture)); //make sure to set firstPass to false at this point firstPass = false; } else { if(log.isDebugEnabled()) log.debug("value to add is null...will not count as a valid datapoint."); } } // public double getRatePerSecond() { // return getSum() * 1000 / (lastCaptureTimeInMillis - startCaptureTimeInMillis); // } @Override public DifferentialMetricData clone() throws CloneNotSupportedException { DifferentialMetricData cloned = new DifferentialMetricData(this); return cloned; } @Override public String toString() { StringBuilder outBuffer = new StringBuilder(); String endl = "\n"; outBuffer.append("DifferentialMetricData:").append(endl); outBuffer.append("startCaptureTimeInMillis: ").append(startCaptureTimeInMillis).append(endl); outBuffer.append("lastCaptureTimeInMillis: ").append(lastCaptureTimeInMillis); outBuffer.append(dataset.toString()); return outBuffer.toString(); } }
true
a6ea8965d90a8ae572a3a9d650fff59c794ef83d
Java
TF-185/bbn-immortals
/phase02/immortals_repo/knowledge-repo/knowledge-repo/repository-service/src/main/java/com/securboration/immortals/service/jar/TtlzContentVisitor.java
UTF-8
202
1.5
2
[]
no_license
package com.securboration.immortals.service.jar; public interface TtlzContentVisitor { public void visit( final String name, byte[] content ); }
true
fa6884d71f17a1a0541b2c6aed236028bf98b53c
Java
zhougan870822/findviews
/src/com/zhoug/plugin/android/dialog/FindViewDialog.java
UTF-8
3,702
2.015625
2
[]
no_license
package com.zhoug.plugin.android.dialog; import com.zhoug.plugin.android.ClassWriter; import com.zhoug.plugin.android.beans.ResIdBean; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.DefaultTableModel; import java.awt.event.*; import java.util.List; public class FindViewDialog extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTable tableView; private JButton SelectAll; private JCheckBox cbapi26; private JCheckBox cbM; private OnListener onListener; private List<ResIdBean> resIdBeanList; private boolean allSelected=true; private static boolean api26=true; private static boolean m=true; public FindViewDialog() { setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); tableView.setRowHeight(30); SelectAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(allSelected){ allSelected=false; }else{ allSelected=true; } onListener.onSelectAll(allSelected); } }); cbapi26.setSelected(ClassWriter.API26); cbapi26.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { ClassWriter.API26=cbapi26.isSelected(); } }); cbM.setSelected(ClassWriter.prefixM); cbM.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { ClassWriter.prefixM=cbM.isSelected(); onListener.onPrefixM(cbM.isSelected()); } }); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onListener.onOk(); onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onListener.onCancel(); onCancel(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } private void onOK() { // add your code here dispose(); } private void onCancel() { // add your code here if necessary dispose(); } public void setTableModel(DefaultTableModel model) { tableView.setModel(model); tableView.getColumnModel().getColumn(0).setPreferredWidth(20); } /* public static void main(String[] args) { FindViewDialog dialog = new FindViewDialog(); dialog.pack(); dialog.setVisible(true); System.exit(0); }*/ public void setOnListener(OnListener onListener) { this.onListener = onListener; } public interface OnListener{ void onSelectAll(boolean selectAll); void onPrefixM(boolean addPrefixM); void onOk(); void onCancel(); } }
true
ef34c903950fe263ce58ae713d8827db992f13f4
Java
adnanisajbeg/java-cro-reactive-service
/s3-file-data-service/src/main/java/is/symphony/test/javacro/s3/service/S3PullService.java
UTF-8
4,167
2.03125
2
[]
no_license
package is.symphony.test.javacro.s3.service; import is.symphony.test.javacro.s3.properties.S3FileDataServiceProperties; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.*; import javax.annotation.PostConstruct; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; @Service public class S3PullService { private final S3AsyncClient s3AsyncClient; private final S3FileDataServiceProperties s3FileDataServiceProperties; private final FileProcessingService fileProcessingService; public S3PullService(final S3AsyncClient s3AsyncClient, final S3FileDataServiceProperties s3FileDataServiceProperties, final FileProcessingService fileProcessingService) { this.s3AsyncClient = s3AsyncClient; this.s3FileDataServiceProperties = s3FileDataServiceProperties; this.fileProcessingService = fileProcessingService; } @PostConstruct public void data() { getAllFileNamesFromBucket().log().subscribe(); } public Flux<ByteBuffer> getFileForAsset(final String key) { return Mono.fromFuture( s3AsyncClient .getObject(GetObjectRequest.builder() .bucket(s3FileDataServiceProperties.getBucket()) .key(key) .build(), new FluxResponseProvider())) .switchIfEmpty(Mono.error(new RuntimeException("Failed to get data from S3 bucket!"))) .flatMapMany(FluxResponse::getFlux); } public Flux<S3Object> getAllFileNamesFromBucket() { return Mono.fromFuture(s3AsyncClient .listObjects(ListObjectsRequest .builder() .bucket(s3FileDataServiceProperties.getBucket()) .build())) .map(ListObjectsResponse::contents) .doOnError(e -> Mono.error(new RuntimeException("Better error message"))) .flatMapIterable(list -> list); } static class FluxResponseProvider implements AsyncResponseTransformer<GetObjectResponse, FluxResponse> { private FluxResponse response; @Override public CompletableFuture<FluxResponse> prepare() { response = new FluxResponse(); return response.cf; } @Override public void onResponse(final GetObjectResponse sdkResponse) { this.response.sdkResponse = sdkResponse; } @Override public void onStream(final SdkPublisher<ByteBuffer> publisher) { response.flux = Flux.from(publisher); response.cf.complete(response); } @Override public void exceptionOccurred(final Throwable error) { response.cf.completeExceptionally(error); } } /** * Holds the API response and stream * @author Philippe */ static class FluxResponse { final CompletableFuture<FluxResponse> cf = new CompletableFuture<>(); private GetObjectResponse sdkResponse; private Flux<ByteBuffer> flux; public CompletableFuture<FluxResponse> getCf() { return cf; } public GetObjectResponse getSdkResponse() { return sdkResponse; } public FluxResponse setSdkResponse(final GetObjectResponse sdkResponse) { this.sdkResponse = sdkResponse; return this; } public Flux<ByteBuffer> getFlux() { return flux; } public FluxResponse setFlux(final Flux<ByteBuffer> flux) { this.flux = flux; return this; } } }
true
014429cc1ec16226d060deed05e01b0a51089e44
Java
JajaInks/SchoolRP
/Source/src/entite/Groupes.java
UTF-8
571
2.234375
2
[]
no_license
package entite; import java.util.Date; public class Groupes { int idGroupe; int idMatiere; String libelGroupe; public int getIdGroupe() { return idGroupe; } public void setIdGroupe(int idGroupe) { this.idGroupe = idGroupe; } public int getIdMatiere() { return idMatiere; } public void setIdMatiere(int idMatiere) { this.idMatiere = idMatiere; } public String getLibelGroupe() { return libelGroupe; } public void setLibelGroupe(String libelGroupe) { this.libelGroupe = libelGroupe; } public String toString() { return libelGroupe; } }
true
fc233d091e7ac84575be56905a15e9386ddbe824
Java
Ninjars/DontBeEvil
/app/src/main/java/com/projects/jez/dontbeevil/state/GameState.java
UTF-8
533
2.421875
2
[]
no_license
package com.projects.jez.dontbeevil.state; import com.projects.jez.dontbeevil.data.Incrementer; import com.projects.jez.dontbeevil.managers.IncrementerManager; import java.util.Collection; /** * Created by Jez on 18/03/2016. */ public class GameState { private final IncrementerManager incrementerManager; public GameState(IncrementerManager incManager) { incrementerManager = incManager; } public Collection<Incrementer> getReadouts() { return incrementerManager.getAllIncrementers(); } }
true
64e5116a3e0150257d1d4bfaf0b228f66706675c
Java
kapsky5/AppDevLab
/TicTacToe/app/src/main/java/com/example/tictactoe/MainActivity.java
UTF-8
4,424
2.671875
3
[]
no_license
package com.example.tictactoe; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private final static int GRID_SIZE = 3; private CellStatus[][] mGameState; private ImageButton[][] mButtons; private Button mResetButton; private TextView mMessageText; private int mCurrentPlayer = CellStatus.FIRST_PLAYER; private void resetGameState() { mMessageText.setText("Tic Tac Toe"); for (int i = 0; i < GRID_SIZE; ++i) { for (int j = 0; j < GRID_SIZE; ++j) { mGameState[i][j] = new CellStatus(); mButtons[i][j].setImageResource(R.drawable.empty); } } } protected int checkGameWin() { if (checkPlayerWon(CellStatus.FIRST_PLAYER)) return CellStatus.FIRST_PLAYER; if (checkPlayerWon(CellStatus.SECOND_PLAYER)) return CellStatus.SECOND_PLAYER; int count = 0; for (int i = 0; i < GRID_SIZE; ++i) { for (int j = 0; j < GRID_SIZE; ++j) { if (mGameState[i][j].getPlayer() != CellStatus.NO_PLAYER) ++count; } } if (count == 9) return CellStatus.DRAW; return CellStatus.NO_PLAYER; } private boolean checkPlayerWon(int player) { boolean winDiag1 = true, winDiag2 = true; for (int i = 0; i < GRID_SIZE; ++i) { winDiag1 = winDiag1 && mGameState[i][i].getPlayer() == player; winDiag2 = winDiag2 && mGameState[i][2 - i].getPlayer() == player; boolean winRow = true, winCol = true; for (int j = 0; j < GRID_SIZE; ++j) { winRow = winRow && mGameState[i][j].getPlayer() == player; winCol = winCol && mGameState[j][i].getPlayer() == player; } if (winRow || winCol) return true; } if (winDiag1 || winDiag2) return true; return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGameState = new CellStatus[GRID_SIZE][GRID_SIZE]; mButtons = new ImageButton[GRID_SIZE][GRID_SIZE]; mResetButton = findViewById(R.id.new_game_button); mMessageText = findViewById(R.id.top_text); for (int i = 0; i < GRID_SIZE; ++i) { for (int j = 0; j < GRID_SIZE; ++j) { String buttonId = "cell_" + i + j; int resID = getResources().getIdentifier(buttonId, "id", getPackageName()); mButtons[i][j] = findViewById(resID); final int row = i, col = j; mButtons[i][j].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mGameState[row][col].getPlayer() == CellStatus.NO_PLAYER) { mGameState[row][col].setPlayer(mCurrentPlayer); if (mCurrentPlayer == CellStatus.FIRST_PLAYER) { mButtons[row][col].setImageResource(R.drawable.nought); } else { mButtons[row][col].setImageResource(R.drawable.cross); } mCurrentPlayer = mCurrentPlayer == CellStatus.FIRST_PLAYER ? CellStatus.SECOND_PLAYER : CellStatus.FIRST_PLAYER; int winner = checkGameWin(); if (winner == CellStatus.FIRST_PLAYER) mMessageText.setText("Winner is First Player!"); else if (winner == CellStatus.SECOND_PLAYER) mMessageText.setText("Winner is Second Player!"); else if (winner == CellStatus.DRAW) mMessageText.setText("Match is draw!"); } } }); } } mResetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { resetGameState(); } }); resetGameState(); } }
true
b27bb3f97b838a6527a3992a577a3a08075f06f1
Java
firmanjabar/MovieCatalogueLocalStorage
/app/src/main/java/com/firmanjabar/submission4/data/api/RequestInterface.java
UTF-8
2,338
2.21875
2
[]
no_license
package com.firmanjabar.submission4.data.api; import com.firmanjabar.submission4.data.model.MovieDetail; import com.firmanjabar.submission4.data.model.MovieResponse; import com.firmanjabar.submission4.data.model.ReviewResponse; import com.firmanjabar.submission4.data.model.TvDetail; import com.firmanjabar.submission4.data.model.TvResponse; import com.firmanjabar.submission4.data.model.VideoResponse; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface RequestInterface { @GET("movie/popular") Observable<MovieResponse> getMovie ( @Query("api_key") String api_key, @Query("language") String language ); @GET("tv/popular") Observable<TvResponse> getTv ( @Query("api_key") String api_key, @Query("language") String language ); @GET("movie/{movie_id}") Observable<MovieDetail> getMovieDetail ( @Path("movie_id") String movie_id, @Query("api_key") String api_key ); @GET("movie/{movie_id}/videos") Observable<VideoResponse> getMovieVideos ( @Path("movie_id") String movie_id, @Query("api_key") String api_key ); @GET("movie/{movie_id}/reviews") Observable<ReviewResponse> getMovieReviews ( @Path("movie_id") String movie_id, @Query("api_key") String api_key ); @GET("search/movie") Observable<MovieResponse> searchMovie( @Query("api_key") String api_key, @Query("language") String language, @Query("query") String query ); @GET("tv/{tv_id}") Observable<TvDetail> getTvDetail ( @Path("tv_id") String tv_id, @Query("api_key") String api_key ); @GET("tv/{tv_id}/videos") Observable<VideoResponse> getTvVideos ( @Path("tv_id") String tv_id, @Query("api_key") String api_key ); @GET("tv/{tv_id}/reviews") Observable<ReviewResponse> getTvReviews ( @Path("tv_id") String tv_id, @Query("api_key") String api_key ); @GET("search/tv") Observable<TvResponse> searchTv( @Query("api_key") String api_key, @Query("language") String language, @Query("query") String query ); }
true
74b2adabd1f76697e950c478db61bd5f2b543b4b
Java
rayho564/TRexAlarm
/TRexAlarmAndroid/app/src/main/java/com/trexalarm/horay/trexalarm/MainActivity.java
UTF-8
23,114
2.078125
2
[]
no_license
package com.trexalarm.horay.trexalarm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.UUID; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.text.InputType; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { Button btnOn, btnOff, rename, changePin, clearLog; TextView txtArduino, txtString, txtStringLength, received, status, nameFromDevice, log; Handler bluetoothIn; final int handlerState = 0; //used to identify handler message private BluetoothAdapter btAdapter = null; //private BluetoothSocket btSocket = null; ArrayList<String> addresses = new ArrayList<>(); ArrayList<BluetoothSocket> btSockets = new ArrayList<>(); //private ConnectedThread mConnectedThread; private ArrayList<ConnectedThread> connectedThreadList = new ArrayList<>(); private ArrayList<String> befEndLineList = new ArrayList<>(); // SPP UUID service - this should work for most devices UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //TODO::Change to array of MAC addresses // String for MAC address private static String pin, pinConfirm; String logStr = ""; //private static String address; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Link the buttons and textViews to respective views btnOn = (Button) findViewById(R.id.buttonOn); btnOff = (Button) findViewById(R.id.buttonOff); rename = (Button) findViewById(R.id.rename); changePin = (Button) findViewById(R.id.changePin); clearLog = (Button) findViewById(R.id.clearLog); nameFromDevice = (TextView) findViewById(R.id.nameFromDevice); txtString = (TextView) findViewById(R.id.txtString); txtStringLength = (TextView) findViewById(R.id.testView1); status = (TextView) findViewById(R.id.status); nameFromDevice = (TextView) findViewById(R.id.nameFromDevice); received = (TextView) findViewById(R.id.received); log = (TextView) findViewById(R.id.log); bluetoothIn = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == handlerState) { String readMessage = (String) msg.obj; //will keep combining the chars until end-of-line int threadNum = Integer.valueOf(readMessage.substring(0, 1)); readMessage = readMessage.substring(1, readMessage.length()); if( befEndLineList.size() < threadNum + 1){ befEndLineList.add(readMessage); } else { befEndLineList.set(threadNum, befEndLineList.get(threadNum) + readMessage); } // determine the end-of-line for (int i = 0; i < befEndLineList.size(); i++) { String befEndLine = befEndLineList.get(i); int endOfLineIndex = befEndLine.indexOf("\n"); int endOfCommand = befEndLine.indexOf("\r"); if (endOfLineIndex != -1) { //check if character is there if not skip String dataInPrint = befEndLine.substring(0, endOfLineIndex); // extract string String str, curStr; Toast.makeText(getBaseContext(), dataInPrint, Toast.LENGTH_LONG).show(); received.setText(dataInPrint); if (endOfCommand != -1) { if (endOfCommand >= 10) { str = dataInPrint.substring(0, 10); if (str.equals("disconnect")) { connectedThreadList.get(i).interrupt(); try { btSockets.get(i).close(); } catch (IOException e) { e.printStackTrace(); } } } } if (endOfLineIndex >= 6) { str = dataInPrint.substring(0, 6); if (str.equals("status")) { curStr = dataInPrint.substring(6, endOfLineIndex); status.setText(curStr); } } /*if(endOfLineIndex >= 4 ){ str = dataInPrint.substring(0, 4); if(str.equals("name")){ curStr = dataInPrint.substring(4, endOfLineIndex); nameFromDevice.setText(curStr); } }*/ if (dataInPrint.equals("Alarm")) { Intent buzz = new Intent(MainActivity.this, backgroundService.class); MainActivity.this.startService(buzz); //String name = btAdapter.getName(); String name = getBluetoothName(btSockets.get(i)); Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show(); nameFromDevice.setText(name); } logStr += befEndLine + "\n"; //Clear the data held in string befEndLineList.set(i, ""); } } } } }; btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter checkBTState(); btnOff.setOnClickListener(new OnClickListener() { public void onClick(View v) { //writeAll(connectedThreadList, "0"); connectedThreadList.get(1).write("1"); //Toast.makeText(getBaseContext(), "Turn off sensor", Toast.LENGTH_SHORT).show(); //String name = btAdapter.getName(); //String name = getBluetoothName(btSocket); //Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show(); //nameFromDevice.setText(name); } }); btnOn.setOnClickListener(new OnClickListener() { public void onClick(View v) { //writeAll(connectedThreadList, "1"); connectedThreadList.get(0).write("1"); //mConnectedThread.write("1"); // Send "1" via Bluetooth Toast.makeText(getBaseContext(), "Turn on sensors", Toast.LENGTH_SHORT).show(); } }); rename.setOnClickListener(new OnClickListener() { public void onClick(View v) { final AlertDialog builder = new AlertDialog.Builder(MainActivity.this) .setView(v) .setTitle("Please enter a new name. Warning: The sensor will disconnect.'\\n' Please reconnect after 2 seconds.") .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick .setNegativeButton(android.R.string.cancel, null) .create(); builder.setContentView(R.layout.dialog_rename); //Check this // Set up the input final EditText input = new EditText(MainActivity.this); final EditText btName = (EditText) findViewById(R.id.btName); builder.setView(input); builder.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String btNewNameStr = input.getText().toString(); String btNameStr = btName.getText().toString(); if(btNewNameStr.length() <= 0){ Toast.makeText(getBaseContext(), "Please enter a new name", Toast.LENGTH_LONG).show(); } if(btNameStr.length() <= 0){ Toast.makeText(getBaseContext(), "Please enter a name", Toast.LENGTH_LONG).show(); } else{ connectedThreadList.get(Integer.valueOf(btNameStr)).write("4"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } connectedThreadList.get(Integer.valueOf(btNameStr)).write(btNewNameStr); connectedThreadList.get(Integer.valueOf(btNameStr)).write("\n"); dialog.dismiss(); } //Dismiss once everything is OK. } }); Button button2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Dismiss once everything is OK. dialog.dismiss(); } }); } }); builder.show(); } }); changePin.setOnClickListener(new OnClickListener() { public void onClick(View v) { //TODO::Change the layout of this AlertDialog builder /*final AlertDialog builder = new AlertDialog.Builder(MainActivity.this) .setView(v) .setTitle("Please enter a new Pin. Warning: The sensor will disconnect.'\\n' Please reconnect after 2 seconds.") .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick .setNegativeButton(android.R.string.cancel, null) .create(); // Set up the input final EditText input = new EditText(MainActivity.this); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); builder.setView(input); final TextView retype = new TextView(MainActivity.this); retype.setText("Please retype the pin"); builder.setView(retype); final EditText input2 = new EditText(MainActivity.this); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); builder.setView(input2); builder.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pin = input.getText().toString(); pinConfirm = input2.getText().toString(); if(pin.length() <= 0){ Toast.makeText(getBaseContext(), "Please enter a pin", Toast.LENGTH_LONG).show(); } else if(!pin.equals(pinConfirm)){ Toast.makeText(getBaseContext(), "Pin do not match", Toast.LENGTH_LONG).show(); } else{ mConnectedThread.write("5"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } mConnectedThread.write(pin); mConnectedThread.write("\n"); dialog.dismiss(); } //Dismiss once everything is OK. } }); Button button2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Dismiss once everything is OK. dialog.dismiss(); } }); } }); builder.show();*/ } }); clearLog.setOnClickListener(new OnClickListener() { public void onClick(View v) { logStr = ""; } }); } private BluetoothSocket createBluetoothSocket(BluetoothDevice device, int i, ArrayList<String> addresses) throws IOException { //String temp = "00001101-0000-1000-8000-" + addresses.get(i).replace(":", ""); //BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-" + addresses.get(i).replace(":", "")); BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Toast.makeText(getBaseContext(), temp, Toast.LENGTH_LONG).show(); //Toast.makeText(getBaseContext(), /*device.getName() + */device.getUuids()[0].getUuid().toString(), Toast.LENGTH_LONG).show(); return device.createRfcommSocketToServiceRecord(BTMODULEUUID); //creates secure outgoing connection with BT device using UUID } @Override public void onResume() { super.onResume(); //Get MAC address from DeviceListActivity via intent Intent intent = getIntent(); //Get the MAC address from the DeviceListActivity via EXTRA addresses = (ArrayList<String>)intent.getSerializableExtra("addressList"); //create device and set the MAC address createDeviceandSetMac(addresses); } //we want to leave btSockets open when leaving activity because of background checks. @Override public void onPause() { super.onPause(); //Don't leave Bluetooth sockets open when leaving activity disconnectAll(btSockets); } @Override public void onDestroy() { super.onDestroy(); disconnectAll(btSockets); Intent intent = new Intent(MainActivity.this, backgroundService.class); MainActivity.this.stopService(intent); } //Checks that the Android device Bluetooth is available and prompts to be turned on if off private void checkBTState() { if(btAdapter==null) { Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show(); } else { if (btAdapter.isEnabled()) { } else { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } } } //create new class for connect thread private class ConnectedThread extends Thread { private InputStream mmInStream = null; private OutputStream mmOutStream = null; private InputStream mmInStream1 = null; private OutputStream mmOutStream1 = null; private int threadNum; //creation of the connect thread public ConnectedThread(BluetoothSocket socket, int threadNum) { InputStream tmpIn = null; OutputStream tmpOut = null; this.threadNum = threadNum; try { //Create I/O streams for connection tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } if(threadNum == 0) { mmInStream = tmpIn; mmOutStream = tmpOut; } else if(threadNum == 1){ mmInStream1 = tmpIn; mmOutStream1 = tmpOut; } } public void run() { byte[] buffer = new byte[512]; int bytes; // Keep looping to listen for received messages while (true) { try { if(threadNum == 0){ bytes = mmInStream.available(); while( bytes> 0 ){ bytes = mmInStream.read(buffer); //read bytes from input buffer String readMessage = new String(buffer, 0, bytes); String readWithThreadNum = Integer.toString(threadNum) + readMessage; // Send the obtained bytes to the UI Activity via handler bluetoothIn.obtainMessage(handlerState, bytes, -1, readWithThreadNum).sendToTarget(); } } else{ bytes = mmInStream1.available(); while( bytes> 0 ){ bytes = mmInStream1.read(buffer); //read bytes from input buffer String readMessage = new String(buffer, 0, bytes); String readWithThreadNum = Integer.toString(threadNum) + readMessage; // Send the obtained bytes to the UI Activity via handler bluetoothIn.obtainMessage(handlerState, bytes, -1, readWithThreadNum).sendToTarget(); } } } catch (IOException e) { break; } } } //write method public void write(String input) { byte[] msgBuffer = input.getBytes(); //converts entered String into bytes if( threadNum == 0 ){ try { mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream } catch (IOException e) { Toast.makeText(getBaseContext(), "Failed to connect", Toast.LENGTH_LONG).show(); //if you cannot write, close the application finish(); } } else{ try { mmOutStream1.write(msgBuffer); //write bytes over BT connection via outstream } catch (IOException e) { Toast.makeText(getBaseContext(), "Failed to connect", Toast.LENGTH_LONG).show(); //if you cannot write, close the application finish(); } } } } public String getBluetoothName(BluetoothSocket btSocket){ BluetoothDevice connectedDevice = btSocket.getRemoteDevice(); String name = connectedDevice.getName(); if(name == null){ Toast.makeText(getBaseContext(), "Name is NULL!", Toast.LENGTH_LONG).show(); name = connectedDevice.getAddress(); } return name; } public void createDeviceandSetMac(ArrayList<String> addresses){ btSockets.clear(); for( int i = 0; i < addresses.size(); i++) { String address = addresses.get(i); BluetoothDevice device = btAdapter.getRemoteDevice(address); try { btSockets.add(createBluetoothSocket(device, i, addresses)); } catch (IOException e) { Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show(); } // Establish the Bluetooth socket connection. //Toast.makeText(getBaseContext(), Integer.valueOf(btSockets.size()), Toast.LENGTH_LONG).show(); connectAll(btSockets); } } public void connectAll(ArrayList<BluetoothSocket> btSockets){ connectedThreadList.clear(); for(int i = 0; i < btSockets.size(); i++){ try { btSockets.get(i).connect(); } catch (IOException e) { try { btSockets.get(i).close(); } catch (IOException e2) { //insert code to deal with this } } connectedThreadList.add(new ConnectedThread(btSockets.get(i), i)); connectedThreadList.get(i).start(); //I send a character when resuming.beginning transmission to check device is connected //If it is not an exception will be thrown in the write method and finish() will be called //connectedThreadList.get(i).write("x"); } } public void disconnectAll(ArrayList<BluetoothSocket> btSockets){ for(int i = 0; i < btSockets.size(); i++){ try { btSockets.get(i).close(); } catch (IOException e2) { //insert code to deal with this } } } public void writeAll(ArrayList<ConnectedThread> connectedThreadList, String msg){ for(int i = 0; i < connectedThreadList.size(); i++){ connectedThreadList.get(i).write(msg); } } }
true
ecdeca8c279b6ffe905dd867f0773f5d762dd1ba
Java
jufegare000/CesetBackend
/Ceset/src/main/java/co/edu/udea/ceset/dao/UsuarioDAO.java
UTF-8
2,489
2.4375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.udea.ceset.dao; import co.edu.udea.ceset.dto.Person; import co.edu.udea.ceset.dto.Rol; import co.edu.udea.ceset.dto.User; import co.edu.udea.ceset.dto.Usuario; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; /** * * @author edevargas */ public class UsuarioDAO implements Serializable { /** * Método que retorna un usuario por defecto dado cualquier id * * @return Usuario */ public User obtenerPorId(int id) { User usuario = new User(); Person prsn = new Person(); prsn.setCompleteName("Satanas"); prsn.setDocument("66666"); prsn.setIdPerson(2); //Datos Dummies usuario.setDateCreation(null); usuario.setIdUser(2); usuario.setPassword("6699"); usuario.setStates("YormanJa"); Rol rolAdmin = new Rol(); rolAdmin.setEstado("ACT"); rolAdmin.setFechaCreacion(new Date()); rolAdmin.setId(1); rolAdmin.setNombre("ADMINISTRADOR"); ArrayList<Rol> listaRoles = new ArrayList<Rol>(); listaRoles.add(rolAdmin); // usuario.setRoles(listaRoles); return usuario; } /** * Método que retorna un usuario por defecto dado cualquier nombre de * usuario y clave * * @return Usuario */ public User autenticar(String nombreUsuario, String clave) { User usuario = new User(); /*usuario.setEstado("ACT"); usuario.setFechaCreacion(new Date()); usuario.setId(1); usuario.setIdentificacion("111111"); usuario.setNombreCompleto("Jhon Doe"); usuario.setNombreUsuario(nombreUsuario); Rol rolAdmin = new Rol(); rolAdmin.setEstado("ACT"); rolAdmin.setFechaCreacion(new Date()); rolAdmin.setId(1); rolAdmin.setNombre("ADMINISTRADOR"); Rol rolUsuario = new Rol(); rolUsuario.setEstado("ACT"); rolUsuario.setFechaCreacion(new Date()); rolUsuario.setId(1); rolUsuario.setNombre("USUARIO"); ArrayList<Rol> listaRoles = new ArrayList<Rol>(); listaRoles.add(rolAdmin); listaRoles.add(rolUsuario); usuario.setRoles(listaRoles); */ return usuario; } }
true
355bfd6dc9340c408ee855a540bf83e15184bd65
Java
xeonye/v2
/.svn/pristine/55/55f89578a0f0da43fc99a057d3a1936ca8d93739.svn-base
UTF-8
890
1.71875
2
[]
no_license
package com.zllh.mall.common.dao; import java.util.List; import java.util.Map; import com.zllh.mall.common.model.MtSettle; public interface MtSettleMapper { int deleteByPrimaryKey(String id); int insert(MtSettle record); int insertSelective(MtSettle record); MtSettle selectByPrimaryKey(String id); List<MtSettle> searchPendingSettle(Map<String,Object> map); List<MtSettle> searchPendingSettleForApp(Map<String,Object> map); List<MtSettle> searchMyPendingSettle(Map<String,Object> map); List<MtSettle> searchSettleManage(Map<String,Object> map); List<MtSettle> searchSettleSignature(Map<String,Object> map); List<MtSettle> searchSettleRegist(Map<String,Object> map); int updateByPrimaryKeySelective(MtSettle record); int updateByPrimaryKey(MtSettle record); MtSettle findSettleByCode(String settleCode); }
true
2cf18afc6530d05d346ba651c03706cc96c772cb
Java
Eduflex-Student-Management-System/eduflex-backend
/src/main/java/com/eduflex/eduflexbackend/service/StudentService.java
UTF-8
603
2.296875
2
[]
no_license
package com.eduflex.eduflexbackend.service; import com.eduflex.eduflexbackend.model.Student; import java.util.List; public interface StudentService { Student addStudent(Student student); Student updateStudent(Student student); List<Student> getAllStudents(); void deleteStudent(int studentId); Student getStudentById(int studentId); List<Student> getAllStudentsByClassYearId(int classYearId); Student addClassYearToStudent(int studentId, int classYearId); Student getStudentByStudentUsernameAndStudentPassword(String studentUsername, String studentPassword); }
true
9d519518199aa1fa09d475e9bc15b585bb7e3866
Java
suruomo/Material-library
/src/main/java/com/suruomo/material/MaterialApplication.java
UTF-8
593
1.679688
2
[]
no_license
package com.suruomo.material; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; /** * @author 苏若墨 */ @SpringBootApplication @MapperScan("com.suruomo.material.dao") public class MaterialApplication{ public static void main(String[] args) { SpringApplication.run(MaterialApplication.class, args); } }
true
5757d5a658b99172f2e5bd944832acd8cff7400b
Java
Vinicius-Lima31/Java
/Java/15 - Função(Métodos)/15-TesteFuncao01/src/curso15testefuncao01/Curso15TesteFuncao01.java
UTF-8
635
3.78125
4
[ "MIT" ]
permissive
package curso15testefuncao01; public class Curso15TesteFuncao01 { //void soma (int a, int b) --> Não vai funcionar... MINUTO 9:00 static void soma (int a, int b) { int s = a + b; System.out.println("A Soma é: " + s); } static int soma1 (int a, int b) { int s = a + b; return s; } public static void main(String[] args) { System.out.println("Começou o Programa"); soma(6, 4); System.out.println("\nComeçou o Programa"); int sm2 = soma1(5, 2); System.out.println("A soma é: " + sm2); } }
true
5035f525c3729b81ad1cb0844be90b9dd4c8e72e
Java
mnementh64/neuralnetwork
/src/main/java/net/mnementh64/neural/model/activation/ActivationUtils.java
UTF-8
378
1.703125
2
[ "MIT" ]
permissive
package net.mnementh64.neural.model.activation; public class ActivationUtils { public static final ActivationFunction identity = new IdentityFunction(); public static final ActivationFunction sigmoid = new SigmoideFunction(); public static final ActivationFunction tanh = new TanhFunction(); public static final ActivationFunction relu = new ReLuFunction(); }
true
b1604d0ea5aa4823c8aa3b34581f74752b361c99
Java
DuminduA/spring-redis
/spring-redis-messaging/src/main/java/com/rabbit/samples/springredismessaging/services/impl/MessagePublisherServiceImpl.java
UTF-8
1,023
2.296875
2
[ "Apache-2.0" ]
permissive
package com.rabbit.samples.springredismessaging.services.impl; import com.rabbit.samples.springredismessaging.services.MessagePublisherService; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.experimental.FieldDefaults; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.stereotype.Service; /** * @author Matteo Baiguini * [email protected] * 07 Feb 2019 */ @Slf4j @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) @AllArgsConstructor @Getter(value = AccessLevel.PROTECTED) @Service public class MessagePublisherServiceImpl implements MessagePublisherService { RedisTemplate<String, Object> redisTemplate; ChannelTopic channelTopic; @Override public void publish(final String message) { log.info("Sending message: {}", message); getRedisTemplate() .convertAndSend( getChannelTopic().getTopic(), message ); } }
true
d06846e0c8b1d3122741d53e1b94f315a46d2f0c
Java
bculkin2442/dice-lang
/dice/src/main/java/bjc/dicelang/dice/ListDiceExpression.java
UTF-8
1,191
3.328125
3
[]
no_license
package bjc.dicelang.dice; import java.util.Arrays; /** * Represents a list dice expression. * * @author student * */ public class ListDiceExpression implements DiceExpression { /** The list value in this expression, if there is one. */ public DieList list; /** * Create a list die expression. * * @param lst * The list value of this expression. */ public ListDiceExpression(final DieList lst) { list = lst; } @Override public String value() { return Arrays.toString(list.roll()); } @Override public boolean isList() { return true; } @Override public String toString() { return list.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((list == null) ? 0 : list.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ListDiceExpression other = (ListDiceExpression) obj; if (list == null) { if (other.list != null) return false; } else if (!list.equals(other.list)) return false; return true; } }
true
d0471711df8428e2f4578df79b6ca126fad54c35
Java
Nepisat/Equivalent-Exchange-2-Reloaded
/src/main/buildcraft/silicon/BlockLaser.java
UTF-8
2,360
2.203125
2
[]
no_license
/** * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com * * BuildCraft is distributed under the terms of the Minecraft Mod Public License * 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package buildcraft.silicon; import buildcraft.core.CreativeTabBuildCraft; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.util.ArrayList; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; public class BlockLaser extends BlockContainer { @SideOnly(Side.CLIENT) private Icon textureTop, textureBottom, textureSide; public BlockLaser(int i) { super(i, Material.iron); setHardness(10F); setCreativeTab(CreativeTabBuildCraft.MACHINES.get()); } @Override public int getRenderType() { return SiliconProxy.laserBlockModel; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } public boolean isACube() { return false; } @Override public TileEntity createNewTileEntity(World world) { return new TileLaser(); } @Override public Icon getIcon(int i, int j) { if (i == ForgeDirection.values()[j].getOpposite().ordinal()) return textureBottom; else if (i == j) return textureTop; else return textureSide; } @Override public int onBlockPlaced(World world, int x, int y, int z, int side, float par6, float par7, float par8, int meta) { super.onBlockPlaced(world, x, y, z, side, par6, par7, par8, meta); if (side <= 6) { meta = side; } return meta; } @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void addCreativeItems(ArrayList itemList) { itemList.add(new ItemStack(this)); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister par1IconRegister) { textureTop = par1IconRegister.registerIcon("buildcraft:laser_top"); textureBottom = par1IconRegister.registerIcon("buildcraft:laser_bottom"); textureSide = par1IconRegister.registerIcon("buildcraft:laser_side"); } }
true
7e6937721b24c28464d797fbab1f6c34bfaca66d
Java
izgarshev/spring5
/src/main/java/com/pablo/services/MessageRendererImpl.java
UTF-8
1,359
2.265625
2
[]
no_license
package com.pablo.services; import com.pablo.interfaces.MessageProvider; import com.pablo.interfaces.MessageRenderer; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Component public class MessageRendererImpl implements MessageRenderer, ApplicationContextAware { MessageProvider messageProvider; @Autowired public void setMessageProvider(MessageProvider messageProvider) { this.messageProvider = messageProvider; } public void render() { System.out.println("init method"); System.out.println(messageProvider.getName()); } @PostConstruct public void postConstruct() { System.out.println("post construct"); } @PreDestroy public void preDestroy() { System.out.println("pre destroy"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ((AbstractApplicationContext) applicationContext).registerShutdownHook(); } }
true
3c07f91b77691e04ce72c2d59b2fa5039be72b4a
Java
lynnlee1229/glink
/glink-benchmark/src/main/java/com/github/tm/glink/benchmark/tdrive/GridVsDistanceBenchmark.java
UTF-8
1,966
2.5
2
[]
no_license
package com.github.tm.glink.benchmark.tdrive; import com.github.tm.glink.core.util.GeoUtils; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.*; import java.util.concurrent.TimeUnit; public class GridVsDistanceBenchmark { @State(Scope.Thread) public static class BenchmarkState { private int count = 1000000; private Set<Long> set = new HashSet<>(count); private List<Point> points = new ArrayList<>(10000); @Setup public void setUp() { Random random = new Random(); GeometryFactory factory = new GeometryFactory(); for (int i = 0; i < 1000001; ++i) { Point p = factory.createPoint(new Coordinate(random.nextDouble() * 180, random.nextDouble() * 90)); points.add(p); } } } @Benchmark @BenchmarkMode(Mode.AverageTime) public void gridBenchmark(BenchmarkState state) { List<Long> result = new ArrayList<>(); for (long i = 0; i < 1000000; ++i) { if (state.set.contains(i)) { result.add(i); } } } @Benchmark @BenchmarkMode(Mode.AverageTime) public void distanceBenchmark(BenchmarkState state) { for (int i = 1, len = state.points.size(); i < len; ++i) { double dis = GeoUtils.calcDistance(state.points.get(0), state.points.get(i)); } } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(GridVsDistanceBenchmark.class.getSimpleName()) .warmupIterations(1) .measurementIterations(1) .forks(1) .timeUnit(TimeUnit.MILLISECONDS) .build(); new Runner(opt).run(); } }
true
19af41190fbcc6a85f0f0b36191308e4a7853f58
Java
krivasmile/Map
/src/main/java/ua/kyiv/mapapp/service/LocationService.java
UTF-8
799
2.390625
2
[]
no_license
package ua.kyiv.mapapp.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ua.kyiv.mapapp.model.Location; import ua.kyiv.mapapp.repo.LocationRepository; import java.util.List; @Service public class LocationService { private LocationRepository locationRepository; @Autowired public LocationService(LocationRepository locationRepository) { this.locationRepository = locationRepository; } public void save(Location location){ locationRepository.save(location); } public List<Location> showAllLocations(){ List<Location> locations = locationRepository.findAll(); locations.sort((l1, l2) -> l1.getCity().compareTo(l2.getCity())); return locations; } }
true
f8711b2014fdb427cb551c8a66f09497573bea12
Java
Lithaos/Java-practice
/kurs/src/main/java/com/study/kurs/services/KnightService.java
UTF-8
2,783
2.5
2
[]
no_license
package com.study.kurs.services; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.study.kurs.domain.Knight; import com.study.kurs.domain.PlayerInformation; import com.study.kurs.domain.repository.KnightRepository; import com.study.kurs.domain.repository.PlayerInformationRepository; import com.study.kurs.domain.repository.QuestRepository; @Component public class KnightService { @Autowired KnightRepository knightRepository; @Autowired QuestRepository questRepository; @Autowired PlayerInformationRepository playerInformation; public List<Knight> getAllKnights() { return new ArrayList<>(knightRepository.getAllKnights()); } public void saveKnight(Knight knight) { knightRepository.createKnight(knight); } public Knight getKnight(Integer id) { return knightRepository.getKnightById(id); } public void deleteKnight(Integer id) { knightRepository.deleteKnight(id); } public void updateKnight(Knight knight) { knightRepository.updateKnight(knight.getId(), knight); } public int collectRewards() { Predicate<Knight> knightPredicate = knight -> { if (knight.getQuest() != null) { return knight.getQuest().isComplited(); } else { return false; } }; int sum = knightRepository.getAllKnights().stream().filter(knightPredicate) .mapToInt(knight -> knight.getQuest().getReward()).sum(); knightRepository.getAllKnights().stream().filter(knightPredicate).forEach(knight -> { knight.setQuest(null); }); return sum; } public void checkExperience() { knightRepository.getAllKnights().stream().forEach(knight -> { System.out.println(knight.getExperience()); if (knight.getQuest() != null) { if (knight.getQuest().isComplited()) { knight.setExperience(knight.getExperience() + knight.getQuest().getExperience()); int knightExp = knight.getExperience(); if (knightExp >= 100) { knight.setLevel(knight.getLevel() + knightExp / 100); knight.setExperience(knightExp % 100); } } } }); } @Transactional public void getMyGold() { List<Knight> allKnights = getAllKnights(); allKnights.forEach(knight -> { if (knight.getQuest() != null) { boolean completed = knight.getQuest().isComplited(); if (completed) { questRepository.update(knight.getQuest()); } } }); PlayerInformation first = playerInformation.getFirst(); int currentGold = first.getGold(); checkExperience(); first.setGold(currentGold + collectRewards()); } }
true
4090488503e83b4f0ccaec6e53ae92e304dc8845
Java
Soura2605/AssignmentTests
/src/main/java/pageFactory/TripAdvisorSearchListingPage.java
UTF-8
1,321
2.28125
2
[]
no_license
package pageFactory; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import helper.WebElementHelper; import locators.FlipkartLocators; import locators.TripAdvisorLocators; import util.WindowStack; public class TripAdvisorSearchListingPage { public WebDriver driver; WebElementHelper webElementHelper; WindowStack winStack; public TripAdvisorSearchListingPage(WebDriver driver) { this.driver=driver; this.webElementHelper=new WebElementHelper(driver); this.winStack=new WindowStack(driver); } //---------------Setters----------------- public TripAdvisorSearchDescriptionPage clickOnTheMatchingProductResult(String Choice) { webElementHelper.clickElement(driver, getAllSearchResultsInGRID().get((Integer.parseInt(Choice))-1));; winStack.windowSwitch(driver, 1); return new TripAdvisorSearchDescriptionPage(driver); } //---------------Getters----------------- public List<WebElement> getAllSearchResultsInGRID() { try { return driver.findElements(By.xpath(TripAdvisorLocators.SearchResultPage.SEARCHRESULTS)); }catch(Exception e) { Assert.fail("Unable to fetch all the results"); e.printStackTrace(); return (List<WebElement>) e; } } }
true
a45669aebb70f3a3622ab848b1749adadade59ca
Java
jinshoogun/jin
/M103/src/DateFormatExample5/DateFormatExample6.java
WINDOWS-1252
790
3.21875
3
[]
no_license
package DateFormatExample5; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.TimeZone; public class DateFormatExample6 { public static void main(String args[]) { GregorianCalendar calendar = new GregorianCalendar(); printDateTime(calendar, " ", "America/New_York"); printDateTime(calendar, "ȫ ", "Asia/Hong_Kong"); printDateTime(calendar, "ĸ ", "Europe/Paris"); } static void printDateTime(GregorianCalendar calendar, String location, String timeZone) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd (E) aa hh:mm"); dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); String str = dateFormat.format(calendar.getTime()); System.out.println(location + str); } }
true
341fb7e39653e8a30dea6af0eb520b04f5ac098b
Java
evilpegasus/APCS
/Chapter2/src/labs/StringManips.java
UTF-8
911
3.5625
4
[]
no_license
package labs; import java.util.Scanner; public class StringManips { public static void main (String[] args) { String phrase = new String ("This is a String test."); String middle3 = phrase.substring(phrase.length()/2-1, phrase.length()/2+2); System.out.println(phrase); System.out.println(middle3); String firstHalf = phrase.substring(0, phrase.length()/2); String secondHalf = phrase.substring(phrase.length()/2, phrase.length()); String switchedPhrase = secondHalf.concat(firstHalf); switchedPhrase = switchedPhrase.replace(" ", "*"); System.out.println(switchedPhrase); Scanner scan = new Scanner(System.in); System.out.print("State: "); String state = scan.nextLine(); System.out.println(); System.out.print("City: "); String city = scan.nextLine(); System.out.println(); System.out.println(state.toUpperCase() + city.toLowerCase() + state.toUpperCase()); } }
true
2526954f7361a143c8cc84052400221fa0177a00
Java
SergeyPasko/MateAcademy
/src/main/java/lesson00/MainPrimitivesSize.java
UTF-8
974
3.28125
3
[]
no_license
package lesson00; /** * @author spasko */ public class MainPrimitivesSize { public static void main(String[] args) { int intNumber = 127; byte byteNumber = (byte) intNumber; int addNumber=13; System.out.println("Before integer " + Integer.toBinaryString(intNumber)); System.out.println("Before byte " + byteToBinaryString(byteNumber)); intNumber += addNumber; byteNumber += addNumber; System.out.println("after integer " + Integer.toBinaryString(intNumber)); System.out.println("after byte " + byteToBinaryString(byteNumber)); System.out.println("Result integer "+intNumber); System.out.println("Result byte "+byteNumber); //System.out.println(((Object)(5/2)).getClass().getName()); //int number=6; //System.out.println(new Integer(number)==(Integer)number); } static String byteToBinaryString(byte b) { return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'); } }
true
9936a6ff6d10c7005a0c8bf5d6a8633f7e830d1b
Java
jtransc/jtransc-examples
/stress/src/main/java/com/stress/sub0/sub8/sub0/Class2300.java
UTF-8
394
2.15625
2
[]
no_license
package com.stress.sub0.sub8.sub0; import com.jtransc.annotation.JTranscKeep; @JTranscKeep public class Class2300 { public static final String static_const_2300_0 = "Hi, my num is 2300 0"; static int static_field_2300_0; int member_2300_0; public void method2300() { System.out.println(static_const_2300_0); } public void method2300_1(int p0, String p1) { System.out.println(p1); } }
true
1310b8e29c66b7b225f7d719a2db5966d53b297b
Java
StefanHagel/citeproc-java
/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/CSLToolContext.java
UTF-8
2,392
2.359375
2
[ "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-only", "GPL-2.0-only", "Apache-2.0", "CPAL-1.0" ]
permissive
// Copyright 2013 Michel Kraemer // // 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 de.undercouch.citeproc.tool; import java.io.File; import de.undercouch.citeproc.BibliographyFileReader; import de.undercouch.citeproc.helper.tool.CachingBibliographyFileReader; /** * A context containing information used during execution of * the {@link de.undercouch.citeproc.CSLTool} * @author Michel Kraemer */ public class CSLToolContext { private static ThreadLocal<CSLToolContext> current = new ThreadLocal<>(); private String toolName; private File configDir; private BibliographyFileReader bibReader = new CachingBibliographyFileReader(); private CSLToolContext() { //hidden constructor } /** * Enters a new context * @return the new context */ public static CSLToolContext enter() { CSLToolContext ctx = new CSLToolContext(); current.set(ctx); return ctx; } /** * Leaves the current context */ public static void exit() { current.remove(); } /** * @return the current context */ public static CSLToolContext current() { return current.get(); } /** * Sets the tool's name * @param toolName the name */ public void setToolName(String toolName) { this.toolName = toolName; } /** * @return the tool's name */ public String getToolName() { return toolName; } /** * Sets the tool's configuration directory * @param configDir the directory */ public void setConfigDir(File configDir) { this.configDir = configDir; } /** * @return the tool's configuration directory */ protected File getConfigDir() { return configDir; } /** * Returns a common reader for bibliography files. Use this method * instead of creating a new {@link BibliographyFileReader} instance * to enable caching. * @return the reader */ public BibliographyFileReader getBibliographyFileReader() { return bibReader; } }
true
23d767599014ea56073567a4121a3c1ec750078c
Java
kunal7384/Practice-Selenium-
/CucumberLearn/src/test/java/stepdefination/LogOutTest.java
UTF-8
997
2.140625
2
[]
no_license
package stepdefination; import org.openqa.selenium.WebDriver; import cucumber.TestContext; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import manager.PageObjectManager; import pages.LogOut; import pages.SearchStudentPage; public class LogOutTest { WebDriver driver; LogOut logout; TestContext textcontext; public LogOutTest(TestContext context) { textcontext=context ; logout = textcontext.getPageObjectManager().getLogOut(); } @When("^User click on LogOut Link$") public void user_click_on_LogOut_Link() throws Throwable { // Write code here that turns the phrase above into concrete actions logout.clickonLogoutAvatar(); } @Then("^User Shoulg get log out from Application$") public void user_Shoulg_get_log_out_from_Application() throws Throwable { // Write code here that turns the phrase above into concrete actions logout.clickonlogOut(); } }
true
9d4278a74f82b44fb76b121aa4d44273d0ad3c3f
Java
RichardBell87/glassgateua
/src/main/java/glassgate/domain/Basecurrency.java
UTF-8
2,489
2.453125
2
[]
no_license
package glassgate.domain; import javax.persistence.*; import javax.validation.constraints.Pattern; import java.util.Date; @Entity @Table(name = "gg_currency") public class Basecurrency { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; // @Pattern(regexp = "(d{1,3})+(,\\d{0,5})?", message = "55555555555555555Введіть нікнейм для доступа на сайт.") @Column (name = "basecurrencyusdvalue") private Double basecurrencyusdvalue; // @Pattern(regexp = "(d{1,3})+(.\\d{0,5})?", message = "5555555555555Мова вводу - англійська, розмір - від 8 символів, з них: мінімум 1 цифра, 1 маленка літера, 1 велика літера.") @Column (name = "basecurrencyeurovalue") private Double basecurrencyeurovalue; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "gguserid") private User author; @Column(name = "basecurrencydatetime") // @Temporal(TemporalType.TIMESTAMP) private Date basecurrencydatetime; public Basecurrency() { } public Basecurrency(User user, Double basecurrencyusdvalue, Double basecurrencyeurovalue, Date basecurrencydatetime) { } public Basecurrency(Double basecurrencyusdvalue, Double basecurrencyeurovalue, User author) { this.basecurrencyusdvalue = basecurrencyusdvalue; this.basecurrencyeurovalue = basecurrencyeurovalue; this.author = author; this.basecurrencydatetime = basecurrencydatetime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getBasecurrencyusdvalue() { return basecurrencyusdvalue; } public void setBasecurrencyusdvalue(Double basecurrencyusdvalue) { this.basecurrencyusdvalue = basecurrencyusdvalue; } public Double getBasecurrencyeurovalue() { return basecurrencyeurovalue; } public void setBasecurrencyeurovalue(Double basecurrencyeurovalue) { this.basecurrencyeurovalue = basecurrencyeurovalue; } public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } public Date getBasecurrencydatetime() { return basecurrencydatetime; } public void setBasecurrencydatetime(Date basecurrencydatetime) { this.basecurrencydatetime = basecurrencydatetime; } }
true
ea3f4c736ed4807d8329e2cac6f6829039cb6c90
Java
dkmeena/SherlockX
/app/src/main/java/com/example/dinesh/sherlockx/NmeaSentence.java
UTF-8
6,087
2.484375
2
[]
no_license
package com.example.dinesh.sherlockx; /** * Created by vikrant on 5/9/16. */ public class NmeaSentence { // National Marine Electronics Association private final String GPGGA = "$GPGGA"; private final String GPGSA = "$GPGSA"; private final String GPGSV = "$GPGSV"; public String getGpsMode() { String gpsMode = ""; if (nmeaParts[0].equalsIgnoreCase(GPGSA)) { if (nmeaParts.length > 2 && !Strings.isNullOrEmpty(nmeaParts[2])) { gpsMode = nmeaParts[2]; } } switch (gpsMode) { case "1": gpsMode = "No Fix Available"; break; case "2": gpsMode = "2D"; break; case "3": gpsMode = "3D"; break; default: gpsMode= "invalide mode = " + gpsMode; break; } return gpsMode; } /** * $GPGSA * <p> * GPS DOP and active satellites * <p> * eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C * eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35 * <p> * <p> * 1 = Mode: * M=Manual, forced to operate in 2D or 3D * A=Automatic, 3D/2D * 2 = Mode: * 1=Fix not available * 2=2D * 3=3D * 3-14 = IDs of SVs used in position fix (null for unused fields) * 15 = PDOP * 16 = HDOP * 17 = VDOP * <p> * $GPGGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx * <p> * 1, hhmmss.ss = UTC of position * llll.ll = latitude of position * a = N or S * yyyyy.yy = Longitude of position * a = E or W * x = GPS Quality indicator (0=no fix, 1=GPS fix, 2=Dif. GPS fix) * xx = number of satellites in use * x.x = horizontal dilution of precision * x.x = Antenna altitude above mean-sea-level * M = units of antenna altitude, meters * x.x = Geoidal separation * M = units of geoidal separation, meters * x.x = Age of Differential GPS data (seconds) * xxxx = Differential reference station ID * <p> * eg3. $GPGGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh * 1 = UTC of Position * 2 = Latitude * 3 = N or S * 4 = Longitude * 5 = E or W * 6 = GPS quality indicator (0=invalid; 1=GPS fix; 2=Diff. GPS fix) * 7 = Number of satellites in use [not those in view] * 8 = Horizontal dilution of position * 9 = Antenna altitude above/below mean sea level (geoid) * 10 = Meters (Antenna height unit) * 11 = Geoidal separation (Diff. between WGS-84 earth ellipsoid and * mean sea level. -=geoid is below WGS-84 ellipsoid) * 12 = Meters (Units of geoidal separation) * 13 = Age in seconds since last update from diff. reference station * 14 = Diff. reference station ID# * 15 = Checksum */ String[] nmeaParts; public NmeaSentence(String nmeaSentence) { if (Strings.isNullOrEmpty(nmeaSentence)) { nmeaParts = new String[]{""}; return; } nmeaParts = nmeaSentence.split(","); } public boolean isLocationSentence() { return nmeaParts[0].equalsIgnoreCase(GPGSA) || nmeaParts[0].equalsIgnoreCase(GPGSV) || nmeaParts[0].equalsIgnoreCase(GPGGA); } public String getLatestPdop() { if (nmeaParts[0].equalsIgnoreCase(GPGSA)) { if (nmeaParts.length > 15 && !Strings.isNullOrEmpty(nmeaParts[15])) { return nmeaParts[15]; } } return ""; } public String getLatestVdop() { if (nmeaParts[0].equalsIgnoreCase(GPGSA)) { if (nmeaParts.length > 17 && !Strings.isNullOrEmpty(nmeaParts[17]) && !nmeaParts[17] .startsWith("*")) { return nmeaParts[17].split("\\*")[0]; } } return ""; } public String getLatestHdop() { if (nmeaParts[0].equalsIgnoreCase(GPGGA)) { if (nmeaParts.length > 8 && !Strings.isNullOrEmpty(nmeaParts[8])) { return nmeaParts[8]; } } else if (nmeaParts[0].equalsIgnoreCase(GPGSA)) { if (nmeaParts.length > 16 && !Strings.isNullOrEmpty(nmeaParts[16])) { return nmeaParts[16]; } } return ""; } public String getGeoIdHeight() { if (nmeaParts[0].equalsIgnoreCase(GPGGA)) { if (nmeaParts.length > 11 && !Strings.isNullOrEmpty(nmeaParts[11])) { return nmeaParts[11]; } } return ""; } public String getAgeOfDgpsData() { if (nmeaParts[0].equalsIgnoreCase(GPGGA)) { if (nmeaParts.length > 13 && !Strings.isNullOrEmpty(nmeaParts[13])) { return nmeaParts[13]; } } return ""; } public String getDgpsId() { if (nmeaParts[0].equalsIgnoreCase(GPGGA)) { if (nmeaParts.length > 14 && !Strings.isNullOrEmpty(nmeaParts[14]) && !nmeaParts[14] .startsWith("*")) { return nmeaParts[14].split("\\*")[0]; } } return ""; } public String getSatelliteInUse() { if (nmeaParts[0].equalsIgnoreCase(GPGGA)) { if (nmeaParts.length > 3 && !Strings.isNullOrEmpty(nmeaParts[3])) { return nmeaParts[3]; } } return ""; } public String getSatelliteInView() { if (nmeaParts[0].equalsIgnoreCase(GPGSV)) { if (nmeaParts.length > 3 && !Strings.isNullOrEmpty(nmeaParts[3])) { return nmeaParts[3]; } } return ""; } public void setNmeaSentence(String nmeaSentence) { if (Strings.isNullOrEmpty(nmeaSentence)) { nmeaParts = new String[]{""}; return; } nmeaParts = nmeaSentence.split(","); } }
true
dc45a62336f45945ee000149855c369db6e30c32
Java
dexter0201/HTTT_HienDaiJava
/IPORTLIB/src/java/BLL/ILoanService.java
UTF-8
321
2.09375
2
[]
no_license
package BLL; import DTO.Loan; import java.util.List; public interface ILoanService { boolean add(Loan loan); boolean edit(Loan loan); boolean delete(Object id); Loan get(Object id); List<Loan> gets(Object obj); int count(Object obj); int page(Object obj); int page(int pageSize, Object obj); }
true
f30bc60eccc530efbd7d940541d8137332032737
Java
alexcdemi/Java-Projects
/Circuit/src/coe318/lab6/Tester.java
UTF-8
970
3.03125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package coe318.lab6; /** * * @author Alexander */ public class Tester { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Circuit circuit1 = Circuit.getInstance(); Node C = new Node(), D = new Node(), F = new Node(); System.out.println(C.toString()+"\n" + D.toString() + "\n" + F.toString()); Resistor r1 = new Resistor(96.0, C, D), r2 = new Resistor(38.0, D, F); System.out.println(r1.toString() + "\n" + r2.toString()); System.out.println("\nCircuit"); circuit1.add(r1); circuit1.add(r2); System.out.println(circuit1.toString()); } }
true
fa762d1d2d9a58218899bfaa676401c3f3cd0ece
Java
omwah/BookShelf
/src/main/java/me/Pew446/BookShelf/BookShelf.java
UTF-8
3,978
2.3125
2
[]
no_license
package me.Pew446.BookShelf; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Logger; import lib.PatPeter.SQLibrary.*; import me.Pew446.BookShelf.BookListener; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; public class BookShelf extends JavaPlugin{ static FileConfiguration config; public static BookShelf plugin; public final Logger logger = Logger.getLogger("Minecraft"); public final BookListener BookListener = new BookListener(this); public static SQLite mysql; static ResultSet r; @Override public void onDisable() { PluginDescriptionFile pdfFile = this.getDescription(); try { if(me.Pew446.BookShelf.BookListener.r != null) me.Pew446.BookShelf.BookListener.r.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } mysql.close(); this.logger.info(pdfFile.getName() + " is now disabled."); } @Override public void onEnable() { config = getConfig(); saveDefaultConfig(); sqlConnection(); sqlDoesDatabaseExist(); getServer().getPluginManager().registerEvents(this.BookListener, this); PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled."); } public void sqlConnection() { mysql = new SQLite(logger, "BookShelf", "Shelves", this.getDataFolder().getAbsolutePath()); try { mysql.open(); } catch (Exception e) { logger.info(e.getMessage()); getPluginLoader().disablePlugin(this); } } public void sqlDoesDatabaseExist() { if(mysql.checkTable("items") == false) { mysql.createTable("CREATE TABLE items (id INTEGER PRIMARY KEY, x INT, y INT, z INT, title STRING, author STRING, type INT, loc INT, amt INT);"); } if(mysql.checkTable("pages") == false) { mysql.createTable("CREATE TABLE pages (id INT, text STRING);"); } if(mysql.checkTable("copy") == false) { mysql.createTable("CREATE TABLE copy (x INT, y INT, z INT, bool INT);"); } System.out.println("BookShelf Database Loaded."); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("bookshelf") || cmd.getName().equalsIgnoreCase("bs")){ // If the player typed /basic then do the following... Player p = Bukkit.getPlayer(sender.getName()); if(p.hasPermission("bookshelf")) { Location loc = p.getTargetBlock(null, 10).getLocation(); if(loc.getBlock().getType() == Material.BOOKSHELF) { ResultSet re = mysql.query("SELECT * FROM copy WHERE x="+loc.getX()+" AND y="+loc.getY()+" AND z="+loc.getZ()+";"); try { if(re.getInt("bool") == 1) { re.close(); p.sendMessage("The bookshelf you are looking at is now limited."); mysql.query("UPDATE copy SET bool=0 WHERE x="+loc.getX()+" AND y="+loc.getY()+" AND z="+loc.getZ()+";"); } else { re.close(); p.sendMessage("The bookshelf you are looking at is now unlimited."); mysql.query("UPDATE copy SET bool=1 WHERE x="+loc.getX()+" AND y="+loc.getY()+" AND z="+loc.getZ()+";"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { p.sendMessage("Please look at a bookshelf when using this command"); } } else { p.sendMessage("You don't have permission to use this command!"); } return true; } return false; } }
true
10982ad4b7453d84e351b482a564657a4ad7027f
Java
hzr958/myProjects
/scmv6/web-psn/src/main/java/com/smate/web/psn/action/autocomplete/AutoCompleteAction.java
UTF-8
14,093
1.945313
2
[]
no_license
package com.smate.web.psn.action.autocomplete; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Actions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; import com.smate.core.base.consts.model.ConstKeyDisc; import com.smate.core.base.consts.model.ConstPosition; import com.smate.core.base.consts.model.ConstRegion; import com.smate.core.base.consts.service.ConstPositionService; import com.smate.core.base.utils.constant.ConstDictionary; import com.smate.core.base.utils.json.JacksonUtils; import com.smate.core.base.utils.string.StringHtml; import com.smate.core.base.utils.struts2.Struts2Utils; import com.smate.web.psn.form.autocomplete.AutoCompleteForm; import com.smate.web.psn.model.autocomplete.AcInsUnit; import com.smate.web.psn.model.autocomplete.AcInstitution; import com.smate.web.psn.service.autocomplete.AutoCompleteSnsService; /** * 页面上输入单词,进行自动提示的类 */ public class AutoCompleteAction extends ActionSupport implements ModelDriven<AutoCompleteForm>, Preparable { private static final long serialVersionUID = 6866955514755380566L; protected Logger logger = LoggerFactory.getLogger(getClass()); private static final int MAXSIZE = 10; private AutoCompleteForm form; @Autowired private AutoCompleteSnsService autoCompleteSnsService; @Autowired private ConstPositionService constPositionService; /** * 获取自动填充的群组研究领域 * * @return * @throws Exception */ @Action(value = "/psnweb/ac/keywords") public String getDisciplinekeyword() throws Exception { HttpServletRequest request = Struts2Utils.getRequest(); String startWith = request.getParameter("q"); if (StringUtils.isBlank(startWith)) startWith = ""; else startWith = startWith.trim(); String data = "[]"; data = autoCompleteSnsService.autoCompleteDiscipline(MAXSIZE, startWith); Struts2Utils.renderJson(data, "encoding:UTF-8"); return null; } /** * 个人主页-获取自动填充的部门(学院) * * @return */ @Actions({@Action("/psnweb/ac/ajaxautoinsunit"), @Action("/psndata/mobile/ajaxautoinsunit")}) public String getAutoInsUnit() { try { if ("zh_CN".equals(form.getLocale())) { LocaleContextHolder.setLocale(Locale.CHINA, true); } List<AcInsUnit> insUnitList = autoCompleteSnsService.getAcInsUnit(form); if (CollectionUtils.isNotEmpty(insUnitList)) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (AcInsUnit acInsUnit : insUnitList) { Map<String, String> map = new HashMap<String, String>(); if (StringUtils.isEmpty(acInsUnit.getDepartment())) {// 没有系名称时,name值设置为院名称 map.put("name", acInsUnit.getCollegeName()); } else { map.put("name", acInsUnit.getDepartment()); } map.put("code", acInsUnit.getUnitIds()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("个人主页-获取自动填充的部门,出错", e); } return null; } /** * 个人主页-获取自动填充的职称 * * @return */ @Actions({@Action("/psnweb/ac/ajaxautoposition"), @Action("/psndata/mobile/ajaxautoposition")}) public String getAutoPostion() { try { if ("zh_CN".equals(form.getLocale())) { LocaleContextHolder.setLocale(Locale.CHINA, true); } List<ConstPosition> positionList = constPositionService.getPosLike(form.getSearchKey(), 5); if (CollectionUtils.isNotEmpty(positionList)) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (ConstPosition constPosition : positionList) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", constPosition.getName()); map.put("code", constPosition.getId()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("个人主页-获取自动填充的职称,出错", e); } return null; } /** * 个人主页-获取自动填充的机构名称 * * @return */ @Actions({@Action("/psnweb/ac/ajaxautoinstitution"), @Action("/psndata/mobile/ajaxautoinstitution")}) public String getAutoInstitution() { try { // 移动端的请求会传locale="zh_CN",移动端的请求不设置为中文的话生产机会检索英文语言的逻辑 if ("zh_CN".equals(form.getLocale())) { LocaleContextHolder.setLocale(Locale.CHINA, true); } List<AcInstitution> acInstitutionList = autoCompleteSnsService.getAcInstitution(form.getSearchKey(), null, 5); if (CollectionUtils.isNotEmpty(acInstitutionList)) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (AcInstitution acInstitution : acInstitutionList) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", acInstitution.getName()); map.put("code", acInstitution.getCode()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("个人主页-获取自动填充的机构名称,出错", e); } return null; } /** * 自动填充学科关键词 * * @return */ @Action("/psnweb/recommend/ajaxautoconstkeydiscscodeid") public String ajaxAutoConstKeyDiscsCodeId() { try { List<ConstKeyDisc> constKeyDiscList = autoCompleteSnsService.getConstKeyDiscs(form.getSearchKey(), 5); if (constKeyDiscList != null && constKeyDiscList.size() > 0) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); for (ConstKeyDisc c : constKeyDiscList) { Map<String, String> map = new HashMap<String, String>(); map.put("code", c.getDiscCodes().toString()); map.put("name", c.getKeyWord()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("自动填充学科关键词", e); } return null; } /** * * 获取自动填充地区 */ @Actions({@Action("/psnweb/ac/ajaxautoregion"), @Action("/psnweb/outside/ajaxautoregion")}) public String getAutoregion() { try { List<ConstRegion> acRegionList = autoCompleteSnsService.getAcregion(form.getSearchKey(), null, 5); if (CollectionUtils.isNotEmpty(acRegionList)) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (ConstRegion constRegion : acRegionList) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", constRegion.getName()); map.put("code", constRegion.getId()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("个人主页-获取自动填充的机构名称,出错", e); } return null; } /** * * 获取自动填充地区 */ @Actions({@Action("/psnweb/outside/ajaxautoprovinces")}) public String getAutoProvinces() { try { List<ConstRegion> acRegionList = autoCompleteSnsService.getAcprovinces(form.getSearchKey(), 5); if (CollectionUtils.isNotEmpty(acRegionList)) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (ConstRegion constRegion : acRegionList) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", constRegion.getName()); map.put("code", constRegion.getId()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("个人主页-获取自动填充的机构名称,出错", e); } return null; } /** * 个人主页-获取自动填充的学历 * * @return */ @Actions({@Action("/psnweb/ac/ajaxautodegree"), @Action("/psndata/mobile/ajaxautodegree")}) public String getAutoDegree() { try { Locale locale = LocaleContextHolder.getLocale();// zh_CN List<ConstDictionary> constDictionaryList = autoCompleteSnsService.getAcDegree("psn_degree", form.getSearchKey()); if (CollectionUtils.isNotEmpty(constDictionaryList)) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (ConstDictionary constDictionary : constDictionaryList) { Map<String, Object> map = new HashMap<String, Object>(); if ("en_US".equals(locale + "")) { map.put("name", constDictionary.getEnUsName()); } else { map.put("name", constDictionary.getZhCnName()); } map.put("code", constDictionary.getKey().getCode()); list.add(map); } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(list), "encoding:UTF-8"); } } catch (Exception e) { logger.error("个人主页-获取自动填充的学历,出错", e); } return null; } /** * 自动提示所在地区 SCM-11985_WSN_2017-5-17 * * @return */ @Action("/psnweb/ac/ajaxregionstr") public String buildPsnRegionStr() { try { // 查询的字符串为空直接返回 if (StringUtils.isNotBlank(form.getSearchKey())) { List<Map<String, Object>> mapList = autoCompleteSnsService.searchConstRegionInfo(form.getSearchKey(), "", 10); Struts2Utils.renderJson(JacksonUtils.listToJsonStr(mapList), "encoding:UTF-8"); } } catch (Exception e) { logger.error("自动提示地区信息出错,searchKey=" + form.getSearchKey(), e); } return null; } /** * 成果编辑添加成果作者,从合作者或好友中提示 * * @return */ @Action("/psnweb/ac/ajaxpsncooperator") public String builPsnCooperator() { try { List<Map<String, Object>> mapList = autoCompleteSnsService.searchPsnCooperator(form, 5); Struts2Utils.renderJson(JacksonUtils.listToJsonStr(mapList), "encoding:UTF-8"); } catch (Exception e) { logger.error("成果作者自动提示人名出错,searchKey=" + form.getSearchKey(), e); } return null; } /** * 获取自动提示JSON数据. * * @return * @throws Exception */ @Action("/psnweb/ac/ajaxgetComplete") public void getAcJsonData() throws Exception { String type = form.getType(); try { List<Map<String, Object>> data = null; String searchKey = form.getSearchKey(); if (StringUtils.isNotBlank(type)) { if (type.equalsIgnoreCase("awardCategory")) {// 奖励类别自动提示列表 data = autoCompleteSnsService.getAcAwardCategory(searchKey, MAXSIZE); } else if (type.equalsIgnoreCase("awardGrade")) {// 奖励等级列表 data = autoCompleteSnsService.getAcAwardGrade(searchKey, MAXSIZE); } else if (type.equalsIgnoreCase("confName")) {// 会议名称自动提示 data = autoCompleteSnsService.getAcConfName(searchKey, MAXSIZE); } else if (type.equalsIgnoreCase("confOrganizer")) {// 会议组织者自动提示列表 data = autoCompleteSnsService.getAcConfOrganizer(searchKey, MAXSIZE); } else if (type.equalsIgnoreCase("journal")) {// 期刊列表 data = autoCompleteSnsService.getAcJournal(searchKey, MAXSIZE); } else if (type.contains("Title")) { // 期刊标题 // TODO data = autoCompleteSnsService.getAcTitle(searchKey, type); } else if (type.equalsIgnoreCase("patentOrg")) {// 发证单位自动提示列表 data = autoCompleteSnsService.getAcPatentOrg(searchKey, MAXSIZE); } else if (type.equalsIgnoreCase("thesisOrg")) {// 颁发单位自动提示列表 data = autoCompleteSnsService.getAcThesisOrg(searchKey, MAXSIZE); } else if (type.equalsIgnoreCase("publisher")) {// 出版社自动提示列表 data = autoCompleteSnsService.getAcPublisher(searchKey, MAXSIZE); } } Struts2Utils.renderJson(JacksonUtils.listToJsonStr(data), "encoding:UTF-8"); } catch (Exception e) { logger.error("成果编辑自动提示出错,type=" + type, e); } } /** * 为成果与人员检索获取自动提示JSON数据. * * @return * @throws Exception */ @Action("/psnweb/ac/ajaxpdwhsearchpub") public void getAcJsonDataForPdwhSearch() throws Exception { try { List<Map<String, Object>> data = null; String searchKey = form.getSearchKey(); // suggestType=1 使用pub检索的排序提示 data = this.autoCompleteSnsService.getPdwhSearchSuggest(searchKey, 1); String jsonData = StringHtml.toHtmlInput(JacksonUtils.listToJsonStr(data));// 将数据中包含的那些html标签进行转义 Struts2Utils.renderJson(jsonData, "encoding:UTF-8"); } catch (Exception e) { logger.error("成果检索获取自动提示JSON数据,type=pubSearch", e); } } @Override public AutoCompleteForm getModel() { return form; } @Override public void prepare() throws Exception { if (form == null) { form = new AutoCompleteForm(); } } }
true
8e55db19708dbd10c4397bb64b7effc2cc948ccc
Java
suntinghui/Housekeeper4Android_landlord
/app/src/main/java/com/housekeeper/activity/view/KeeperLeasedAdapter.java
UTF-8
7,993
2.078125
2
[]
no_license
package com.housekeeper.activity.view; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.ares.house.dto.app.LeasedListAppDto; import com.housekeeper.activity.BaseActivity; import com.housekeeper.activity.HouseInfoActivity; import com.housekeeper.activity.keeper.KeeperIDCardActivity; import com.housekeeper.activity.keeper.KeeperReturnActivity; import com.housekeeper.client.Constants; import com.housekeeper.client.net.ImageCacheManager; import com.wufriends.housekeeper.landlord.R; import java.util.ArrayList; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by sth on 10/7/15. */ public class KeeperLeasedAdapter extends BaseAdapter { private BaseActivity context = null; private LayoutInflater layoutInflater = null; private List<LeasedListAppDto> list = new ArrayList<LeasedListAppDto>(); public KeeperLeasedAdapter(BaseActivity context) { this.context = context; this.layoutInflater = LayoutInflater.from(context); } public void setData(List<LeasedListAppDto> list) { if (list == null) return; this.list = list; this.notifyDataSetChanged(); } @Override public int getCount() { return this.list.size(); } @Override public Object getItem(int position) { return this.list.get(position); } @Override public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.layout_keeper_leased, parent, false); holder.houseInfoLayout = (LinearLayout) convertView.findViewById(R.id.houseInfoLayout); holder.headImageView = (CustomNetworkImageView) convertView.findViewById(R.id.headImageView); holder.addressTextView = (TextView) convertView.findViewById(R.id.addressTextView); holder.cityTextView = (TextView) convertView.findViewById(R.id.cityTextView); holder.begingDateTextView = (TextView) convertView.findViewById(R.id.begingDateTextView); holder.endDateTextView = (TextView) convertView.findViewById(R.id.endDateTextView); holder.tenantInfoLayout = (LinearLayout) convertView.findViewById(R.id.tenantInfoLayout); holder.tenantLogoImageView = (CircleImageView) convertView.findViewById(R.id.tenantLogoImageView); holder.tenantNameTextView = (TextView) convertView.findViewById(R.id.tenantNameTextView); holder.tenantTelphoneTextView = (TextView) convertView.findViewById(R.id.tenantTelphoneTextView); holder.tenantAddressTextView = (TextView) convertView.findViewById(R.id.tenantAddressTextView); holder.landlordInfoLayout = (LinearLayout) convertView.findViewById(R.id.landlordInfoLayout); holder.landlordLogoImageView = (CircleImageView) convertView.findViewById(R.id.landlordLogoImageView); holder.landlordNameTextView = (TextView) convertView.findViewById(R.id.landlordNameTextView); holder.returnTextView = (TextView) convertView.findViewById(R.id.returnTextView); holder.returnBtn = (Button) convertView.findViewById(R.id.returnBtn); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final LeasedListAppDto infoDto = list.get(position); holder.headImageView.setDefaultImageResId(R.drawable.head_tenant_default); holder.headImageView.setErrorImageResId(R.drawable.head_tenant_default); holder.headImageView.setLocalImageBitmap(R.drawable.head_tenant_default); holder.headImageView.setImageUrl(Constants.HOST_IP + infoDto.getIndexImgUrl(), ImageCacheManager.getInstance().getImageLoader()); holder.addressTextView.setText(infoDto.getCommunity() + " " + infoDto.getHouseNum()); holder.cityTextView.setText(infoDto.getCityStr() + " " + infoDto.getAreaStr() + " " + infoDto.getAddress()); holder.begingDateTextView.setText(infoDto.getBeginTimeStr()); holder.endDateTextView.setText(infoDto.getEndTimeStr()); holder.tenantLogoImageView.setImageURL(Constants.HOST_IP + infoDto.getUserLogo()); holder.tenantNameTextView.setText(infoDto.getUserName()); // holder.tenantTelphoneTextView.setText(infoDto.getUserBankCard()); holder.tenantAddressTextView.setText(infoDto.getWorkAddress()); // holder.landlordLogoImageView.setImageURL(Constants.HOST_IP + infoDto.getLandlordLogo()); // holder.landlordNameTextView.setText(infoDto.getLandlordUserName()); // b 正常 c退租中 d已完成 if (infoDto.getStatus() == 'b') { holder.returnTextView.setVisibility(View.GONE); holder.returnBtn.setVisibility(View.VISIBLE); holder.returnBtn.setEnabled(true); } else if (infoDto.getStatus() == 'c') { holder.returnTextView.setVisibility(View.GONE); holder.returnBtn.setVisibility(View.VISIBLE); holder.returnBtn.setText("退租中"); holder.returnBtn.setEnabled(false); } else if (infoDto.getStatus() == 'd') { holder.returnTextView.setVisibility(View.VISIBLE); holder.returnBtn.setVisibility(View.GONE); holder.returnBtn.setEnabled(false); holder.returnTextView.setText("该房源已经申请退租,退租时间是" + infoDto.getTakeBackTime() + ",需退还金额" + infoDto.getTakeBackMortgageMoney() + "元。"); } holder.houseInfoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, HouseInfoActivity.class); intent.putExtra("houseId", infoDto.getHouseId() + ""); context.startActivity(intent); } }); holder.tenantInfoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, KeeperIDCardActivity.class); intent.putExtra("editable", false); context.startActivity(intent); } }); holder.landlordInfoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); holder.returnBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, KeeperReturnActivity.class); intent.putExtra("DTO", infoDto); context.startActivity(intent); } }); return convertView; } public static final class ViewHolder { private LinearLayout houseInfoLayout; private CustomNetworkImageView headImageView; private TextView addressTextView; private TextView cityTextView; private TextView begingDateTextView; private TextView endDateTextView; private LinearLayout tenantInfoLayout; private CircleImageView tenantLogoImageView; private TextView tenantNameTextView; private TextView tenantTelphoneTextView; private TextView tenantAddressTextView; private LinearLayout landlordInfoLayout; private CircleImageView landlordLogoImageView; private TextView landlordNameTextView; private TextView returnTextView; private Button returnBtn; } }
true
3122c960fa13e498f62eeeed614867e44096cbbd
Java
tannguyen2k/AppBanXeMer
/app/src/main/java/com/example/cuahangxeonline/Model/GioHang.java
UTF-8
1,062
1.9375
2
[]
no_license
package com.example.cuahangxeonline.Model; public class GioHang { public String IDsp, Tensp; public double Giasp; public String Hinhsp; public int Soluong; public String getIDsp() { return IDsp; } public void setIDsp(String IDsp) { this.IDsp = IDsp; } public String getTensp() { return Tensp; } public void setTensp(String tensp) { Tensp = tensp; } public double getGiasp() { return Giasp; } public void setGiasp(double giasp) { Giasp = giasp; } public String getHinhsp() { return Hinhsp; } public void setHinhsp(String hinhsp) { Hinhsp = hinhsp; } public int getSoluong() { return Soluong; } public void setSoluong(int soluong) { Soluong = soluong; } public GioHang(String IDsp, String tensp, double giasp, String hinhsp, int soluong) { this.IDsp = IDsp; Tensp = tensp; Giasp = giasp; Hinhsp = hinhsp; Soluong = soluong; } }
true
3fc24e3fdd03c6436719135dde91a766cfbedca8
Java
talipturkmen/DesignPatterns
/src/main/java/com/amadeus/training/patterns/structural/decorator/web/ABPage.java
UTF-8
286
2.34375
2
[]
no_license
package com.amadeus.training.patterns.structural.decorator.web; /** * css + horizonal */ public class ABPage implements WebPage { @Override public void render() { addCss(); addHS(); } private void addCss() { } private void addHS() { } }
true
92abbb1a4ea9fd5a8ed6473712fef404a29b921b
Java
pmacik/jaxrs-cdi-reproducer
/src/main/java/org/jboss/qa/jaxrs_cdi_reproducer/rest/BeanREST.java
UTF-8
838
2.234375
2
[]
no_license
package org.jboss.qa.jaxrs_cdi_reproducer.rest; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.jboss.qa.jaxrs_cdi_reproducer.dao.BeanDAO; import org.jboss.qa.jaxrs_cdi_reproducer.model.Bean; @Path("/bean") @RequestScoped public class BeanREST { @Inject private BeanDAO dao; @GET() @Produces("text/xml") @Path("/getAll") public List<Bean> findAll() { return dao.findAll(); } @GET() @Produces("text/xml") @Path("/get/{id}") public Bean findById(@PathParam("id") Integer id) { return dao.findById(id); } @GET() @Produces("text/xml") @Path("/create/{name}") public Bean create(@PathParam("name") String name) { return dao.create(name); } }
true
0ccda8837d072d28e054f77eef7e7082d55d7342
Java
LinYsss/netty_mvc_server
/src/main/java/com/waya/demo/util/utils/ReflectionUtil.java
UTF-8
4,358
2.984375
3
[]
no_license
package com.waya.demo.util.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 反射工具类 */ public final class ReflectionUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class); /** * 创建实例 */ public static Object newInstance(Class<?> cls) { Object instance; try { instance = cls.newInstance();//newInstance相当于new } catch (Exception e) { LOGGER.error("new instance failure", e); throw new RuntimeException(e); } return instance; } /** * 创建实例(根据类名) */ public static Object newInstance(String className) { Class<?> cls = ClassUtil.loadClass(className); return newInstance(cls); } /** * 调用方法 */ public static Object invokeMethod(Object obj, Method method, Object... args) { Object result; try { method.setAccessible(true); result = method.invoke(obj, args);//invoke 方法.invoke(controller对象,获取值) } catch (Exception e) { LOGGER.error("invoke method failure", e); throw new RuntimeException(e); } return result; } /** * 设置成员变量的值 */ public static void setField(Object obj, Field field, Object value) { try { field.setAccessible(true); //去除私有权限 field.set(obj, value); } catch (Exception e) { LOGGER.error("set field failure", e); throw new RuntimeException(e); } } /** * 获得调用方法的名称 * * @return 方法名称 */ public static String getCallMethod(){ StackTraceElement[] stack = Thread.currentThread().getStackTrace(); // 获得调用方法名 String method = stack[3].getMethodName(); return method; } /** * 获得调用方法的类名+方法名,带上中括号 * * @return 方法名称 */ public static String getCallClassMethod(){ StackTraceElement stack[] = Thread.currentThread().getStackTrace(); // 获得调用方法名 String[] className = stack[3].getClassName().split("\\."); String fullName = className[className.length - 1] + ":" + stack[3].getMethodName(); return fullName; } /** * 获得调用方法的类名+方法名 * * @return 方法名称 */ public static String getNakeCallClassMethod(){ StackTraceElement stack[] = Thread.currentThread().getStackTrace(); // 获得调用方法名 String[] className = stack[3].getClassName().split("\\."); String fullName = className[className.length - 1] + "." + stack[3].getMethodName(); return fullName; } /** * 取得父类所有的接口 * * @param targetClass * @return */ public static Class<?>[] getInterfaces(Class<?> targetClass){ Set<Class<?>> interfaceSet = new HashSet<>(); //数组转成list List<Class<?>> subList = Arrays.asList(targetClass.getInterfaces()); if (subList.size() > 0) interfaceSet.addAll(subList); Class superClass = targetClass.getSuperclass(); while (null != superClass) { subList = Arrays.asList(superClass.getInterfaces()); if (subList.size() > 0) interfaceSet.addAll(subList); superClass = superClass.getSuperclass(); } //set 转成 数组 return interfaceSet.toArray(new Class<?>[0]); } public static Object newProxyInstance(Object targetObject, InvocationHandler handler){ Class targetClass = targetObject.getClass(); ClassLoader loader = targetClass.getClassLoader(); //被代理类实现的接口 Class<?>[] targetInterfaces = ReflectionUtil.getInterfaces(targetClass); Object proxy = Proxy.newProxyInstance(loader, targetInterfaces, handler); return proxy; } }
true
4c628a0214c6a6cc684bf9e9fd2a303ba14f2d7d
Java
kesavarajesh/YovoAndroidAutomation
/src/main/java/com/automation/pages/UserProfilePage.java
UTF-8
846
1.96875
2
[]
no_license
package com.automation.pages; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.AndroidFindBy; public class UserProfilePage extends BasePOMPage { @AndroidFindBy(id = "user_name") private AndroidElement userProfile; @AndroidFindBy(id = "back_button") private AndroidElement backBtn; @AndroidFindBy(id = "send_coin_text") private AndroidElement sendCoinTxt; public UserProfilePage(AppiumDriver appiumDriver) { super(appiumDriver); } public String getUserNameOnUserProfile() { return userProfile.getText(); } public void clickOnBackBtn() { backBtn.click(); } public boolean verifySendCoinsTxt() { return sendCoinTxt.isDisplayed(); } }
true
6692b9b477edbcde6d1e30fe05082cc5ed8cca41
Java
Gleb4ever/JavaSkillBox
/06_InheritanceAndPolymorphism/HomeWork 6.3.1/src/Clients/Client.java
UTF-8
1,044
3.234375
3
[]
no_license
package Clients; public abstract class Client { private double account; Client(double account) { this.account = account; } public double getAccount() { return account; } public void setAccount(double account) { this.account = account; } public double get_BANK_COMMISION() { return 0.01; } public double get_BANK_COMMISION_2() { return 0.005; } public abstract void accountInfo(); public void topUpBalance(double amount) { if (amount > 0){ setAccount(getAccount() + amount); } else {System.out.println("Введена некоректная сумма для внесения!"); } } public void withdrawMoney(double amount) { { if (amount > 0 && amount < getAccount()){ setAccount(getAccount() - amount); } else {System.out.println("Введена некоректная сумма для снятия!"); } } } }
true
242aeb4c992f785a77a41d758d185e168008b995
Java
SwimmingHwang/Humuson-IMC-Intern
/intern-admin/src/main/java/com/humuson/config/AdminSecurityConfig.java
UTF-8
3,520
2.078125
2
[]
no_license
package com.humuson.config; import com.humuson.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @RequiredArgsConstructor class AdminSecurityConfig extends WebSecurityConfigurerAdapter { private final UserService userService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void configure(WebSecurity web) throws Exception { // static 디렉터리의 하위 파일 목록은 인증 무시 ( = 항상통과 ) web.ignoring().antMatchers("/resources/**", "/css/**", "/js/**", "/img/**", "/vendor/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests().antMatchers("/**").permitAll(); http.authorizeRequests() .antMatchers("/user/**").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/monitor/**").permitAll() // acturator의 endpoint에 모두 접근하게 허용 .antMatchers("/sba/**").permitAll() .anyRequest().hasRole("ADMIN") ; http.formLogin() .loginPage("/user/login") .usernameParameter("email").passwordParameter("password") // id, pwd param 변경 .loginProcessingUrl("/user/login") // .defaultSuccessUrl("/user/login/result") .failureForwardUrl("/user/login") ; http.logout() .logoutRequestMatcher(new AntPathRequestMatcher("/user/logout")) .logoutSuccessUrl("/user/logout/result") .invalidateHttpSession(true) // 로그아웃 시 세션 제거 // .deleteCookies("JSESSIONID") // 쿠키 제거 // .clearAuthentication(true) // 권한 정보 제거 // .permitAll() ; http.exceptionHandling() .accessDeniedPage("/user/denied") ; http.httpBasic() // .disable() ; http.headers() // 기본 보안 암호 사용 제거 .httpStrictTransportSecurity() .disable() ; // http.sessionManagement() // .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // .maximumSessions(1) // 세션 1개만 유지 // .maxSessionsPreventsLogin(true); // 동시 접속 세션수 제한 // ; } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); //auth.authenticationProvider(authenticationProvider); } }
true
41610df1781849308bbe123aa006dce161b447fc
Java
o2p-asiainfo/o2p-base-dao
/src/main/java/com/ailk/eaap/op2/settleRuleOrgRel/dao/SettleRuleOrgRelDaoImpl.java
UTF-8
1,974
2.125
2
[]
no_license
/** * Project Name:o2p-base-dao * File Name:SettleRuleOrgRelDaoImpl.java * Package Name:com.ailk.eaap.op2.settleRuleOrgRel.dao * Date:2016年4月14日下午9:24:30 * Copyright (c) 2016, www.asiainfo.com All Rights Reserved. * */ package com.ailk.eaap.op2.settleRuleOrgRel.dao; import com.ailk.eaap.op2.bo.SettleRuleOrgRel; import com.linkage.rainbow.dao.SqlMapDAO; /** * ClassName:SettleRuleOrgRelDaoImpl <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2016年4月14日 下午9:24:30 <br/> * @author wushuzhen * @version * @since JDK 1.7 * @see */ public class SettleRuleOrgRelDaoImpl implements SettleRuleOrgRelDao{ private SqlMapDAO sqlMapDao; public SettleRuleOrgRelDaoImpl() { super(); } @Override public void insert(SettleRuleOrgRel settleRuleOrgRel) { // TODO Auto-generated method stub if(settleRuleOrgRel.getOrgId()!=null&&settleRuleOrgRel.getOrgId()>0){ sqlMapDao.insert("settleRuleOrgRel.insertSelective", settleRuleOrgRel); } } @Override public SettleRuleOrgRel querySettleRuleOrgRelInfo( SettleRuleOrgRel settleRuleOrgRel) { // TODO Auto-generated method stub return (SettleRuleOrgRel) sqlMapDao.queryForObject("settleRuleOrgRel.querySettleRuleOrgRelInfo", settleRuleOrgRel); } @Override public void updateSettleRuleOrgRelInfo(SettleRuleOrgRel settleRuleOrgRel) { // TODO Auto-generated method stub if(settleRuleOrgRel.getOrgId()!=null&&settleRuleOrgRel.getOrgId()>0){ sqlMapDao.update("settleRuleOrgRel.updateSettleRuleOrgRelInfo", settleRuleOrgRel); } } @Override public void deleteSettleRuleOrgRelInfo(SettleRuleOrgRel settleRuleOrgRel) { // TODO Auto-generated method stub sqlMapDao.delete("settleRuleOrgRel.deleteSettleRuleOrgRelInfo", settleRuleOrgRel); } public SqlMapDAO getSqlMapDao() { return sqlMapDao; } public void setSqlMapDao(SqlMapDAO sqlMapDao) { this.sqlMapDao = sqlMapDao; } }
true
fdfe450e72d1ed109861248b6238359753109c50
Java
tpfk624/Kitri---JAVA
/arraytest/src/com/kitri/array/NumberBaseBall.java
UHC
3,072
3.796875
4
[]
no_license
package com.kitri.array; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /* 0, com, my 3ڸ迭 1. com ڸ ߻ >> comRandom() 2. 1 ڴ ߺ x 0 x 3. Է 3ڸ ڸ my迭 ֱ 4. com my ڿ ڸ 5. ڰ ٸ 5-1. ڸ ٸ strike 5-2. ڸ ٸٸ ball 6. 5 6-1.strike 3 : xxx x° Դϴ. (1), (0) 6-2. strike 3 ƴ϶ 1. xxx xƮũ xԴϴ. >> 3 */ //int strike, int ball, int count Ŀ ޶ public class NumberBaseBall { private int my[] = new int[3]; private int com[] = new int[3]; BufferedReader in; // public NumberBaseBall() { //߻޼ҵ ȣ comRandom(); in = new BufferedReader(new InputStreamReader(System.in));//͹ޱ } //߻ private void comRandom() { com[0] = (int)(Math.random() * 10)+1; //0 x do { com[1] = (int)(Math.random() * 10); }while(com[0] == com[1]); do { com[2] = (int)(Math.random() * 10); }while(com[0] == com[2] || com[1] == com[2]); } //game() 0 ѷ private void game() { System.out.println(Arrays.toString(com)); int strike = 0; int ball = 0; int count = 0; while(true) { strike = 0; ball = 0; System.out.print("Է: "); int myNum = getNumber(); //149 my[0] = (myNum/100); //1 my[1] = myNum / 10 % 10; //4 //(myNum-(my[0] *100))/10; my[2] = (myNum % 10); //9 //ڰ Ȱ ڸ Էߴٸ? ҽ߰ϱ System.out.println(Arrays.toString(my)); //ڿ ڸ for(int i = 0; i<3; i++) { for(int j =0; j<3; j++) { if(com[i] == my[j]) { if(i == j) { strike += 1; }else { ball += 1; } } } } count++; // if(strike != 3) { System.out.println(myNum + " " + strike + "Ʈũ " + ball + "ballԴϴ."); }else { System.out.println(myNum + "" + count + " Դϴ"); System.out.print("Ǵ(1), (0) : "); int mynum = getNumber(); if(mynum == 0) { System.out.print("α׷ !!!"); System.exit(0); } else comRandom(); game(); } } } private int getNumber() { int num = 0; try { num = Integer.parseInt(in.readLine()); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return num; } public static void main(String[] args) { NumberBaseBall nbb = new NumberBaseBall(); nbb.game(); } }
true
8f94e2f9158f4e4f598a751236cbf0286b8a9551
Java
KidusMT/Advanced-Software-Development
/testForLab03/src/main/SavingsStrategy.java
UTF-8
334
3.015625
3
[]
no_license
package main; public class SavingsStrategy implements InterestStrategy { @Override public double calculateInterest(double balance) { // TODO Auto-generated method stub if(balance<1000) { return balance*0.01; }else if(balance>=1000 && balance<5000) { return balance*0.02; }else { return balance*0.04; } } }
true
2ff0bb62edaeb64069c97d2aaca2bc7aa468a7e1
Java
djw1149/cougaar-core
/core/src/org/cougaar/core/persist/PersistenceMetricImpl.java
UTF-8
3,541
1.898438
2
[]
no_license
/* * <copyright> * * Copyright 1997-2004 BBNT Solutions, LLC * under sponsorship of the Defense Advanced Research Projects * Agency (DARPA). * * You can redistribute this software and/or modify it under the * terms of the Cougaar Open Source License as published on the * Cougaar Open Source Website (www.cougaar.org). * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * </copyright> */ package org.cougaar.core.persist; import org.cougaar.core.service.PersistenceMetricsService; /** * {@link org.cougaar.core.service.PersistenceMetricsService.Metric} * implementation. */ public class PersistenceMetricImpl implements PersistenceMetricsService.Metric { private String name; private long startTime, endTime, cpuTime, size; private boolean full; private Throwable failed; private PersistencePlugin plugin; private int count; PersistenceMetricImpl(String name, long startTime, long endTime, long cpuTime, long size, boolean full, Throwable failed, PersistencePlugin plugin) { this.name = name; this.startTime = startTime; this.endTime = endTime; this.cpuTime = cpuTime; this.size = size; this.full = full; this.failed = failed; this.plugin = plugin; this.count = 1; } PersistenceMetricImpl() { } void average(PersistenceMetricsService.Metric metric) { startTime += metric.getStartTime(); endTime += metric.getEndTime(); cpuTime += metric.getCpuTime(); size += metric.getSize(); count += 1; } public long getStartTime() { return count == 0 ? startTime : startTime / count; } public long getEndTime() { return count == 0 ? endTime : endTime / count; } public long getSize() { return count == 0 ? size : size / count; } public long getCpuTime() { return count == 0 ? cpuTime : cpuTime / count; } public boolean isFull() { return full; } public Throwable getException() { return failed; } public String getName() { return name; } public Class getPersistencePluginClass() { return plugin.getClass(); } public String getPersistencePluginName() { return plugin.getName(); } public int getPersistencePluginParamCount() { return plugin.getParamCount(); } public String getPersistencePluginParam(int i) { return plugin.getParam(i); } public int getCount() { return count; } @Override public String toString() { return (failed == null ? "Persisted " : "Failed ") + (full ? "full" : "delta") + name + ", " + size +" bytes in " + (endTime - startTime) + " ms" + ((cpuTime > 0L) ? (" using " + cpuTime) : "") + " ms cpu"; } }
true
9da2c7cfa5c606623db0b450ee0440cbd2c232e2
Java
Aonanz/JavaInternship
/JavaSE/src/Day02/集合框架/Map/TreeMapAndLinkMap/linkandtreemap.java
UTF-8
1,363
3.84375
4
[]
no_license
package Day02.集合框架.Map.TreeMapAndLinkMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; public class linkandtreemap { public static void main(String[] args) { HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); // 按输入顺序排 LinkedHashMap<Integer, String> linkedhashMap = new LinkedHashMap<Integer, String>(); TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // 无序 testMap(hashMap); System.out.println("-------------------------------------"); // 有序正序,利用给的顺序排序 testMap(linkedhashMap); System.out.println("-------------------------------------"); // 有序排序,会按真正的自然排序(123456789) testMap(treeMap); } public static void testMap(Map<Integer, String> map) { map.put(9,"Will"); map.put(8,"Willa"); map.put(7,"Willb"); map.put(6,"Willc"); map.put(5,"Willd"); map.put(4,"Wille"); map.put(3,"Willf"); map.put(2,"Willg"); map.put(1,"Willh"); map.put(0,"Willi"); for(Integer key: map.keySet()) { String value = map.get(key); System.out.println(key + ":" + value); } } }
true
fb50547cd15eb133039e3c08ccd5d0648675e7cf
Java
miriarte/thrifty
/thrifty-schema/src/main/java/com/microsoft/thrifty/schema/Service.java
UTF-8
9,790
1.8125
2
[ "Apache-2.0" ]
permissive
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.microsoft.thrifty.schema.parser.AnnotationElement; import com.microsoft.thrifty.schema.parser.FunctionElement; import com.microsoft.thrifty.schema.parser.ServiceElement; import com.microsoft.thrifty.schema.parser.TypeElement; import java.util.ArrayDeque; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; public final class Service extends Named { private final ServiceElement element; private final ImmutableList<ServiceMethod> methods; private final ThriftType type; private final ImmutableMap<String, String> annotations; private ThriftType extendsService; Service( ServiceElement element, ThriftType type, Map<NamespaceScope, String> namespaces, FieldNamingPolicy fieldNamingPolicy) { super(element.name(), namespaces); this.element = element; this.type = type; ImmutableList.Builder<ServiceMethod> methods = ImmutableList.builder(); for (FunctionElement functionElement : element.functions()) { ServiceMethod method = new ServiceMethod(functionElement, fieldNamingPolicy); methods.add(method); } this.methods = methods.build(); ImmutableMap.Builder<String, String> annotationBuilder = ImmutableMap.builder(); AnnotationElement anno = element.annotations(); if (anno != null) { annotationBuilder.putAll(anno.values()); } this.annotations = annotationBuilder.build(); } private Service(Builder builder) { super(builder.element.name(), builder.namespaces); this.element = builder.element; this.methods = builder.methods; this.type = builder.type; this.annotations = builder.annotations; this.extendsService = builder.extendsService; } @Override public ThriftType type() { return type; } public String documentation() { return element.documentation(); } @Override public Location location() { return element.location(); } public ImmutableList<ServiceMethod> methods() { return methods; } public ThriftType extendsService() { return extendsService; } public ImmutableMap<String, String> annotations() { return annotations; } public Builder toBuilder() { return new Builder(element, methods, type, annotations, namespaces(), extendsService); } public static final class Builder { private ServiceElement element; private ImmutableList<ServiceMethod> methods; private ThriftType type; private ImmutableMap<String, String> annotations; private Map<NamespaceScope, String> namespaces; private ThriftType extendsService; Builder(ServiceElement element, ImmutableList<ServiceMethod> methods, ThriftType type, ImmutableMap<String, String> annotations, Map<NamespaceScope, String> namespaces, ThriftType extendsService) { this.element = element; this.methods = methods; this.type = type; this.annotations = annotations; this.namespaces = namespaces; this.extendsService = extendsService; } public Builder element(ServiceElement element) { if (element == null) { throw new NullPointerException("element may not be null"); } this.element = element; return this; } public Builder methods(ImmutableList<ServiceMethod> methods) { if (methods == null) { throw new NullPointerException("methods may not be null"); } this.methods = methods; return this; } public Builder type(ThriftType type) { this.type = type; return this; } public Builder annotations(ImmutableMap<String, String> annotations) { this.annotations = annotations; return this; } public Builder namespaces(Map<NamespaceScope, String> namespaces) { Map<NamespaceScope, String> immutableNamespaces = namespaces; if (!(immutableNamespaces instanceof ImmutableMap)) { immutableNamespaces = ImmutableMap.copyOf(namespaces); } this.namespaces = immutableNamespaces; return this; } public Builder extendsService(ThriftType extendsService) { this.extendsService = extendsService; return this; } public Service build() { return new Service(this); } } @Override public boolean isDeprecated() { return super.isDeprecated() || annotations.containsKey("deprecated") || annotations.containsKey("thrifty.deprecated"); } void link(Linker linker) { TypeElement extendsType = element.extendsService(); if (extendsType != null) { extendsService = linker.resolveType(extendsType); // TODO: Validate that this is actually a service type } for (ServiceMethod method : methods) { method.link(linker); } } void validate(Linker linker) { // Validate the following properties: // 1. If the service extends a type, that the type is itself a service // 2. The service contains no duplicate methods, including those inherited from base types. // 3. All service methods themselves are valid. Map<String, ServiceMethod> methodsByName = new LinkedHashMap<>(); Deque<Service> hierarchy = new ArrayDeque<>(); if (extendsService != null) { Named named = linker.lookupSymbol(extendsService()); if (!(named instanceof Service)) { linker.addError(location(), "Base type '" + extendsService.name() + "' is not a service"); } } // Assume base services have already been validated ThriftType baseType = extendsService; while (baseType != null) { Named named = linker.lookupSymbol(baseType); if (!(named instanceof Service)) { break; } Service svc = (Service) named; hierarchy.add(svc); baseType = svc.extendsService; } while (!hierarchy.isEmpty()) { // Process from most- to least-derived services; that way, if there // is a name conflict, we'll report the conflict with the least-derived // class. Service svc = hierarchy.remove(); for (ServiceMethod serviceMethod : svc.methods()) { // Add the base-type method names to the map. In this case, // we don't care about duplicates because the base types have // already been validated and we have already reported that error. methodsByName.put(serviceMethod.name(), serviceMethod); } } for (ServiceMethod method : methods) { ServiceMethod conflictingMethod = methodsByName.put(method.name(), method); if (conflictingMethod != null) { methodsByName.put(conflictingMethod.name(), conflictingMethod); linker.addError(method.location(), "Duplicate method; '" + method.name() + "' conflicts with another method declared at " + conflictingMethod.location()); } } for (ServiceMethod method : methods) { method.validate(linker); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Service service = (Service) o; if (!element.equals(service.element)) { return false; } if (!methods.equals(service.methods)) { return false; } if (type != null ? !type.equals(service.type) : service.type != null) { return false; } if (annotations != null ? !annotations.equals(service.annotations) : service.annotations != null) { return false; } return extendsService != null ? extendsService.equals(service.extendsService) : service.extendsService == null; } @Override public int hashCode() { int result = element.hashCode(); result = 31 * result + methods.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (annotations != null ? annotations.hashCode() : 0); result = 31 * result + (extendsService != null ? extendsService.hashCode() : 0); return result; } }
true