blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6e50b51d6f07657fd253501db2f23143483caa17 | 8,641,474,259,034 | 6db99a38675c4e6e72e3ad514e33c25abaed20fc | /CSE305Project/src/java/servlets/userLoginServlet.java | 286537a423c51795021f6e131f38ad883ebeabad | [] | no_license | conor-beck2/Mazon-Ecommerce-Site | https://github.com/conor-beck2/Mazon-Ecommerce-Site | 2cf9c7bf35309d1522a09f7db0d47d5d4847532d | ab44d547dc55a385b06126826b73de1672d4fdd5 | refs/heads/master | 2021-09-03T12:33:02.050000 | 2018-01-09T03:40:55 | 2018-01-09T03:40:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 servlets;
import beans.customerBean;
import beans.itemBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Conor
*/
public class userLoginServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
String customerEmail = request.getParameter("username");
String password = request.getParameter("password");
String query;
String passwordCheck = new String();
int id = 0;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Connection co = null;
try {
co = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "password");
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stat = co.createStatement();
query = "SELECT email, password FROM customer WHERE (email = '" + customerEmail + "' AND password = '" + password + "');";
try {
ResultSet result = stat.executeQuery(query) ;
while (result.next()) {
passwordCheck = result.getString("password");
}
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
if (passwordCheck != null && passwordCheck.equals(password)) {
customerBean customer = new customerBean();
String dataQuery = "SELECT * FROM customer WHERE (email = '" + customerEmail + "' AND password = '" + password + "');";
try {
ResultSet result = stat.executeQuery(dataQuery) ;
while (result.next()) {
id = result.getInt("customerID");
customer.setId(id);
customer.setEmail(customerEmail);
customer.setPassword(password);
customer.setFirstName(result.getString("firstName"));
customer.setLastName(result.getString("lastName"));
customer.setPhoneNumber(result.getString("phoneNum"));
customer.setZipCode(result.getInt("zipCode"));
customer.setAddress(result.getString("address"));
customer.setTown(result.getString("town"));
}
//System.out.println("yo");
//System.out.println(customer.getTown());
session.setAttribute("customer", customer);
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
dataQuery = "SELECT * FROM inventory;";
// itemBean items = new itemBean();
ArrayList<itemBean> items = new ArrayList();
try{
ResultSet result = stat.executeQuery(dataQuery);
while(result.next()) {
itemBean item = new itemBean();
item.setId(result.getInt("itemID"));
item.setName(result.getString("name"));
item.setPrice(result.getDouble("price"));
item.setCategory(result.getString("category"));
item.setSeller(result.getString("seller"));
item.setDescription(result.getString("description"));
items.add(item);
}
session.setAttribute("items", items);
}
catch (SQLException ex){
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
query = "SELECT * FROM cart WHERE customerID = '" + Integer.toString(id)+"';";
ArrayList<Integer> idList = new ArrayList();
ArrayList<itemBean> cart = new ArrayList();
ArrayList<Integer> quan = new ArrayList();
try {
ResultSet result = stat.executeQuery(query) ;
while (result.next()) {
idList.add(result.getInt("itemID"));
quan.add(result.getInt("quantity"));
}
for(int i = 0; i < idList.size(); i++){
int index = idList.get(i);
String str = Integer.toString(index);
query = "SELECT * FROM inventory WHERE itemID = " + str +";";
ResultSet res = stat.executeQuery(query);
while (res.next()) {
itemBean it = new itemBean();
it.setName(res.getString("name"));
it.setId(res.getInt("itemID"));
it.setCategory(res.getString("category"));
it.setPrice(res.getDouble("price"));
it.setSeller(res.getString("seller"));
it.setDescription(res.getString("description"));
it.setQuantity(quan.get(i));
cart.add(it);
}
}
session.setAttribute("cart", cart);
double total = 0;
int times = 0;
for(int i = 0; i < cart.size(); i++){
times = cart.get(i).getQuantity();
total = total + (cart.get(i).getPrice() * times);
}
session.setAttribute("total", total);
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
catch (SQLException ex){
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
RequestDispatcher jsp = request.getRequestDispatcher("loggedIn.jsp");
jsp.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| UTF-8 | Java | 8,763 | java | userLoginServlet.java | Java | [
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author Conor\n */\npublic class userLoginServlet extends HttpServ",
"end": 820,
"score": 0.8343454003334045,
"start": 815,
"tag": "NAME",
"value": "Conor"
},
{
"context": " String customerEmail = request.getParameter(\... | null | [] | /*
* 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 servlets;
import beans.customerBean;
import beans.itemBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Conor
*/
public class userLoginServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
String customerEmail = request.getParameter("username");
String password = request.getParameter("password");
String query;
String passwordCheck = new String();
int id = 0;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Connection co = null;
try {
co = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "password");
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stat = co.createStatement();
query = "SELECT email, password FROM customer WHERE (email = '" + customerEmail + "' AND password = '" + password + "');";
try {
ResultSet result = stat.executeQuery(query) ;
while (result.next()) {
passwordCheck = result.getString("password");
}
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
if (passwordCheck != null && passwordCheck.equals(password)) {
customerBean customer = new customerBean();
String dataQuery = "SELECT * FROM customer WHERE (email = '" + customerEmail + "' AND password = '" + password + "');";
try {
ResultSet result = stat.executeQuery(dataQuery) ;
while (result.next()) {
id = result.getInt("customerID");
customer.setId(id);
customer.setEmail(customerEmail);
customer.setPassword(<PASSWORD>);
customer.setFirstName(result.getString("firstName"));
customer.setLastName(result.getString("lastName"));
customer.setPhoneNumber(result.getString("phoneNum"));
customer.setZipCode(result.getInt("zipCode"));
customer.setAddress(result.getString("address"));
customer.setTown(result.getString("town"));
}
//System.out.println("yo");
//System.out.println(customer.getTown());
session.setAttribute("customer", customer);
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
dataQuery = "SELECT * FROM inventory;";
// itemBean items = new itemBean();
ArrayList<itemBean> items = new ArrayList();
try{
ResultSet result = stat.executeQuery(dataQuery);
while(result.next()) {
itemBean item = new itemBean();
item.setId(result.getInt("itemID"));
item.setName(result.getString("name"));
item.setPrice(result.getDouble("price"));
item.setCategory(result.getString("category"));
item.setSeller(result.getString("seller"));
item.setDescription(result.getString("description"));
items.add(item);
}
session.setAttribute("items", items);
}
catch (SQLException ex){
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
query = "SELECT * FROM cart WHERE customerID = '" + Integer.toString(id)+"';";
ArrayList<Integer> idList = new ArrayList();
ArrayList<itemBean> cart = new ArrayList();
ArrayList<Integer> quan = new ArrayList();
try {
ResultSet result = stat.executeQuery(query) ;
while (result.next()) {
idList.add(result.getInt("itemID"));
quan.add(result.getInt("quantity"));
}
for(int i = 0; i < idList.size(); i++){
int index = idList.get(i);
String str = Integer.toString(index);
query = "SELECT * FROM inventory WHERE itemID = " + str +";";
ResultSet res = stat.executeQuery(query);
while (res.next()) {
itemBean it = new itemBean();
it.setName(res.getString("name"));
it.setId(res.getInt("itemID"));
it.setCategory(res.getString("category"));
it.setPrice(res.getDouble("price"));
it.setSeller(res.getString("seller"));
it.setDescription(res.getString("description"));
it.setQuantity(quan.get(i));
cart.add(it);
}
}
session.setAttribute("cart", cart);
double total = 0;
int times = 0;
for(int i = 0; i < cart.size(); i++){
times = cart.get(i).getQuantity();
total = total + (cart.get(i).getPrice() * times);
}
session.setAttribute("total", total);
}
catch (SQLException ex) {
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
catch (SQLException ex){
Logger.getLogger(userLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
RequestDispatcher jsp = request.getRequestDispatcher("loggedIn.jsp");
jsp.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 8,765 | 0.559283 | 0.558142 | 213 | 40.140846 | 27.208445 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671362 | false | false | 13 |
46b01657e0e636aaf3bff10e4579d540bf08bd45 | 37,108,517,455,215 | 882e77219bce59ae57cbad7e9606507b34eebfcf | /mi2s_securitycenter_miui12/src/main/java/com/miui/appmanager/c/a.java | 13e7b91b57dd0eaf8b08e65124a38cf742c19b90 | [] | no_license | CrackerCat/XiaomiFramework | https://github.com/CrackerCat/XiaomiFramework | 17a12c1752296fa1a52f61b83ecf165f328f4523 | 0b7952df317dac02ebd1feea7507afb789cef2e3 | refs/heads/master | 2022-06-12T03:30:33.285000 | 2020-05-06T11:30:54 | 2020-05-06T11:30:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.miui.appmanager.c;
import com.miui.appmanager.AppManagerMainActivity;
class a implements Runnable {
/* renamed from: a reason: collision with root package name */
final /* synthetic */ AppManagerMainActivity f3618a;
a(AppManagerMainActivity appManagerMainActivity) {
this.f3618a = appManagerMainActivity;
}
public void run() {
this.f3618a.n();
}
}
| UTF-8 | Java | 406 | java | a.java | Java | [] | null | [] | package com.miui.appmanager.c;
import com.miui.appmanager.AppManagerMainActivity;
class a implements Runnable {
/* renamed from: a reason: collision with root package name */
final /* synthetic */ AppManagerMainActivity f3618a;
a(AppManagerMainActivity appManagerMainActivity) {
this.f3618a = appManagerMainActivity;
}
public void run() {
this.f3618a.n();
}
}
| 406 | 0.697044 | 0.667488 | 17 | 22.882353 | 23.087767 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 13 |
22995db325944cf64598c1ec73e3d64a23b04227 | 37,761,352,485,842 | 47a9f8ee286e6907d000d1f4bcf5857bcc68a34c | /generator/src/main/java/de/kibr/ega/generator/GraphGenerator.java | ae7af361f3ef284c23b6ec8db735f9dee8a9789f | [] | no_license | Iavra/effiziente-graphenalgorithmen | https://github.com/Iavra/effiziente-graphenalgorithmen | 61400eb7e20b59bc26c4207de3f8c4f9cf4240db | cf46ac2f2006e1760fa426c93be437fd0dc742b0 | refs/heads/master | 2020-04-01T14:24:50.126000 | 2018-10-21T11:18:56 | 2018-10-21T11:18:56 | 153,293,297 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.kibr.ega.generator;
import de.kibr.ega.generator.capacity.CapacityGenerator;
import de.kibr.ega.generator.edge.EdgeGenerator;
import de.kibr.ega.generator.node.NodeGenerator;
import de.kibr.ega.graph.Graph;
import de.kibr.ega.graph.GraphEdge;
import de.kibr.ega.graph.GraphNode;
import java.util.List;
import java.util.stream.Collectors;
public class GraphGenerator {
private final NodeGenerator nodeGenerator;
private final EdgeGenerator edgeGenerator;
private final CapacityGenerator capacityGenerator;
public GraphGenerator(NodeGenerator nodeGenerator, EdgeGenerator edgeGenerator, CapacityGenerator capacityGenerator) {
this.nodeGenerator = nodeGenerator;
this.edgeGenerator = edgeGenerator;
this.capacityGenerator = capacityGenerator;
}
public Graph generateGraph(int size) {
if (size < 0) throw new IllegalArgumentException("size must be non-negative");
List<GraphNode> nodes = nodeGenerator.generateNodes(size);
List<GraphEdge> edges = edgeGenerator.generateEdges(nodes);
edges.addAll(edges.stream().map(GraphEdge::flip).collect(Collectors.toList()));
// TODO determine start/sink
Graph graph = new Graph(nodes, edges);
capacityGenerator.setCapacities(graph);
return graph;
}
}
| UTF-8 | Java | 1,317 | java | GraphGenerator.java | Java | [] | null | [] | package de.kibr.ega.generator;
import de.kibr.ega.generator.capacity.CapacityGenerator;
import de.kibr.ega.generator.edge.EdgeGenerator;
import de.kibr.ega.generator.node.NodeGenerator;
import de.kibr.ega.graph.Graph;
import de.kibr.ega.graph.GraphEdge;
import de.kibr.ega.graph.GraphNode;
import java.util.List;
import java.util.stream.Collectors;
public class GraphGenerator {
private final NodeGenerator nodeGenerator;
private final EdgeGenerator edgeGenerator;
private final CapacityGenerator capacityGenerator;
public GraphGenerator(NodeGenerator nodeGenerator, EdgeGenerator edgeGenerator, CapacityGenerator capacityGenerator) {
this.nodeGenerator = nodeGenerator;
this.edgeGenerator = edgeGenerator;
this.capacityGenerator = capacityGenerator;
}
public Graph generateGraph(int size) {
if (size < 0) throw new IllegalArgumentException("size must be non-negative");
List<GraphNode> nodes = nodeGenerator.generateNodes(size);
List<GraphEdge> edges = edgeGenerator.generateEdges(nodes);
edges.addAll(edges.stream().map(GraphEdge::flip).collect(Collectors.toList()));
// TODO determine start/sink
Graph graph = new Graph(nodes, edges);
capacityGenerator.setCapacities(graph);
return graph;
}
}
| 1,317 | 0.746393 | 0.745634 | 34 | 37.735294 | 27.764036 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735294 | false | false | 13 |
c2c1a17b12c70fea445dcab80a3c4a276fd95bbe | 23,828,478,617,442 | d6a3cc3a3c15f2d6e2e391dac0c7d0324ebd5806 | /src/test/java/io/github/zeroone3010/yahueapi/v2/HueSceneActivationTestRun.java | 2accaa484e0b8a389eca7124a8941c02d3b01a69 | [
"MIT"
] | permissive | ZeroOne3010/yetanotherhueapi | https://github.com/ZeroOne3010/yetanotherhueapi | b8f9640c58ef2f74c23dbd1e2b1c6ef15be90da4 | a37548d0dc9d714019aeffd82ca09997992883ca | refs/heads/master | 2023-07-20T04:42:58.774000 | 2023-07-19T08:06:02 | 2023-07-19T08:06:02 | 141,633,066 | 68 | 26 | MIT | false | 2023-07-19T08:06:03 | 2018-07-19T21:34:51 | 2023-07-08T22:03:33 | 2023-07-19T08:06:02 | 572 | 59 | 21 | 2 | Java | false | false | package io.github.zeroone3010.yahueapi.v2;
import java.util.List;
import java.util.Objects;
public class HueSceneActivationTestRun {
public static final String ROOM_NAME = "Kirjastohuone";
public static final String SCENE_NAME = "Crocus";
/**
* @param args IP address of the Bridge, API key
*/
public static void main(final String... args) {
if (args == null || args.length != 2) {
System.err.println("You must give two arguments: 1) the IP of the Bridge and 2) the API key.");
return;
}
final String ip = args[0];
final String apiKey = args[1];
final Hue hue = new Hue(ip, apiKey);
final List<Scene> scenes = hue.getRoomByName(ROOM_NAME).get().getScenes();
scenes.forEach(scene -> System.out.println(scene.getName()));
scenes.stream().filter(scene -> Objects.equals(scene.getName(), SCENE_NAME))
.findFirst()
.get()
.activate();
}
}
| UTF-8 | Java | 924 | java | HueSceneActivationTestRun.java | Java | [
{
"context": "package io.github.zeroone3010.yahueapi.v2;\n\nimport java.util.List;\nimport java.",
"end": 29,
"score": 0.9984973073005676,
"start": 18,
"tag": "USERNAME",
"value": "zeroone3010"
}
] | null | [] | package io.github.zeroone3010.yahueapi.v2;
import java.util.List;
import java.util.Objects;
public class HueSceneActivationTestRun {
public static final String ROOM_NAME = "Kirjastohuone";
public static final String SCENE_NAME = "Crocus";
/**
* @param args IP address of the Bridge, API key
*/
public static void main(final String... args) {
if (args == null || args.length != 2) {
System.err.println("You must give two arguments: 1) the IP of the Bridge and 2) the API key.");
return;
}
final String ip = args[0];
final String apiKey = args[1];
final Hue hue = new Hue(ip, apiKey);
final List<Scene> scenes = hue.getRoomByName(ROOM_NAME).get().getScenes();
scenes.forEach(scene -> System.out.println(scene.getName()));
scenes.stream().filter(scene -> Objects.equals(scene.getName(), SCENE_NAME))
.findFirst()
.get()
.activate();
}
}
| 924 | 0.652597 | 0.641775 | 31 | 28.806452 | 27.335926 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580645 | false | false | 13 |
542c83344351805f6e8b4aca3e7e54eedcf93bc1 | 38,817,914,454,778 | 75f35578faafe712ff94681b00de6fe62e4d5b9f | /trunk/F1LAT/src/main/java/com/pochoF1/model/ResultTeam.java | 9ab1c05f444c0e35e4c9878260cc36a5c83ea97e | [] | no_license | BGCX067/f1-drivers-data-svn-to-git | https://github.com/BGCX067/f1-drivers-data-svn-to-git | 127c169a2cb58ac407ac0daf4ed8ed14ca726840 | b6e7dc0b91700ad4c6dd64756497d4cdb540c507 | refs/heads/master | 2016-09-01T08:52:04.133000 | 2015-12-28T14:29:05 | 2015-12-28T14:29:05 | 48,834,507 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pochoF1.model;
import java.io.Serializable;
import com.pochoF1.enums.Equipos;
public class ResultTeam implements Serializable{
private static final long serialVersionUID = 1L;
private String posicion;
private Equipos equipo;
private String puntaje;
private String year;
public String equipoString;
public String equipoAbbr;
public String getPosicion() {
return posicion;
}
public void setPosicion(String posicion) {
this.posicion = posicion;
}
public Equipos getEquipo() {
return equipo;
}
public void setEquipo(Equipos equipo) {
this.equipo = equipo;
}
public String getPuntaje() {
return puntaje;
}
public void setPuntaje(String puntaje) {
this.puntaje = puntaje;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
@Override
public String toString() {
return this.posicion + " - " + this.equipo + " - " + this.puntaje;
}
public String getEquipoString() {
return equipoString;
}
public void setEquipoString(String equipoString) {
this.equipoString = equipoString;
}
public String getEquipoAbbr() {
return equipoAbbr;
}
public void setEquipoAbbr(String equipoAbbr) {
this.equipoAbbr = equipoAbbr;
}
}
| UTF-8 | Java | 1,290 | java | ResultTeam.java | Java | [] | null | [] | package com.pochoF1.model;
import java.io.Serializable;
import com.pochoF1.enums.Equipos;
public class ResultTeam implements Serializable{
private static final long serialVersionUID = 1L;
private String posicion;
private Equipos equipo;
private String puntaje;
private String year;
public String equipoString;
public String equipoAbbr;
public String getPosicion() {
return posicion;
}
public void setPosicion(String posicion) {
this.posicion = posicion;
}
public Equipos getEquipo() {
return equipo;
}
public void setEquipo(Equipos equipo) {
this.equipo = equipo;
}
public String getPuntaje() {
return puntaje;
}
public void setPuntaje(String puntaje) {
this.puntaje = puntaje;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
@Override
public String toString() {
return this.posicion + " - " + this.equipo + " - " + this.puntaje;
}
public String getEquipoString() {
return equipoString;
}
public void setEquipoString(String equipoString) {
this.equipoString = equipoString;
}
public String getEquipoAbbr() {
return equipoAbbr;
}
public void setEquipoAbbr(String equipoAbbr) {
this.equipoAbbr = equipoAbbr;
}
}
| 1,290 | 0.694574 | 0.692248 | 59 | 19.864407 | 16.610653 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.457627 | false | false | 13 |
fea191594c1103736778a74781ac40ab010a408d | 38,817,914,457,912 | d2498430e140054cb345ee4cd5936506c5a68bfe | /VMPCSImporter2Test/protosheetimporttests/vampire/editor/importer/vmpcs/application/ProtoCategoryImportTest.java | 0f8d2a5c47acf9ff39e26b463336cbfafc213a7d | [] | no_license | rexVictor/vampire-editor | https://github.com/rexVictor/vampire-editor | 6e04b24826b88d8001fec432326f397fdf24b10d | e9f0d44422a3ac9adf687543b21dd011472bf51d | refs/heads/master | 2021-01-10T05:08:26.006000 | 2014-04-08T04:51:16 | 2014-04-08T04:51:16 | 43,219,256 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vampire.editor.importer.vmpcs.application;
import static org.junit.Assert.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import vampire.editor.fileformat.vmpcs.domain.ProtoCategory;
import vampire.editor.fileformat.vmpcs.domain.ProtoSheet;
@SuppressWarnings("nls")
public class ProtoCategoryImportTest {
private List<ProtoCategory> actual;
private List<ProtoCategory> expected = new ArrayList<>();
@Before
public void setup() throws Throwable{
Path path = Paths.get("testcases", "protosheet", "protocats", "test1.json");
ProtoSheet protoSheet = ModelImporter.loadSheet(path);
actual = protoSheet.getTraits();
expected.add(new ProtoCategory(11, "attributes"));
expected.add(new ProtoCategory(12, "abilities"));
expected.add(new ProtoCategory(13, "virtues"));
}
@Test
public void testProtoCategoryImport() {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++){
assertEquals(expected.get(i), actual.get(i));
}
}
}
| UTF-8 | Java | 1,112 | java | ProtoCategoryImportTest.java | Java | [] | null | [] | package vampire.editor.importer.vmpcs.application;
import static org.junit.Assert.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import vampire.editor.fileformat.vmpcs.domain.ProtoCategory;
import vampire.editor.fileformat.vmpcs.domain.ProtoSheet;
@SuppressWarnings("nls")
public class ProtoCategoryImportTest {
private List<ProtoCategory> actual;
private List<ProtoCategory> expected = new ArrayList<>();
@Before
public void setup() throws Throwable{
Path path = Paths.get("testcases", "protosheet", "protocats", "test1.json");
ProtoSheet protoSheet = ModelImporter.loadSheet(path);
actual = protoSheet.getTraits();
expected.add(new ProtoCategory(11, "attributes"));
expected.add(new ProtoCategory(12, "abilities"));
expected.add(new ProtoCategory(13, "virtues"));
}
@Test
public void testProtoCategoryImport() {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++){
assertEquals(expected.get(i), actual.get(i));
}
}
}
| 1,112 | 0.739209 | 0.732014 | 43 | 24.860466 | 22.579659 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.511628 | false | false | 13 |
21e4e5ad0f785e3b057d44025fae504b29384c4d | 35,716,948,073,260 | 4cf8ea6bce8b1e4d8e847fc290fa5a79e49d8dd8 | /2D Gamedev API/src/com/teamanubiz/gameapi/gfx/Sprite.java | 0d12f3d667b99278b422a8ab154c001148ed0a47 | [] | no_license | TeamAnubiz/2d-gamedev-api | https://github.com/TeamAnubiz/2d-gamedev-api | be85f8326c409ce17ff22c9c8f023e4bea3914d6 | a2118bb8780966e789dc235828f6a26cba9de02d | refs/heads/master | 2016-08-03T21:56:44.170000 | 2015-03-09T19:09:03 | 2015-03-09T19:09:03 | 24,164,016 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.teamanubiz.gameapi.gfx;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import java.awt.Graphics;
public class Sprite {
private BufferedImage source;
/**
*
* Creates a Sprite object from an Image.
*
* @param src
*/
public Sprite(BufferedImage src) {
this.source = src;
}
/**
*
* Sets the source image.
*
* @param src
*/
public void setSource(BufferedImage src) {
this.source = src;
}
/**
*
* Crops the image.
*
* @param xOffset
* @param yOffset
* @param width
* @param height
*/
public void crop(int xOffset, int yOffset, int width, int height) {
BufferedImage temp = (BufferedImage) source;
temp = temp.getSubimage(xOffset, yOffset, width, height);
source = temp;
}
/**
*
* Scales the Sprite to the specified width and height.
*
* @param width
* @param height
*/
public void scale(int width, int height) {
//Graphics dbg = ((BufferedImage) source).createGraphics();
//dbg.drawImage(source, 0, 0, width, height, null);
//source.getGraphics().drawImage(source,0,0,width,height,null);
int imageWidth = source.getWidth();
int imageHeight = source.getHeight();
double scaleX = (double)width/imageWidth;
double scaleY = (double)height/imageHeight;
AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
source = bilinearScaleOp.filter(
source,
new BufferedImage(width, height, source.getType()));
//BufferedImage temp = (BufferedImage) source;
//temp.getScaledInstance(width, height, Image.SCALE_DEFAULT);
//source = temp;
}
public void rotate(int degrees) {
double rotationRequired = Math.toRadians(degrees);
double locationX = source.getWidth(null) / 2;
double locationY = source.getHeight(null) / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
op.filter((BufferedImage) source, null);
}
/**
* Returns the current instance of the Image.
*/
public BufferedImage getCurrent() {
return source;
}
}
| UTF-8 | Java | 2,465 | java | Sprite.java | Java | [] | null | [] | package com.teamanubiz.gameapi.gfx;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import java.awt.Graphics;
public class Sprite {
private BufferedImage source;
/**
*
* Creates a Sprite object from an Image.
*
* @param src
*/
public Sprite(BufferedImage src) {
this.source = src;
}
/**
*
* Sets the source image.
*
* @param src
*/
public void setSource(BufferedImage src) {
this.source = src;
}
/**
*
* Crops the image.
*
* @param xOffset
* @param yOffset
* @param width
* @param height
*/
public void crop(int xOffset, int yOffset, int width, int height) {
BufferedImage temp = (BufferedImage) source;
temp = temp.getSubimage(xOffset, yOffset, width, height);
source = temp;
}
/**
*
* Scales the Sprite to the specified width and height.
*
* @param width
* @param height
*/
public void scale(int width, int height) {
//Graphics dbg = ((BufferedImage) source).createGraphics();
//dbg.drawImage(source, 0, 0, width, height, null);
//source.getGraphics().drawImage(source,0,0,width,height,null);
int imageWidth = source.getWidth();
int imageHeight = source.getHeight();
double scaleX = (double)width/imageWidth;
double scaleY = (double)height/imageHeight;
AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
source = bilinearScaleOp.filter(
source,
new BufferedImage(width, height, source.getType()));
//BufferedImage temp = (BufferedImage) source;
//temp.getScaledInstance(width, height, Image.SCALE_DEFAULT);
//source = temp;
}
public void rotate(int degrees) {
double rotationRequired = Math.toRadians(degrees);
double locationX = source.getWidth(null) / 2;
double locationY = source.getHeight(null) / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
op.filter((BufferedImage) source, null);
}
/**
* Returns the current instance of the Image.
*/
public BufferedImage getCurrent() {
return source;
}
}
| 2,465 | 0.684787 | 0.681947 | 116 | 20.25 | 24.065956 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.689655 | false | false | 13 |
34f046f16d40653ffe41b1eeab254f96119ba457 | 38,981,123,206,568 | 3a6e6391024f229e83afdd50a016ad8ae3a92b50 | /exerciseone/src/main/java/com/exerciseone/service/StudentServiceImpl.java | 6f3ff31be9d4288f8317b6f14582fd6f83cc6d0a | [] | no_license | raulpablob68/exerciseone | https://github.com/raulpablob68/exerciseone | b1468d5ac768ef68742f276bd14d2d5954c64741 | 1432a44cd6f88d430c07c0e2c6ad789aebf72978 | refs/heads/master | 2020-05-22T21:35:12.099000 | 2019-06-01T00:18:51 | 2019-06-01T00:18:51 | 186,529,660 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exerciseone.service;
import com.exerciseone.dao.IStudentDao;
import com.exerciseone.entity.Student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements IStudentService {
@Autowired
private IStudentDao studentDao;
@Override
public Student get(int studentId) {
return studentDao.findById(studentId).get();
}
@Override
public List<Student> getAll() {
return (List<Student>) studentDao.findAll();
}
@Override
public Student post(Student student) {
return studentDao.save(student);
}
@Override
public Student put(Student student, int studentId) {
studentDao.findById(studentId).ifPresent((s) -> {
student.setStudentId(studentId);
studentDao.save(student);
});
return student;
}
@Override
public void delete(int studentId) {
studentDao.deleteById(studentId);
}
@Override
public List<Student> getAllById(List<Integer> listStudentId) {
return studentDao.getAllStudentsByStudentId(listStudentId);
}
@Override
public List<Student> getAllByClassId(int classId) {
return (List<Student>) studentDao.getAllStudentsByClassId(classId);
}
}
| UTF-8 | Java | 1,332 | java | StudentServiceImpl.java | Java | [] | null | [] | package com.exerciseone.service;
import com.exerciseone.dao.IStudentDao;
import com.exerciseone.entity.Student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements IStudentService {
@Autowired
private IStudentDao studentDao;
@Override
public Student get(int studentId) {
return studentDao.findById(studentId).get();
}
@Override
public List<Student> getAll() {
return (List<Student>) studentDao.findAll();
}
@Override
public Student post(Student student) {
return studentDao.save(student);
}
@Override
public Student put(Student student, int studentId) {
studentDao.findById(studentId).ifPresent((s) -> {
student.setStudentId(studentId);
studentDao.save(student);
});
return student;
}
@Override
public void delete(int studentId) {
studentDao.deleteById(studentId);
}
@Override
public List<Student> getAllById(List<Integer> listStudentId) {
return studentDao.getAllStudentsByStudentId(listStudentId);
}
@Override
public List<Student> getAllByClassId(int classId) {
return (List<Student>) studentDao.getAllStudentsByClassId(classId);
}
}
| 1,332 | 0.708709 | 0.708709 | 56 | 21.785715 | 21.883389 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 13 |
710feda525566d4dbf80e818667747e64fdef5f7 | 32,315,334,000,337 | 7cf40bb0d60adbe9aded76ee7b59a959590cc290 | /src/leetcode/StringShift.java | 8a88b2535dcb8f725b0a86d692717bca216501ef | [] | no_license | nikhil121101/java-dsa | https://github.com/nikhil121101/java-dsa | f08e5c4381818abbad590ef965a5b5a0a7bb0c10 | 1ab55b748eeb1d505821d0c81f749b1d8e005f3a | refs/heads/master | 2023-04-18T11:01:44.816000 | 2021-05-07T05:47:32 | 2021-05-07T05:47:32 | 305,587,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
public class StringShift {
public static String stringShift(String s, int[][] shift) {
String temp1 = "";
String temp2 = "";
for(int i = 0 ; i < shift.length ; i++) {
if(shift[i][0] == 0) {
temp2 = s.substring(0 , shift[i][1]);
temp1 = s.substring(shift[i][1]);
s = temp1 + temp2;
}
else {
temp2 = s.substring(0 , s.length() - shift[i][1]);
temp1 = s.substring(s.length() - shift[i][1]);
s = temp1 + temp2;
}
}
return s;
}
public static void main(String args[]) {
String s = "abcdefg";
int a[][] = {{1,1},{1,1},{0,2},{1,3}};
System.out.println(stringShift(s , a));
}
}
| UTF-8 | Java | 815 | java | StringShift.java | Java | [] | null | [] | package leetcode;
public class StringShift {
public static String stringShift(String s, int[][] shift) {
String temp1 = "";
String temp2 = "";
for(int i = 0 ; i < shift.length ; i++) {
if(shift[i][0] == 0) {
temp2 = s.substring(0 , shift[i][1]);
temp1 = s.substring(shift[i][1]);
s = temp1 + temp2;
}
else {
temp2 = s.substring(0 , s.length() - shift[i][1]);
temp1 = s.substring(s.length() - shift[i][1]);
s = temp1 + temp2;
}
}
return s;
}
public static void main(String args[]) {
String s = "abcdefg";
int a[][] = {{1,1},{1,1},{0,2},{1,3}};
System.out.println(stringShift(s , a));
}
}
| 815 | 0.43681 | 0.403681 | 29 | 27.103449 | 20.717051 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.896552 | false | false | 13 |
904095dbd2bbf1ea2d30230b0608c0623e8e13ca | 5,360,119,216,269 | de2ee12ef60e82b50a34bec4cc22e3fbf9118299 | /Project/src/com/ciccFramework/gui/MatrixGeneratorInterface.java | 9d1fa198426132987bac245bb0259892a1919443 | [] | no_license | justinmaltese/ciccframework | https://github.com/justinmaltese/ciccframework | 44fb94981adfaf215e0d5764b476e85ffb6b3f2e | d40c0d5eda0690a830ab483f763ac82cf82dd940 | refs/heads/master | 2021-01-21T22:19:43.834000 | 2018-04-02T02:33:56 | 2018-04-02T02:33:56 | 92,325,544 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ciccFramework.gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTabbedPane;
import com.ciccFramework.algorithms.ga.GeneticAlgorithm;
import com.ciccFramework.compatibility.BinaryCompatibilityChecker;
import com.ciccFramework.compatibility.CompatibilityChecker;
import com.ciccFramework.compatibility.QaryCompatibilityChecker;
import com.ciccFramework.compatibility.matrix.CompatibilityMatrixGenerator;
import com.ciccFramework.core.ExecutionHandler;
import com.ciccFramework.core.ParameterSet;
import com.ciccFramework.core.CoveringProblem;
import com.ciccFramework.io.CodeWriter;
import com.ciccFramework.schema.AlgorithmSchema;
import com.ciccFramework.schema.XMLSchemaLoader;
import java.awt.Component;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JCheckBox;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import java.awt.ScrollPane;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
/* This class serves as a graphical user interface for compatibility matrix generation
* purposes. A user first selects a maximum value for q,n and r. Then, compatibility matrices
* are generated sequentially as .matrix files until the maximum parameter values are reached.
*
*
* NOTE: Portions of this class were generated using the WindowBuilder WYSIWYG editor for eclipse.
*
* @author Justin Maltese
* @date 04/10/2016
* @version 1.0
*/
public class MatrixGeneratorInterface {
// GUI elements accessible globally
private JFrame frame;
private TextArea runTextArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MatrixGeneratorInterface window = new MatrixGeneratorInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MatrixGeneratorInterface() {
initialize();
}
/* This method is responsible for initializating all components of the GUI */
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 786, 430);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.getContentPane().add(panel, BorderLayout.CENTER);
JLabel lblCodeParameters = new JLabel("Compatibility Matrix Generator");
lblCodeParameters.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblCodeParameters.setBounds(235, 9, 340, 26);
panel.add(lblCodeParameters);
JLabel lblQ = new JLabel("Q:");
lblQ.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblQ.setBounds(65, 105, 40, 25);
panel.add(lblQ);
JLabel lblProblemParameters = new JLabel("Select Maximum Parameters");
lblProblemParameters.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblProblemParameters.setBounds(10, 74, 200, 26);
panel.add(lblProblemParameters);
JLabel lblN = new JLabel("N:");
lblN.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblN.setBounds(65, 150, 40, 25);
panel.add(lblN);
JLabel lblR = new JLabel("R:");
lblR.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblR.setBounds(65, 195, 40, 25);
panel.add(lblR);
final JTextField qText = new JTextField();
qText.setText("4");
qText.setBounds(95, 110, 35, 20);
panel.add(qText);
qText.setColumns(10);
final JTextField nText = new JTextField();
nText.setText("8");
nText.setColumns(10);
nText.setBounds(95, 155, 35, 20);
panel.add(nText);
final JTextField rText = new JTextField();
rText.setText("8");
rText.setColumns(10);
rText.setBounds(95, 200, 35, 20);
panel.add(rText);
runTextArea = new TextArea();
runTextArea.setBounds(210, 55, 520, 205);
panel.add(runTextArea);
final JButton startBtn = new JButton("Start");
startBtn.addActionListener(new ActionListener() {
/* Called when the start button is pressed, this method parses all required
* values from the current form. If all values are valid, a CompatibilityMatrixGenerator
* is used to batch create compatibility matrices.
*
* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
int q;
int n;
int r;
try {
q = Integer.parseInt(qText.getText());
n = Integer.parseInt(nText.getText());
r = Integer.parseInt(rText.getText());
redirectOutputToGUI();
startBtn.setEnabled(false);
new Thread(new CompatibilityMatrixGenerator(q,n,r)).start();
} catch (NumberFormatException E) {
String errorText = "Error: Must have valid integer values for all textboxs!";
JOptionPane.showMessageDialog(null, errorText);
}
}
});
startBtn.setBounds(436, 277, 89, 23);
panel.add(startBtn);
}
/* Appends a string to the text area which is designated for
* all program output.
*/
private void appendToTextArea(final String str) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runTextArea.append(str);
}
});
}
/* This method redirects standard output and error streams to a
* textarea within the GUI.
*/
private void redirectOutputToGUI() {
OutputStream outStream = new OutputStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
appendToTextArea(new String(b, off, len));
}
@Override
public void write(int b) throws IOException {
appendToTextArea(String.valueOf((char) b));
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(outStream, true));
System.setErr(new PrintStream(outStream, true));
}
}
| UTF-8 | Java | 6,787 | java | MatrixGeneratorInterface.java | Java | [
{
"context": "uilder WYSIWYG editor for eclipse.\n * \n * @author Justin Maltese\n * @date 04/10/2016\n * @version 1.0\n */\n\npublic c",
"end": 2170,
"score": 0.9998559951782227,
"start": 2156,
"tag": "NAME",
"value": "Justin Maltese"
}
] | null | [] | package com.ciccFramework.gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTabbedPane;
import com.ciccFramework.algorithms.ga.GeneticAlgorithm;
import com.ciccFramework.compatibility.BinaryCompatibilityChecker;
import com.ciccFramework.compatibility.CompatibilityChecker;
import com.ciccFramework.compatibility.QaryCompatibilityChecker;
import com.ciccFramework.compatibility.matrix.CompatibilityMatrixGenerator;
import com.ciccFramework.core.ExecutionHandler;
import com.ciccFramework.core.ParameterSet;
import com.ciccFramework.core.CoveringProblem;
import com.ciccFramework.io.CodeWriter;
import com.ciccFramework.schema.AlgorithmSchema;
import com.ciccFramework.schema.XMLSchemaLoader;
import java.awt.Component;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JCheckBox;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import java.awt.ScrollPane;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
/* This class serves as a graphical user interface for compatibility matrix generation
* purposes. A user first selects a maximum value for q,n and r. Then, compatibility matrices
* are generated sequentially as .matrix files until the maximum parameter values are reached.
*
*
* NOTE: Portions of this class were generated using the WindowBuilder WYSIWYG editor for eclipse.
*
* @author <NAME>
* @date 04/10/2016
* @version 1.0
*/
public class MatrixGeneratorInterface {
// GUI elements accessible globally
private JFrame frame;
private TextArea runTextArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MatrixGeneratorInterface window = new MatrixGeneratorInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MatrixGeneratorInterface() {
initialize();
}
/* This method is responsible for initializating all components of the GUI */
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 786, 430);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.getContentPane().add(panel, BorderLayout.CENTER);
JLabel lblCodeParameters = new JLabel("Compatibility Matrix Generator");
lblCodeParameters.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblCodeParameters.setBounds(235, 9, 340, 26);
panel.add(lblCodeParameters);
JLabel lblQ = new JLabel("Q:");
lblQ.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblQ.setBounds(65, 105, 40, 25);
panel.add(lblQ);
JLabel lblProblemParameters = new JLabel("Select Maximum Parameters");
lblProblemParameters.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblProblemParameters.setBounds(10, 74, 200, 26);
panel.add(lblProblemParameters);
JLabel lblN = new JLabel("N:");
lblN.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblN.setBounds(65, 150, 40, 25);
panel.add(lblN);
JLabel lblR = new JLabel("R:");
lblR.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblR.setBounds(65, 195, 40, 25);
panel.add(lblR);
final JTextField qText = new JTextField();
qText.setText("4");
qText.setBounds(95, 110, 35, 20);
panel.add(qText);
qText.setColumns(10);
final JTextField nText = new JTextField();
nText.setText("8");
nText.setColumns(10);
nText.setBounds(95, 155, 35, 20);
panel.add(nText);
final JTextField rText = new JTextField();
rText.setText("8");
rText.setColumns(10);
rText.setBounds(95, 200, 35, 20);
panel.add(rText);
runTextArea = new TextArea();
runTextArea.setBounds(210, 55, 520, 205);
panel.add(runTextArea);
final JButton startBtn = new JButton("Start");
startBtn.addActionListener(new ActionListener() {
/* Called when the start button is pressed, this method parses all required
* values from the current form. If all values are valid, a CompatibilityMatrixGenerator
* is used to batch create compatibility matrices.
*
* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
int q;
int n;
int r;
try {
q = Integer.parseInt(qText.getText());
n = Integer.parseInt(nText.getText());
r = Integer.parseInt(rText.getText());
redirectOutputToGUI();
startBtn.setEnabled(false);
new Thread(new CompatibilityMatrixGenerator(q,n,r)).start();
} catch (NumberFormatException E) {
String errorText = "Error: Must have valid integer values for all textboxs!";
JOptionPane.showMessageDialog(null, errorText);
}
}
});
startBtn.setBounds(436, 277, 89, 23);
panel.add(startBtn);
}
/* Appends a string to the text area which is designated for
* all program output.
*/
private void appendToTextArea(final String str) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runTextArea.append(str);
}
});
}
/* This method redirects standard output and error streams to a
* textarea within the GUI.
*/
private void redirectOutputToGUI() {
OutputStream outStream = new OutputStream() {
@Override
public void write(byte[] b, int off, int len) throws IOException {
appendToTextArea(new String(b, off, len));
}
@Override
public void write(int b) throws IOException {
appendToTextArea(String.valueOf((char) b));
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(outStream, true));
System.setErr(new PrintStream(outStream, true));
}
}
| 6,779 | 0.703256 | 0.683365 | 231 | 28.380953 | 22.766504 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.095238 | false | false | 13 |
5d9e4d253037757e065f5bcf177f3ec709a5def6 | 33,492,155,004,501 | 5b7c4912b5dd05475dc7034a0a4e4a9a3b3dc246 | /todo1-kardex-store/src/main/java/com/todo1/app/model/entity/Cliente.java | da850cc461313113b7b34440c2c3fc57d155f850 | [] | no_license | gaboegui/todo1-kardex-store | https://github.com/gaboegui/todo1-kardex-store | 2870fe5f7310f40a94800c8d22ca611fef06c0d2 | c0e839607a74cf9e35d9432ba442eb89914724ec | refs/heads/main | 2023-03-06T08:48:10.671000 | 2021-02-15T16:55:13 | 2021-02-15T16:55:13 | 338,893,257 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.todo1.app.model.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.CreditCardNumber;
import org.springframework.format.annotation.DateTimeFormat;
/**
* Entidad de persistencia para los Clientes/Usuarios
*
* @author Gabriel E.
*
*/
@Entity
@Table(name = "clientes")
public class Cliente implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 50)
@NotEmpty
@Size(min = 4, max = 49)
private String nombre;
@Column(length = 50)
@NotEmpty
@Size(min = 4, max = 50)
private String apellido;
@NotEmpty
@Column(unique = true, length = 74)
private String username;
@NotEmpty
@Size(min = 8)
@Column(length = 60)
private String password;
@Column(columnDefinition = "boolean default true")
private Boolean enabled;
@Transient
@CreditCardNumber
private String tarjetaCredito;
private String tarjetaCreditoEncriptada;
@Pattern(regexp = "[0-9]{2}[/][0-9]{2}")
private String fechaCaducidad;
@NotEmpty
@Size(min = 3)
@Pattern(regexp = "[0-9]{3}")
private String codigoSeguridadTarjeta;
@NotEmpty
@Email
private String email;
private String foto;
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date creadoEn;
@OneToMany(mappedBy = "cliente", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Factura> facturas;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "usuarios_roles",
joinColumns = @JoinColumn(name ="user_id" ),
inverseJoinColumns = @JoinColumn(name ="role_id" ),
uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id","role_id"})})
private List<Role> roles;
private static final long serialVersionUID = 1L;
@PrePersist
public void prePersist() {
creadoEn = new Date();
foto = new String();
}
// extra apara añadir de una en una
public void addFactura(Factura factura) {
facturas.add(factura);
}
// inicializo con el constructor la lista
public Cliente() {
facturas = new ArrayList<Factura>();
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreadoEn() {
return creadoEn;
}
public void setCreadoEn(Date creadoEn) {
this.creadoEn = creadoEn;
}
public List<Factura> getFacturas() {
return facturas;
}
public void setFacturas(List<Factura> facturas) {
this.facturas = facturas;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
public String getFechaCaducidad() {
return fechaCaducidad;
}
public void setFechaCaducidad(String fechaCaducidad) {
this.fechaCaducidad = fechaCaducidad;
}
public String getCodigoSeguridadTarjeta() {
return codigoSeguridadTarjeta;
}
public void setCodigoSeguridadTarjeta(String codigoSeguridadTarjeta) {
this.codigoSeguridadTarjeta = codigoSeguridadTarjeta;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTarjetaCredito() {
return tarjetaCredito;
}
public void setTarjetaCredito(String tarjetaCredito) {
this.tarjetaCredito = tarjetaCredito;
}
public String getTarjetaCreditoEncriptada() {
return tarjetaCreditoEncriptada;
}
public void setTarjetaCreditoEncriptada(String tarjetaCreditoEncriptada) {
this.tarjetaCreditoEncriptada = tarjetaCreditoEncriptada;
}
@Override
public String toString() {
return nombre + " " + apellido;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
}
| UTF-8 | Java | 5,136 | java | Cliente.java | Java | [
{
"context": "istencia para los Clientes/Usuarios\n * \n * @author Gabriel E. \n *\n */\n@Entity\n@Table(name = \"clientes\")\npublic ",
"end": 1142,
"score": 0.9327241778373718,
"start": 1133,
"tag": "NAME",
"value": "Gabriel E"
},
{
"context": "d setPassword(String password) {\n\t\... | null | [] | package com.todo1.app.model.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.CreditCardNumber;
import org.springframework.format.annotation.DateTimeFormat;
/**
* Entidad de persistencia para los Clientes/Usuarios
*
* @author <NAME>.
*
*/
@Entity
@Table(name = "clientes")
public class Cliente implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 50)
@NotEmpty
@Size(min = 4, max = 49)
private String nombre;
@Column(length = 50)
@NotEmpty
@Size(min = 4, max = 50)
private String apellido;
@NotEmpty
@Column(unique = true, length = 74)
private String username;
@NotEmpty
@Size(min = 8)
@Column(length = 60)
private String password;
@Column(columnDefinition = "boolean default true")
private Boolean enabled;
@Transient
@CreditCardNumber
private String tarjetaCredito;
private String tarjetaCreditoEncriptada;
@Pattern(regexp = "[0-9]{2}[/][0-9]{2}")
private String fechaCaducidad;
@NotEmpty
@Size(min = 3)
@Pattern(regexp = "[0-9]{3}")
private String codigoSeguridadTarjeta;
@NotEmpty
@Email
private String email;
private String foto;
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date creadoEn;
@OneToMany(mappedBy = "cliente", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Factura> facturas;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "usuarios_roles",
joinColumns = @JoinColumn(name ="user_id" ),
inverseJoinColumns = @JoinColumn(name ="role_id" ),
uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id","role_id"})})
private List<Role> roles;
private static final long serialVersionUID = 1L;
@PrePersist
public void prePersist() {
creadoEn = new Date();
foto = new String();
}
// extra apara añadir de una en una
public void addFactura(Factura factura) {
facturas.add(factura);
}
// inicializo con el constructor la lista
public Cliente() {
facturas = new ArrayList<Factura>();
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreadoEn() {
return creadoEn;
}
public void setCreadoEn(Date creadoEn) {
this.creadoEn = creadoEn;
}
public List<Factura> getFacturas() {
return facturas;
}
public void setFacturas(List<Factura> facturas) {
this.facturas = facturas;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
public String getFechaCaducidad() {
return fechaCaducidad;
}
public void setFechaCaducidad(String fechaCaducidad) {
this.fechaCaducidad = fechaCaducidad;
}
public String getCodigoSeguridadTarjeta() {
return codigoSeguridadTarjeta;
}
public void setCodigoSeguridadTarjeta(String codigoSeguridadTarjeta) {
this.codigoSeguridadTarjeta = codigoSeguridadTarjeta;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getTarjetaCredito() {
return tarjetaCredito;
}
public void setTarjetaCredito(String tarjetaCredito) {
this.tarjetaCredito = tarjetaCredito;
}
public String getTarjetaCreditoEncriptada() {
return tarjetaCreditoEncriptada;
}
public void setTarjetaCreditoEncriptada(String tarjetaCreditoEncriptada) {
this.tarjetaCreditoEncriptada = tarjetaCreditoEncriptada;
}
@Override
public String toString() {
return nombre + " " + apellido;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
}
| 5,135 | 0.742356 | 0.737098 | 248 | 19.705645 | 18.92318 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.169355 | false | false | 13 |
fb45f2ed1725e426c8ad184eac1a4b63aeb55ed1 | 7,782,480,768,480 | cab07cb930e4c487d12f0197d5818048023fd88c | /graphene/src/main/java/com/graphene/web/controller/forgotPsw/ForgotPswForm.java | 2523165e49fc28d3f9fc15306022c65acf5c8cb7 | [] | no_license | maidoulubiubiu/RuleIsRule | https://github.com/maidoulubiubiu/RuleIsRule | 41cca13108df1986b505d27c39877bb6c024885d | ae4c200bf885e1df1c452fef246981459a17a2a8 | refs/heads/master | 2021-01-10T07:48:39.337000 | 2014-10-14T14:22:57 | 2014-10-14T14:22:57 | 48,677,619 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.graphene.web.controller.forgotPsw;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class ForgotPswForm {
@NotEmpty @Email
private String forgotemail;
public String getForgotemail() {
return forgotemail;
}
public void setForgotemail(String forgotemail) {
this.forgotemail = forgotemail;
}
}
| UTF-8 | Java | 387 | java | ForgotPswForm.java | Java | [] | null | [] | package com.graphene.web.controller.forgotPsw;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class ForgotPswForm {
@NotEmpty @Email
private String forgotemail;
public String getForgotemail() {
return forgotemail;
}
public void setForgotemail(String forgotemail) {
this.forgotemail = forgotemail;
}
}
| 387 | 0.775194 | 0.775194 | 22 | 16.59091 | 19.135069 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 13 |
a4c6f1f1df09942ef4b4890504ef676210ac34cf | 30,262,339,594,142 | 0fdea16d95c76ada1364a3be06cdda2194290789 | /GameServer/src/gameserver/fighting/SkillEffectManager.java | c7ef68fe215631b0236f20b2d346c65580ac5872 | [] | no_license | ringofthec/server95 | https://github.com/ringofthec/server95 | bbffc006ac4d4d26a9e58c92a326fc79154902d1 | a550e11b4bdbd48d2a4d0bbff1c04e0a3e786012 | refs/heads/master | 2021-08-08T09:01:45.740000 | 2017-11-10T01:55:26 | 2017-11-10T01:55:26 | 110,184,989 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gameserver.fighting;
import gameserver.fighting.clock.OnTimeCallBack;
import gameserver.fighting.clock.TimeCallBack;
import gameserver.fighting.creature.CreatureObject;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import table.Float3;
import table.MT_Data_Skill;
import table.base.TABLE;
import table.base.TableManager;
import com.commons.util.GridPoint;
public class SkillEffectManager {
private static final Logger logger = LoggerFactory.getLogger(SkillEffectManager.class);
private FightingManager m_FightingManager;
public SkillEffectManager(FightingManager fightingManager)
{
m_FightingManager = fightingManager;
}
public void Shutdown() {
m_FightingManager = null;
}
/// <summary>
/// 技能目标类型
/// </summary>
public enum SKILL_TARGET_TYPE
{
/// <summary>
/// 一个单位
/// </summary>
CREATURE,
/// <summary>
/// 一个坐标
/// </summary>
POSITION,
}
/// <summary>
/// 技能类型
/// </summary>
public enum SKILLEFFECT_TYPE
{
/// <summary>
/// 普通攻击
/// </summary>
ATTACK,
/// <summary>
/// 普通效果 添加一个特效 只有显示 没有意义
/// </summary>
NORMAL,
/// <summary>
/// 飞行球特效
/// </summary>
FLYBALL,
}
private class EffectData
{
public CreatureObject fireCreature; //释放者
public SKILL_TARGET_TYPE targetType; //技能目标类型
public CreatureObject targetCreature; //目标
public GridPoint position; //目标坐标
public Vector2 offset; //导弹位置偏移
public MT_Data_Skill skill; //释放的技能
public Float3 val; //SKILLEFFECT 一个单元格数据
}
private IEffect CreateSkillEffect(SKILLEFFECT_TYPE Id)
{
if (Id == SKILLEFFECT_TYPE.FLYBALL || Id == SKILLEFFECT_TYPE.NORMAL)
return new FlyballEffect();
return null;
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, GridPoint position, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.POSITION, creature, null, position, Vector2.zero(), skillId);
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, GridPoint position, Vector2 offset, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.POSITION, creature, null, position, offset, skillId);
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, CreatureObject target, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.CREATURE, creature, target, GridPoint.zero(), Vector2.zero(), skillId);
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, CreatureObject target, Vector2 offset, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.CREATURE, creature, target, GridPoint.zero(), offset, skillId);
}
void fireAnimationEvent_impl(SKILL_TARGET_TYPE type, CreatureObject creature, CreatureObject target, GridPoint position, Vector2 offset, int skillId)
{
if (creature == null) return;
MT_Data_Skill skillData = TableManager.GetInstance().TableSkill().GetElement(skillId);
if (skillData == null)
{
logger.error("skill id is null {0}", skillId);
return;
}
List<Float3> animationData = skillData.SkillEvent();
for (int i = 0; i < animationData.size(); ++i)
{
Float3 val = animationData.get(i);
EffectData data = new EffectData();
data.fireCreature = creature;
data.targetType = type;
data.targetCreature = target;
data.position = position;
data.offset = offset;
data.skill = skillData;
data.val = val;
if (TABLE.IsInvalid(val.field1()) || val.field1() <= 0)
{
OnAnimationSpace(data);
}
else
{
m_FightingManager.ClockManager.addGameTimeCallBack(val.field1(), new OnTimeCallBack() {
@Override
public void run(TimeCallBack timeCallBack, Object[] args) {
((SkillEffectManager)args[0]).OnAnimationSpace((EffectData)args[1]);
}
}, this, data);
}
}
}
//动作回调 关键帧 时间回调
void OnAnimationSpace(EffectData data)
{
IEffect effect = CreateSkillEffect(SKILLEFFECT_TYPE.values()[((Float)data.val.field3()).intValue()]);
if (effect == null) return;
effect.fireEffect(m_FightingManager,((Float)data.val.field2()).intValue(), 0, data.fireCreature, data.targetType, data.targetCreature, data.position, data.offset, data.skill);
}
}
| UTF-8 | Java | 4,989 | java | SkillEffectManager.java | Java | [] | null | [] | package gameserver.fighting;
import gameserver.fighting.clock.OnTimeCallBack;
import gameserver.fighting.clock.TimeCallBack;
import gameserver.fighting.creature.CreatureObject;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import table.Float3;
import table.MT_Data_Skill;
import table.base.TABLE;
import table.base.TableManager;
import com.commons.util.GridPoint;
public class SkillEffectManager {
private static final Logger logger = LoggerFactory.getLogger(SkillEffectManager.class);
private FightingManager m_FightingManager;
public SkillEffectManager(FightingManager fightingManager)
{
m_FightingManager = fightingManager;
}
public void Shutdown() {
m_FightingManager = null;
}
/// <summary>
/// 技能目标类型
/// </summary>
public enum SKILL_TARGET_TYPE
{
/// <summary>
/// 一个单位
/// </summary>
CREATURE,
/// <summary>
/// 一个坐标
/// </summary>
POSITION,
}
/// <summary>
/// 技能类型
/// </summary>
public enum SKILLEFFECT_TYPE
{
/// <summary>
/// 普通攻击
/// </summary>
ATTACK,
/// <summary>
/// 普通效果 添加一个特效 只有显示 没有意义
/// </summary>
NORMAL,
/// <summary>
/// 飞行球特效
/// </summary>
FLYBALL,
}
private class EffectData
{
public CreatureObject fireCreature; //释放者
public SKILL_TARGET_TYPE targetType; //技能目标类型
public CreatureObject targetCreature; //目标
public GridPoint position; //目标坐标
public Vector2 offset; //导弹位置偏移
public MT_Data_Skill skill; //释放的技能
public Float3 val; //SKILLEFFECT 一个单元格数据
}
private IEffect CreateSkillEffect(SKILLEFFECT_TYPE Id)
{
if (Id == SKILLEFFECT_TYPE.FLYBALL || Id == SKILLEFFECT_TYPE.NORMAL)
return new FlyballEffect();
return null;
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, GridPoint position, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.POSITION, creature, null, position, Vector2.zero(), skillId);
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, GridPoint position, Vector2 offset, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.POSITION, creature, null, position, offset, skillId);
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, CreatureObject target, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.CREATURE, creature, target, GridPoint.zero(), Vector2.zero(), skillId);
}
//触发一个技能动作回调
public void fireAnimationEvent(CreatureObject creature, CreatureObject target, Vector2 offset, int skillId)
{
fireAnimationEvent_impl(SKILL_TARGET_TYPE.CREATURE, creature, target, GridPoint.zero(), offset, skillId);
}
void fireAnimationEvent_impl(SKILL_TARGET_TYPE type, CreatureObject creature, CreatureObject target, GridPoint position, Vector2 offset, int skillId)
{
if (creature == null) return;
MT_Data_Skill skillData = TableManager.GetInstance().TableSkill().GetElement(skillId);
if (skillData == null)
{
logger.error("skill id is null {0}", skillId);
return;
}
List<Float3> animationData = skillData.SkillEvent();
for (int i = 0; i < animationData.size(); ++i)
{
Float3 val = animationData.get(i);
EffectData data = new EffectData();
data.fireCreature = creature;
data.targetType = type;
data.targetCreature = target;
data.position = position;
data.offset = offset;
data.skill = skillData;
data.val = val;
if (TABLE.IsInvalid(val.field1()) || val.field1() <= 0)
{
OnAnimationSpace(data);
}
else
{
m_FightingManager.ClockManager.addGameTimeCallBack(val.field1(), new OnTimeCallBack() {
@Override
public void run(TimeCallBack timeCallBack, Object[] args) {
((SkillEffectManager)args[0]).OnAnimationSpace((EffectData)args[1]);
}
}, this, data);
}
}
}
//动作回调 关键帧 时间回调
void OnAnimationSpace(EffectData data)
{
IEffect effect = CreateSkillEffect(SKILLEFFECT_TYPE.values()[((Float)data.val.field3()).intValue()]);
if (effect == null) return;
effect.fireEffect(m_FightingManager,((Float)data.val.field2()).intValue(), 0, data.fireCreature, data.targetType, data.targetCreature, data.position, data.offset, data.skill);
}
}
| 4,989 | 0.626506 | 0.621644 | 140 | 32.792858 | 32.84259 | 183 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.107143 | false | false | 13 |
10c00197f94e4a5fe484b2a76f6100b36e1495fa | 22,823,456,239,342 | c1d75dfbdf0102ab18e64f28d309d4982a759179 | /src/main/java/com/example/service/WordCounter.java | 1383142eafb6798e3e549d5ed89401ee61a10823 | [] | no_license | jcasey214/spring-playground | https://github.com/jcasey214/spring-playground | 66f1cbbf2fe5ab68f0bd7a6467ae89598dc18972 | 01e0a0983611686fd40bdedfa3fffbc163ee5b9a | refs/heads/master | 2021-01-23T06:55:04.077000 | 2017-05-12T18:04:03 | 2017-05-12T18:04:03 | 86,410,600 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.service;
import com.example.config.WordCountConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Map;
public class WordCounter {
@Autowired
WordCountConfig config;
public Map<String, Integer> count(String str) {
String s;
if (config.getCaseSensitive()) {
s = str.replace("[^a-zA-Z\\s]", "");
} else {
s = str.replaceAll("[^a-zA-Z\\s]", "").toLowerCase();
}
if(config.getWords().getSkip().size() > 0){
for (String w : config.getWords().getSkip()){
s = s.replaceAll(w, "");
}
}
String[] words = StringUtils.split(s, " ");
Map<String, Integer> count = new HashMap<>();
for (String w : words) {
if (count.containsKey(w)) {
Integer num = count.get(w);
count.put(w, num + 1);
} else {
count.put(w, 1);
}
}
return count;
}
}
| UTF-8 | Java | 1,105 | java | WordCounter.java | Java | [] | null | [] | package com.example.service;
import com.example.config.WordCountConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Map;
public class WordCounter {
@Autowired
WordCountConfig config;
public Map<String, Integer> count(String str) {
String s;
if (config.getCaseSensitive()) {
s = str.replace("[^a-zA-Z\\s]", "");
} else {
s = str.replaceAll("[^a-zA-Z\\s]", "").toLowerCase();
}
if(config.getWords().getSkip().size() > 0){
for (String w : config.getWords().getSkip()){
s = s.replaceAll(w, "");
}
}
String[] words = StringUtils.split(s, " ");
Map<String, Integer> count = new HashMap<>();
for (String w : words) {
if (count.containsKey(w)) {
Integer num = count.get(w);
count.put(w, num + 1);
} else {
count.put(w, 1);
}
}
return count;
}
}
| 1,105 | 0.527602 | 0.523982 | 43 | 24.697674 | 20.006435 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false | 13 |
dbcdd39c8125cbc71d4f4d99ed4446ba869871a5 | 32,392,643,388,114 | aad50107e027e43b0df188aee021e7c63700203a | /dsl-hell-model/src/main/java/fluent/api/model/impl/ClassModelImpl.java | 6ec3bedd106095c2a90934284fb8eb5de3a91a16 | [
"BSD-2-Clause"
] | permissive | c0stra/dsl-hell | https://github.com/c0stra/dsl-hell | 940864ee39bb241c249537571a40e9f7e81fad56 | 9c714cd2a7e8369351464129395737bf3a6f941e | refs/heads/master | 2023-05-11T10:50:09.667000 | 2023-05-09T21:01:27 | 2023-05-09T21:01:27 | 211,950,175 | 4 | 0 | BSD-2-Clause | false | 2023-05-09T21:01:28 | 2019-09-30T20:26:05 | 2022-04-01T23:17:07 | 2023-05-09T21:01:27 | 168 | 4 | 0 | 0 | Java | false | false | package fluent.api.model.impl;
import fluent.api.model.ClassModel;
import fluent.api.model.ModifiersModel;
import fluent.api.model.TypeModel;
import javax.lang.model.type.TypeKind;
import java.util.List;
public class ClassModelImpl extends TypeModelImpl<ClassModel> implements ClassModel {
private ClassModel superClass;
public ClassModelImpl(ModifiersModel modifiers, String packageName, String simpleName, String fullName, TypeKind kind) {
super(modifiers, packageName, simpleName, fullName, kind);
}
public ClassModelImpl(ModifiersModel modifiers, String packageName, String simpleName, String fullName, TypeKind kind, List<TypeModel<?>> typeParameters, ClassModel rawType) {
super(modifiers, packageName, simpleName, fullName, kind, typeParameters, rawType);
}
@Override
protected ClassModel t() {
return this;
}
@Override
protected ClassModel construct(String collect, List<TypeModel<?>> typeParameters) {
return new ClassModelImpl(modifiers(), packageName(), simpleName() + collect, fullName() + collect, TypeKind.DECLARED, typeParameters, this);
}
@Override
public ClassModel superClass(ClassModel superClass) {
this.superClass = superClass;
return this;
}
@Override
public ClassModel superClass() {
return superClass;
}
}
| UTF-8 | Java | 1,365 | java | ClassModelImpl.java | Java | [] | null | [] | package fluent.api.model.impl;
import fluent.api.model.ClassModel;
import fluent.api.model.ModifiersModel;
import fluent.api.model.TypeModel;
import javax.lang.model.type.TypeKind;
import java.util.List;
public class ClassModelImpl extends TypeModelImpl<ClassModel> implements ClassModel {
private ClassModel superClass;
public ClassModelImpl(ModifiersModel modifiers, String packageName, String simpleName, String fullName, TypeKind kind) {
super(modifiers, packageName, simpleName, fullName, kind);
}
public ClassModelImpl(ModifiersModel modifiers, String packageName, String simpleName, String fullName, TypeKind kind, List<TypeModel<?>> typeParameters, ClassModel rawType) {
super(modifiers, packageName, simpleName, fullName, kind, typeParameters, rawType);
}
@Override
protected ClassModel t() {
return this;
}
@Override
protected ClassModel construct(String collect, List<TypeModel<?>> typeParameters) {
return new ClassModelImpl(modifiers(), packageName(), simpleName() + collect, fullName() + collect, TypeKind.DECLARED, typeParameters, this);
}
@Override
public ClassModel superClass(ClassModel superClass) {
this.superClass = superClass;
return this;
}
@Override
public ClassModel superClass() {
return superClass;
}
}
| 1,365 | 0.728205 | 0.728205 | 43 | 30.744186 | 41.317879 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.953488 | false | false | 13 |
59ff070dce968d5542f7772a87643715e7953b64 | 17,549,236,406,206 | cf3cb78e27d522e2a0ee1cf7b6fdfa22f8597399 | /collect_app/build/generated/ap_generated_sources/selfSignedRelease/out/org/odk/collect/android/formentry/BackgroundAudioPermissionDialogFragment_MembersInjector.java | 3536377dce35cb7e59f570c57c769673d193e15a | [
"Apache-2.0"
] | permissive | Bhawak/CS-collect | https://github.com/Bhawak/CS-collect | 7061a67dc21cf079e34d29138a47cbdc5212783f | b79b5b1c7eadcb0ce336215a500b30e66bd2c698 | refs/heads/master | 2023-04-13T16:25:55.739000 | 2023-03-16T06:45:07 | 2023-03-16T06:45:07 | 495,328,349 | 0 | 0 | NOASSERTION | false | 2023-03-16T06:45:08 | 2022-05-23T08:49:24 | 2023-01-09T10:39:41 | 2023-03-16T06:45:07 | 128,530 | 0 | 0 | 0 | Java | false | false | // Generated by Dagger (https://dagger.dev).
package org.odk.collect.android.formentry;
import dagger.MembersInjector;
import dagger.internal.DaggerGenerated;
import dagger.internal.InjectedFieldSignature;
import javax.inject.Provider;
import org.odk.collect.android.permissions.PermissionsProvider;
@DaggerGenerated
@SuppressWarnings({
"unchecked",
"rawtypes"
})
public final class BackgroundAudioPermissionDialogFragment_MembersInjector implements MembersInjector<BackgroundAudioPermissionDialogFragment> {
private final Provider<PermissionsProvider> permissionsProvider;
private final Provider<BackgroundAudioViewModel.Factory> viewModelFactoryProvider;
public BackgroundAudioPermissionDialogFragment_MembersInjector(
Provider<PermissionsProvider> permissionsProvider,
Provider<BackgroundAudioViewModel.Factory> viewModelFactoryProvider) {
this.permissionsProvider = permissionsProvider;
this.viewModelFactoryProvider = viewModelFactoryProvider;
}
public static MembersInjector<BackgroundAudioPermissionDialogFragment> create(
Provider<PermissionsProvider> permissionsProvider,
Provider<BackgroundAudioViewModel.Factory> viewModelFactoryProvider) {
return new BackgroundAudioPermissionDialogFragment_MembersInjector(permissionsProvider, viewModelFactoryProvider);
}
@Override
public void injectMembers(BackgroundAudioPermissionDialogFragment instance) {
injectPermissionsProvider(instance, permissionsProvider.get());
injectViewModelFactory(instance, viewModelFactoryProvider.get());
}
@InjectedFieldSignature("org.odk.collect.android.formentry.BackgroundAudioPermissionDialogFragment.permissionsProvider")
public static void injectPermissionsProvider(BackgroundAudioPermissionDialogFragment instance,
PermissionsProvider permissionsProvider) {
instance.permissionsProvider = permissionsProvider;
}
@InjectedFieldSignature("org.odk.collect.android.formentry.BackgroundAudioPermissionDialogFragment.viewModelFactory")
public static void injectViewModelFactory(BackgroundAudioPermissionDialogFragment instance,
BackgroundAudioViewModel.Factory viewModelFactory) {
instance.viewModelFactory = viewModelFactory;
}
}
| UTF-8 | Java | 2,225 | java | BackgroundAudioPermissionDialogFragment_MembersInjector.java | Java | [] | null | [] | // Generated by Dagger (https://dagger.dev).
package org.odk.collect.android.formentry;
import dagger.MembersInjector;
import dagger.internal.DaggerGenerated;
import dagger.internal.InjectedFieldSignature;
import javax.inject.Provider;
import org.odk.collect.android.permissions.PermissionsProvider;
@DaggerGenerated
@SuppressWarnings({
"unchecked",
"rawtypes"
})
public final class BackgroundAudioPermissionDialogFragment_MembersInjector implements MembersInjector<BackgroundAudioPermissionDialogFragment> {
private final Provider<PermissionsProvider> permissionsProvider;
private final Provider<BackgroundAudioViewModel.Factory> viewModelFactoryProvider;
public BackgroundAudioPermissionDialogFragment_MembersInjector(
Provider<PermissionsProvider> permissionsProvider,
Provider<BackgroundAudioViewModel.Factory> viewModelFactoryProvider) {
this.permissionsProvider = permissionsProvider;
this.viewModelFactoryProvider = viewModelFactoryProvider;
}
public static MembersInjector<BackgroundAudioPermissionDialogFragment> create(
Provider<PermissionsProvider> permissionsProvider,
Provider<BackgroundAudioViewModel.Factory> viewModelFactoryProvider) {
return new BackgroundAudioPermissionDialogFragment_MembersInjector(permissionsProvider, viewModelFactoryProvider);
}
@Override
public void injectMembers(BackgroundAudioPermissionDialogFragment instance) {
injectPermissionsProvider(instance, permissionsProvider.get());
injectViewModelFactory(instance, viewModelFactoryProvider.get());
}
@InjectedFieldSignature("org.odk.collect.android.formentry.BackgroundAudioPermissionDialogFragment.permissionsProvider")
public static void injectPermissionsProvider(BackgroundAudioPermissionDialogFragment instance,
PermissionsProvider permissionsProvider) {
instance.permissionsProvider = permissionsProvider;
}
@InjectedFieldSignature("org.odk.collect.android.formentry.BackgroundAudioPermissionDialogFragment.viewModelFactory")
public static void injectViewModelFactory(BackgroundAudioPermissionDialogFragment instance,
BackgroundAudioViewModel.Factory viewModelFactory) {
instance.viewModelFactory = viewModelFactory;
}
}
| 2,225 | 0.838652 | 0.838652 | 50 | 43.5 | 38.474018 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false | 13 |
ec7dc797a8dd10ff539c9fe3b65e4ca9e1a02414 | 21,680,994,943,019 | 52fb5f4a7484a2766957b9415aacf69d51ba110f | /Selenium_demo/src/Package1/FirefoxDriverDemo.java | 5b05da58307a2fa77d62861c90f30d8c21be5a31 | [] | no_license | faisalsakib/JavaSelenium | https://github.com/faisalsakib/JavaSelenium | 280c65463cdcc5e48fea9c85772d29aca7477e1a | 5750f6bcbc47428a416cc12961c650270990c006 | refs/heads/master | 2020-04-14T09:18:19.127000 | 2019-01-01T18:52:04 | 2019-01-01T18:52:04 | 163,756,906 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Package1;
public class FirefoxDriverDemo extends BrowserDemo2{
public static void main(String[] args) {
Browser_demo obj = new FirefoxDriverDemo();
obj.openINt();
((FirefoxDriverDemo) obj).getUrl();
obj.refreshINIT();
obj.closeINT();
}
@Override // polymorfism
public void openINt() {
System.out.println("Open FireFox");
}
@Override
public void refreshINIT() {
System.out.println("Refreash FireFox");
}
@Override
public void closeINT() {
System.out.println("Close FireFox");
}
@Override
public void getUrl() {
System.out.println("Get Url for firefox");
}
}
| UTF-8 | Java | 655 | java | FirefoxDriverDemo.java | Java | [] | null | [] | package Package1;
public class FirefoxDriverDemo extends BrowserDemo2{
public static void main(String[] args) {
Browser_demo obj = new FirefoxDriverDemo();
obj.openINt();
((FirefoxDriverDemo) obj).getUrl();
obj.refreshINIT();
obj.closeINT();
}
@Override // polymorfism
public void openINt() {
System.out.println("Open FireFox");
}
@Override
public void refreshINIT() {
System.out.println("Refreash FireFox");
}
@Override
public void closeINT() {
System.out.println("Close FireFox");
}
@Override
public void getUrl() {
System.out.println("Get Url for firefox");
}
}
| 655 | 0.641221 | 0.638168 | 38 | 15.236842 | 16.315046 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.289474 | false | false | 13 |
b13e08af43fd9301940ecdd53f845e33a45b5228 | 27,539,330,338,064 | bd3e98ee120e46c27e4fddc77a3bf65ea5a9664b | /app/src/main/java/com/sungu/bts/ui/form/QRCodeActivity.java | a3d85af6b171932b0e9702cc1e14ac40bbea55d6 | [] | no_license | zhouhaichao/ShiGongYan | https://github.com/zhouhaichao/ShiGongYan | f98f81af7fae8e10bc3ab0f62fd3c73e2d655026 | be700ce1384706e295bbab9f59313fa3524ac46a | refs/heads/master | 2020-03-26T22:49:06.154000 | 2019-06-28T01:38:28 | 2019-06-28T01:38:28 | 145,489,559 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sungu.bts.ui.form;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.gson.Gson;
import com.sungu.bts.R;
import com.sungu.bts.business.interfaces.IGetJason;
import com.sungu.bts.business.jasondata.CustomerQrcode;
import com.sungu.bts.business.jasondata.CustomerQrcodeSend;
import com.sungu.bts.business.util.DDZConsts;
import com.sungu.bts.business.util.DDZGetJason;
import com.sungu.bts.business.util.DDZResponseUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
public class QRCodeActivity extends DDZBaseActivity {
long custId;
private String url;
@ViewInject(R.id.ll_qrcode)
LinearLayout ll_qrcode;
@ViewInject(R.id.iv_qrcode)
ImageView iv_qrcode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
x.view().inject(this);
loadIntent();
loadInfo();
loadEvent();
}
private void loadIntent() {
Intent intent = getIntent();
custId = intent.getLongExtra(DDZConsts.INTENT_EXTRA_CUSTOM_ID, 0);
}
private void loadInfo() {
getReportContract();
}
private void loadEvent() {
ll_qrcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
iv_qrcode.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
UMImage image = new UMImage(QRCodeActivity.this, url);//网络图片
new ShareAction(QRCodeActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
.withMedia(image).share();
return false;
}
});
}
private UMShareListener umShareListener = new UMShareListener() {
@Override
public void onStart(SHARE_MEDIA platform) {
//分享开始的回调
}
@Override
public void onResult(SHARE_MEDIA platform) {
Log.d("plat", "platform" + platform);
Toast.makeText(QRCodeActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
Toast.makeText(QRCodeActivity.this,platform + " 分享失败啦,请确保微信能正常使用", Toast.LENGTH_SHORT).show();
if(t!=null){
Log.d("throw","throw:"+t.getMessage());
}
}
@Override
public void onCancel(SHARE_MEDIA platform) {
Toast.makeText(QRCodeActivity.this,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
}
};
/**
* 获取信息
* */
private void getReportContract() {
CustomerQrcodeSend customerQrcodeSend = new CustomerQrcodeSend();
customerQrcodeSend.userId = ddzCache.getAccountEncryId();
customerQrcodeSend.custId = custId;
String strSend = customerQrcodeSend.getJsonString();
DDZGetJason.getEnterpriseJasonData(this, ddzCache.getEnterpriseUrl(), "/customer/qrcode", strSend, new IGetJason() {
@Override
public void onSuccess(String result) {
Gson gson = new Gson();
CustomerQrcode customerQrcode = gson.fromJson(result, CustomerQrcode.class);
if (customerQrcode.rc == 0) {
url=customerQrcode.url;
//根据Code获取二维码
x.image().bind(iv_qrcode,customerQrcode.url,new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.FIT_XY).build());
} else {
//根据命令码给出提示
Toast.makeText(QRCodeActivity.this, DDZResponseUtils.GetReCode(customerQrcode), Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
}
}
| UTF-8 | Java | 4,685 | java | QRCodeActivity.java | Java | [] | null | [] | package com.sungu.bts.ui.form;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.gson.Gson;
import com.sungu.bts.R;
import com.sungu.bts.business.interfaces.IGetJason;
import com.sungu.bts.business.jasondata.CustomerQrcode;
import com.sungu.bts.business.jasondata.CustomerQrcodeSend;
import com.sungu.bts.business.util.DDZConsts;
import com.sungu.bts.business.util.DDZGetJason;
import com.sungu.bts.business.util.DDZResponseUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
public class QRCodeActivity extends DDZBaseActivity {
long custId;
private String url;
@ViewInject(R.id.ll_qrcode)
LinearLayout ll_qrcode;
@ViewInject(R.id.iv_qrcode)
ImageView iv_qrcode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
x.view().inject(this);
loadIntent();
loadInfo();
loadEvent();
}
private void loadIntent() {
Intent intent = getIntent();
custId = intent.getLongExtra(DDZConsts.INTENT_EXTRA_CUSTOM_ID, 0);
}
private void loadInfo() {
getReportContract();
}
private void loadEvent() {
ll_qrcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
iv_qrcode.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
UMImage image = new UMImage(QRCodeActivity.this, url);//网络图片
new ShareAction(QRCodeActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
.withMedia(image).share();
return false;
}
});
}
private UMShareListener umShareListener = new UMShareListener() {
@Override
public void onStart(SHARE_MEDIA platform) {
//分享开始的回调
}
@Override
public void onResult(SHARE_MEDIA platform) {
Log.d("plat", "platform" + platform);
Toast.makeText(QRCodeActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
Toast.makeText(QRCodeActivity.this,platform + " 分享失败啦,请确保微信能正常使用", Toast.LENGTH_SHORT).show();
if(t!=null){
Log.d("throw","throw:"+t.getMessage());
}
}
@Override
public void onCancel(SHARE_MEDIA platform) {
Toast.makeText(QRCodeActivity.this,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
}
};
/**
* 获取信息
* */
private void getReportContract() {
CustomerQrcodeSend customerQrcodeSend = new CustomerQrcodeSend();
customerQrcodeSend.userId = ddzCache.getAccountEncryId();
customerQrcodeSend.custId = custId;
String strSend = customerQrcodeSend.getJsonString();
DDZGetJason.getEnterpriseJasonData(this, ddzCache.getEnterpriseUrl(), "/customer/qrcode", strSend, new IGetJason() {
@Override
public void onSuccess(String result) {
Gson gson = new Gson();
CustomerQrcode customerQrcode = gson.fromJson(result, CustomerQrcode.class);
if (customerQrcode.rc == 0) {
url=customerQrcode.url;
//根据Code获取二维码
x.image().bind(iv_qrcode,customerQrcode.url,new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.FIT_XY).build());
} else {
//根据命令码给出提示
Toast.makeText(QRCodeActivity.this, DDZResponseUtils.GetReCode(customerQrcode), Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
}
}
| 4,685 | 0.641155 | 0.640717 | 139 | 31.899281 | 29.381464 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633094 | false | false | 13 |
8d3baf9b131ffb9fd18352806d5ea6bb80d6fcd8 | 22,436,909,177,555 | 79d16620010628f5a9b148b340fd6f9dce2f450a | /examples/Selection.java | 596750d02f2295bf1669a6a3a9ad51a102667fb3 | [] | no_license | cmitch/EditorProject | https://github.com/cmitch/EditorProject | 350e9b31b3cb715295d5ac8c333ad591d3ddd804 | 419974b2deeba33a96d66e5d33f5470e8e265175 | refs/heads/master | 2016-09-23T02:14:37.894000 | 2016-08-02T22:13:45 | 2016-08-02T22:13:45 | 64,581,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by Chris on 8/1/2016.
*/
public class Selection {
}
| UTF-8 | Java | 68 | java | Selection.java | Java | [
{
"context": "/**\n * Created by Chris on 8/1/2016.\n */\npublic class Selection {\n}\n",
"end": 23,
"score": 0.9983425140380859,
"start": 18,
"tag": "NAME",
"value": "Chris"
}
] | null | [] | /**
* Created by Chris on 8/1/2016.
*/
public class Selection {
}
| 68 | 0.617647 | 0.529412 | 5 | 12.6 | 12.846789 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 13 |
0b2feac0108e9bf2f35cc303fab3b25baf756b6d | 9,122,510,544,061 | cef227f2e7ac074902e6fc6103b067dd48c63ea0 | /spring-boot-websocket-server/src/main/java/com/github/baymin/wsserver/WsServerApplication.java | 8ede8afebdb8b1c1b5c48a9e2d4d1589d3c5674c | [
"MIT"
] | permissive | crpeng2019/spring-boot-in-action | https://github.com/crpeng2019/spring-boot-in-action | 1d186d4a3927633c7bcd08302dd45b84571993c7 | 5a76e0357452d2b4b419af899507f35e8de1baa4 | refs/heads/master | 2023-07-08T10:37:55.820000 | 2021-08-10T08:01:02 | 2021-08-10T08:01:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.baymin.wsserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WsServerApplication {
public static void main(String[] args) {
SpringApplication.run(WsServerApplication.class, args);
}
}
| UTF-8 | Java | 335 | java | WsServerApplication.java | Java | [
{
"context": "package com.github.baymin.wsserver;\n\nimport org.springframework.boot.Spring",
"end": 25,
"score": 0.9185472726821899,
"start": 19,
"tag": "USERNAME",
"value": "baymin"
}
] | null | [] | package com.github.baymin.wsserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WsServerApplication {
public static void main(String[] args) {
SpringApplication.run(WsServerApplication.class, args);
}
}
| 335 | 0.79403 | 0.79403 | 13 | 24.76923 | 24.720449 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 13 |
a709e4dbbfe9dbcce32a4dcfd1cdd7bfaa1364fc | 6,760,278,545,864 | c178be41702a4c7dd303a4b13492c4c6f1da2e04 | /src/main/java/com/verify/demo/service/impl/AdminServiceImpl.java | 95f0aad4a8fc4a3c305c3789c739fdba1e9910a8 | [] | no_license | louzhiyuan/verify | https://github.com/louzhiyuan/verify | c6b414835aaf132940ac3f901fdc4a3c16acb743 | d79218c29a1ec2921dc85cc15fe1719715dfe3ad | refs/heads/master | 2018-07-11T07:14:54.303000 | 2018-06-14T09:21:58 | 2018-06-14T09:21:58 | 132,446,669 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.verify.demo.service.impl;
import com.verify.demo.entity.Admin;
import com.verify.demo.repository.AdminRepository;
import com.verify.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
AdminRepository adminRepository;
@Override
public Admin checkAdminMsg(String adminname, String adminpassword) {
return adminRepository.checkAdminMsg(adminname,adminpassword);
}
}
| UTF-8 | Java | 568 | java | AdminServiceImpl.java | Java | [] | null | [] | package com.verify.demo.service.impl;
import com.verify.demo.entity.Admin;
import com.verify.demo.repository.AdminRepository;
import com.verify.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
AdminRepository adminRepository;
@Override
public Admin checkAdminMsg(String adminname, String adminpassword) {
return adminRepository.checkAdminMsg(adminname,adminpassword);
}
}
| 568 | 0.802817 | 0.802817 | 19 | 28.894737 | 25.191675 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 13 |
1a7bf66e4abad0b952c60e1eaa5d7f38bc455da8 | 28,535,762,744,663 | 31be1d57215f04f0cd82882c2e48f15593c6e889 | /part04-Part04_29.RecordsFromAFile/src/main/java/RecordsFromAFile.java | cd272397b9445236267a9d145dcb2c6cf391aea6 | [] | no_license | dilbaay23/moocJavaProgramming1 | https://github.com/dilbaay23/moocJavaProgramming1 | 2d623b33205fb0e19185e38f4262bbba4393cdc4 | c9e3999ced7a9f878e7fab9a51994326d25e918b | refs/heads/master | 2022-12-29T04:36:58.811000 | 2020-08-01T15:11:39 | 2020-08-01T15:11:39 | 284,271,089 | 0 | 0 | null | false | 2020-10-14T00:06:48 | 2020-08-01T14:02:32 | 2020-08-01T15:38:48 | 2020-10-14T00:06:47 | 1,003 | 0 | 0 | 20 | Java | false | false |
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class RecordsFromAFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name of the file:");
String file=scanner.nextLine();
// ArrayList<String> list=new ArrayList<>();
try(Scanner scan = new Scanner(Paths.get(file))) {
while(scan.hasNext()){
String line=scan.nextLine();
String[] parts =line.split(",");
String name=parts[0];
int age=Integer.valueOf(parts[1]);
System.out.println(name+ ", age: "+age+" years");
}
} catch (Exception e) {
}
}
}
| UTF-8 | Java | 808 | java | RecordsFromAFile.java | Java | [] | null | [] |
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class RecordsFromAFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name of the file:");
String file=scanner.nextLine();
// ArrayList<String> list=new ArrayList<>();
try(Scanner scan = new Scanner(Paths.get(file))) {
while(scan.hasNext()){
String line=scan.nextLine();
String[] parts =line.split(",");
String name=parts[0];
int age=Integer.valueOf(parts[1]);
System.out.println(name+ ", age: "+age+" years");
}
} catch (Exception e) {
}
}
}
| 808 | 0.522277 | 0.519802 | 27 | 28.888889 | 19.264885 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518519 | false | false | 13 |
71de7f4cc9ec71e6670407d4572c6df827791303 | 11,656,541,261,814 | d991ca6adfb7e59616bfb649e4c202ceb6688c84 | /CtoFTester.java | 49ab7262fc6f66d060455ffb0e9dbe6be8a08a81 | [] | no_license | TheoYochum/MKS21X-CtoF | https://github.com/TheoYochum/MKS21X-CtoF | de7d7ef904b0f39588588023d839e18f24ba3822 | fb6de70bccf4a581230ca3983d5a0bde40456c14 | refs/heads/main | 2023-08-12T07:15:42.547000 | 2021-09-24T00:41:34 | 2021-09-24T00:41:34 | 409,780,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //The functions should each take in a temperature value that could be an int or double based on how we want it to function, I will probably do doubles
//The functions should both return an int or double depending on how we want it to function I will likely do a double as it will only divide by 3
import java.util.Scanner;
public class CtoFTester {
public static void main(String[] args) {
double x;
Scanner in = new Scanner(System.in);
x = in.nextDouble();
System.out.println(celsiusToFahrenheit(x));
//System.out.println(fahrenheitToCelsius(x));
}
public static double celsiusToFahrenheit(double input) {
return (input * (9.0 / 5.0) + 32);
}
public static double fahrenheitToCelsius(double input) {
return ((input - 32) * (5.0 / 9.0));
}
}
| UTF-8 | Java | 786 | java | CtoFTester.java | Java | [] | null | [] | //The functions should each take in a temperature value that could be an int or double based on how we want it to function, I will probably do doubles
//The functions should both return an int or double depending on how we want it to function I will likely do a double as it will only divide by 3
import java.util.Scanner;
public class CtoFTester {
public static void main(String[] args) {
double x;
Scanner in = new Scanner(System.in);
x = in.nextDouble();
System.out.println(celsiusToFahrenheit(x));
//System.out.println(fahrenheitToCelsius(x));
}
public static double celsiusToFahrenheit(double input) {
return (input * (9.0 / 5.0) + 32);
}
public static double fahrenheitToCelsius(double input) {
return ((input - 32) * (5.0 / 9.0));
}
}
| 786 | 0.704835 | 0.688295 | 22 | 34.727272 | 40.878071 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 13 |
8f8e5c97bb667daa409c724c3ebf1dc2d9bcc610 | 26,259,430,079,686 | b47ff128c3b2c983484b82808e8a90494c3dca26 | /socket-server/src/main/java/com/na/baccarat/socketserver/entity/GameTable.java | 18281ff276d89827a2fabc18cc915fc2df84a33a | [] | no_license | m0o0m/Proj | https://github.com/m0o0m/Proj | f5eb4b7727ff906cee05b8aa530d768683ca010c | 677a700512f8218b440232987e7d873d772dd25b | refs/heads/master | 2021-04-28T10:03:52.580000 | 2018-02-02T02:27:16 | 2018-02-02T02:27:16 | 122,055,557 | 0 | 1 | null | true | 2018-02-19T11:52:54 | 2018-02-19T11:52:54 | 2017-12-08T06:12:26 | 2018-02-02T02:30:40 | 203,848 | 0 | 0 | 0 | null | false | null | package com.na.baccarat.socketserver.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.annotation.JSONField;
import com.na.baccarat.socketserver.command.requestpara.Card;
import com.na.baccarat.socketserver.common.enums.GameTableInstantStateEnum;
import com.na.baccarat.socketserver.common.enums.GameTableTypeEnum;
import com.na.baccarat.socketserver.common.enums.RoundStatusEnum;
import com.na.baccarat.socketserver.common.enums.TradeItemEnum;
import com.na.baccarat.socketserver.common.limitrule.CheckLimitRule;
import com.na.baccarat.socketserver.config.BaccaratConfig;
import com.na.user.socketserver.entity.GameTablePO;
/**
* 游戏桌子
*/
public class GameTable implements Serializable {
private static final long serialVersionUID = 1L;
private Logger log = LoggerFactory.getLogger(GameTable.class);
private GameTablePO gameTablePO;
/**
* 桌子即时状态。
*/
@JSONField(name = "stu")
private Integer instantState = GameTableInstantStateEnum.INACTIVE.get();
/**
* 靴信息
*/
private Round round;
/**
* 游戏桌路子
*/
private List<Round> rounds;
/**
* 荷官
*/
private User dealer;
/**
* 荷官主管
*/
private User checkers;
/**
* 靴拓展信息
*/
private RoundExt roundExt;
/**
* 靴启动的开始时间(需要数据库去查询)
*/
private Date bootStartTime;
/**
* 玩法列表
*/
private List<Play> playList;
/**
* 卡片信息
* 0-5 表示 闲前2张 庄前2张 闲第3张 庄第3张
*/
private Card[] cards;
/**
* 更换荷官次数 还靴清空
*/
private int changeDealerNum = 0;
/**
* 当前桌子庄和闲
*/
private Map<TradeItemEnum,Set<User>> bankPlayerMap = new ConcurrentHashMap<>();
//投注倒计时
private AtomicLong coundDown = new AtomicLong(-11);
//倒计时当前时间
private Date coundDownDate;
//倒计时
private Integer countDownSeconds;
private GameTableInstantStateEnum oldStatus;
//分位咪牌倒计时60秒
private AtomicLong miCardDownSeat = new AtomicLong(-1l);
private CheckLimitRule limitRule;
public void setCards(Card[] cards) {
this.cards = cards;
}
public Card[] getCards() {
return cards;
}
public GameTableInstantStateEnum getOldStatus() {
return oldStatus;
}
public void setOldStatus(GameTableInstantStateEnum oldStatus) {
this.oldStatus = oldStatus;
}
/**
* 设置卡片
* @param type
* @param num
* @param index
*/
public void setCard(String type, int num, int index) {
if (this.cards == null) {
cards = new Card[BaccaratConfig.maxCardNum];
}
this.cards[index] = new Card(type, num);
exportCard(index);
}
public void removeCard(int index){
if(this.cards!=null && index<this.cards.length){
this.cards[index] = null;
clean(index);
}
}
/**
* 索引从0开始
*
* @param index
*/
public void exportCard(int index) {
Card c = this.cards[index];
if (c != null) {
switch (index) {
case 0:
roundExt.getRoundExtPO().setPlayerCard1Mode(c.getCardType());
roundExt.getRoundExtPO().setPlayerCard1Number(c.getCardNum());
break;
case 1:
roundExt.getRoundExtPO().setPlayerCard2Mode(c.getCardType());
roundExt.getRoundExtPO().setPlayerCard2Number(c.getCardNum());
break;
case 2:
roundExt.getRoundExtPO().setBankCard1Mode(c.getCardType());
roundExt.getRoundExtPO().setBankCard1Number(c.getCardNum());
break;
case 3:
roundExt.getRoundExtPO().setBankCard2Mode(c.getCardType());
roundExt.getRoundExtPO().setBankCard2Number(c.getCardNum());
break;
case 4:
roundExt.getRoundExtPO().setPlayerCard3Mode(c.getCardType());
roundExt.getRoundExtPO().setPlayerCard3Number(c.getCardNum());
break;
case 5:
roundExt.getRoundExtPO().setBankCard3Mode(c.getCardType());
roundExt.getRoundExtPO().setBankCard3Number(c.getCardNum());
break;
}
}
}
/**
* 清除指定索引的牌。
*
* @param index
*/
private void clean(int index) {
Card c = this.cards[index];
switch (index) {
case 0:
roundExt.getRoundExtPO().setPlayerCard1Mode(null);
roundExt.getRoundExtPO().setPlayerCard1Number(null);
break;
case 1:
roundExt.getRoundExtPO().setPlayerCard2Mode(null);
roundExt.getRoundExtPO().setPlayerCard2Number(null);
break;
case 2:
roundExt.getRoundExtPO().setBankCard1Mode(null);
roundExt.getRoundExtPO().setBankCard1Number(null);
break;
case 3:
roundExt.getRoundExtPO().setBankCard2Mode(null);
roundExt.getRoundExtPO().setBankCard2Number(null);
break;
case 4:
roundExt.getRoundExtPO().setPlayerCard3Mode(null);
roundExt.getRoundExtPO().setPlayerCard3Number(null);
break;
case 5:
roundExt.getRoundExtPO().setBankCard3Mode(null);
roundExt.getRoundExtPO().setBankCard3Number(null);
break;
}
}
public User getDealer() {
return dealer;
}
public void setDealer(User dealer) {
this.dealer = dealer;
}
public Round getRound() {
return round;
}
public void setRound(Round round) {
this.round = round;
}
public RoundExt getRoundExt() {
return roundExt;
}
public void setRoundExt(RoundExt roundExt) {
this.roundExt = roundExt;
}
public List<Round> getRounds() {
return rounds;
}
public void setRounds(List<Round> rounds) {
this.rounds = rounds;
}
public User getCheckers() {
return checkers;
}
public void setCheckers(User checkers) {
this.checkers = checkers;
}
public List<Play> getPlayList() {
return playList;
}
public void setPlayList(List<Play> playList) {
this.playList = playList;
}
public Date getBootStartTime() {
return bootStartTime;
}
public void setBootStartTime(Date bootStartTime) {
this.bootStartTime = bootStartTime;
}
public int getChangeDealerNum() {
return changeDealerNum;
}
public void setChangeDealerNum(int changeDealerNum) {
this.changeDealerNum = changeDealerNum;
}
public AtomicLong getCoundDown() {
return coundDown;
}
public void setCoundDown(AtomicLong coundDown) {
this.coundDown = coundDown;
}
public Map<TradeItemEnum, Set<User>> getBankPlayerMap() {
return bankPlayerMap;
}
public Set<User> getBankPlayerMap(TradeItemEnum tradeItemEnum) {
if(bankPlayerMap == null ||tradeItemEnum == null){
return null;
}
return bankPlayerMap.get(tradeItemEnum);
}
public void setBankPlayerMap(Map<TradeItemEnum, Set<User>> bankPlayerMap) {
this.bankPlayerMap = bankPlayerMap;
}
public AtomicLong getMiCardDownSeat() {
return miCardDownSeat;
}
public void setMiCardDownSeat(AtomicLong miCardDownSeat) {
this.miCardDownSeat = miCardDownSeat;
}
public Date getCoundDownDate() {
return coundDownDate;
}
public void setCoundDownDate(Date coundDownDate) {
this.coundDownDate = coundDownDate;
}
/**
* 返回指定交易项ID的交易项。
* @param tradeItemId
* @return
*/
@JSONField(deserialize=false,serialize = false)
public TradeItem getTradeItemById(Integer tradeItemId){
for(Play play : this.playList){
Optional<TradeItem> opt = play.getTradeList().stream().filter(item->item.getId().equals(tradeItemId)).findFirst();
if(opt.isPresent()){
return opt.get();
}
}
return null;
}
@JSONField(deserialize=false,serialize = false)
public GameTableInstantStateEnum getInstantStateEnum() {
if(instantState==null)return null;
return GameTableInstantStateEnum.get(instantState);
}
public void setInstantStateEnum(GameTableInstantStateEnum instantStateEnum) {
log.debug("【桌子】: " + this.getGameTablePO().getId() + ",瞬时状态: " + this.instantState +",修改为: " + instantStateEnum);
this.instantState = instantStateEnum.get();
}
@JSONField(deserialize=false,serialize = false)
public Integer getInstantState() {
return instantState;
}
public void setInstantState(Integer instantState) {
this.instantState = instantState;
}
public GameTablePO getGameTablePO() {
return gameTablePO;
}
public void setGameTablePO(GameTablePO gameTablePO) {
this.gameTablePO = gameTablePO;
}
public CheckLimitRule getLimitRule() {
return limitRule;
}
public void setLimitRule(CheckLimitRule limitRule) {
this.limitRule = limitRule;
}
public String getShowStatus() {
GameTableTypeEnum gameTableTypeEnum = this.getGameTablePO().getTypeEnum();
RoundStatusEnum roundStatusEnum = this.round.getRoundPO().getStatusEnum();
if(gameTableTypeEnum == GameTableTypeEnum.MI_BEING
|| gameTableTypeEnum == GameTableTypeEnum.MI_NORMAL ) {
if(roundStatusEnum == RoundStatusEnum.IDLE
|| roundStatusEnum == RoundStatusEnum.SHUFFLE) {
return "洗牌中";
} else if(roundStatusEnum == RoundStatusEnum.NEWGAME
|| roundStatusEnum == RoundStatusEnum.BETTING) {
return "下注中";
} else if(roundStatusEnum == RoundStatusEnum.AWAITING_RESULT) {
return "咪牌中";
} else if(roundStatusEnum == RoundStatusEnum.FINISH) {
return "结算中";
} else if (roundStatusEnum == RoundStatusEnum.PAUSE) {
return "暂停中";
}
} else {
if(roundStatusEnum == RoundStatusEnum.IDLE
|| roundStatusEnum == RoundStatusEnum.SHUFFLE) {
return "洗牌中";
} else if(roundStatusEnum == RoundStatusEnum.NEWGAME
|| roundStatusEnum == RoundStatusEnum.BETTING) {
return "下注中";
} else if(roundStatusEnum == RoundStatusEnum.AWAITING_RESULT
|| roundStatusEnum == RoundStatusEnum.FINISH) {
return "结算中";
} else if (roundStatusEnum == RoundStatusEnum.PAUSE) {
return "暂停中";
}
}
return "空闲中";
}
public Integer getCountDownSeconds() {
return countDownSeconds;
}
public void setCountDownSeconds(Integer countDownSeconds) {
this.countDownSeconds = countDownSeconds;
}
}
| UTF-8 | Java | 10,038 | java | GameTable.java | Java | [] | null | [] | package com.na.baccarat.socketserver.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.annotation.JSONField;
import com.na.baccarat.socketserver.command.requestpara.Card;
import com.na.baccarat.socketserver.common.enums.GameTableInstantStateEnum;
import com.na.baccarat.socketserver.common.enums.GameTableTypeEnum;
import com.na.baccarat.socketserver.common.enums.RoundStatusEnum;
import com.na.baccarat.socketserver.common.enums.TradeItemEnum;
import com.na.baccarat.socketserver.common.limitrule.CheckLimitRule;
import com.na.baccarat.socketserver.config.BaccaratConfig;
import com.na.user.socketserver.entity.GameTablePO;
/**
* 游戏桌子
*/
public class GameTable implements Serializable {
private static final long serialVersionUID = 1L;
private Logger log = LoggerFactory.getLogger(GameTable.class);
private GameTablePO gameTablePO;
/**
* 桌子即时状态。
*/
@JSONField(name = "stu")
private Integer instantState = GameTableInstantStateEnum.INACTIVE.get();
/**
* 靴信息
*/
private Round round;
/**
* 游戏桌路子
*/
private List<Round> rounds;
/**
* 荷官
*/
private User dealer;
/**
* 荷官主管
*/
private User checkers;
/**
* 靴拓展信息
*/
private RoundExt roundExt;
/**
* 靴启动的开始时间(需要数据库去查询)
*/
private Date bootStartTime;
/**
* 玩法列表
*/
private List<Play> playList;
/**
* 卡片信息
* 0-5 表示 闲前2张 庄前2张 闲第3张 庄第3张
*/
private Card[] cards;
/**
* 更换荷官次数 还靴清空
*/
private int changeDealerNum = 0;
/**
* 当前桌子庄和闲
*/
private Map<TradeItemEnum,Set<User>> bankPlayerMap = new ConcurrentHashMap<>();
//投注倒计时
private AtomicLong coundDown = new AtomicLong(-11);
//倒计时当前时间
private Date coundDownDate;
//倒计时
private Integer countDownSeconds;
private GameTableInstantStateEnum oldStatus;
//分位咪牌倒计时60秒
private AtomicLong miCardDownSeat = new AtomicLong(-1l);
private CheckLimitRule limitRule;
public void setCards(Card[] cards) {
this.cards = cards;
}
public Card[] getCards() {
return cards;
}
public GameTableInstantStateEnum getOldStatus() {
return oldStatus;
}
public void setOldStatus(GameTableInstantStateEnum oldStatus) {
this.oldStatus = oldStatus;
}
/**
* 设置卡片
* @param type
* @param num
* @param index
*/
public void setCard(String type, int num, int index) {
if (this.cards == null) {
cards = new Card[BaccaratConfig.maxCardNum];
}
this.cards[index] = new Card(type, num);
exportCard(index);
}
public void removeCard(int index){
if(this.cards!=null && index<this.cards.length){
this.cards[index] = null;
clean(index);
}
}
/**
* 索引从0开始
*
* @param index
*/
public void exportCard(int index) {
Card c = this.cards[index];
if (c != null) {
switch (index) {
case 0:
roundExt.getRoundExtPO().setPlayerCard1Mode(c.getCardType());
roundExt.getRoundExtPO().setPlayerCard1Number(c.getCardNum());
break;
case 1:
roundExt.getRoundExtPO().setPlayerCard2Mode(c.getCardType());
roundExt.getRoundExtPO().setPlayerCard2Number(c.getCardNum());
break;
case 2:
roundExt.getRoundExtPO().setBankCard1Mode(c.getCardType());
roundExt.getRoundExtPO().setBankCard1Number(c.getCardNum());
break;
case 3:
roundExt.getRoundExtPO().setBankCard2Mode(c.getCardType());
roundExt.getRoundExtPO().setBankCard2Number(c.getCardNum());
break;
case 4:
roundExt.getRoundExtPO().setPlayerCard3Mode(c.getCardType());
roundExt.getRoundExtPO().setPlayerCard3Number(c.getCardNum());
break;
case 5:
roundExt.getRoundExtPO().setBankCard3Mode(c.getCardType());
roundExt.getRoundExtPO().setBankCard3Number(c.getCardNum());
break;
}
}
}
/**
* 清除指定索引的牌。
*
* @param index
*/
private void clean(int index) {
Card c = this.cards[index];
switch (index) {
case 0:
roundExt.getRoundExtPO().setPlayerCard1Mode(null);
roundExt.getRoundExtPO().setPlayerCard1Number(null);
break;
case 1:
roundExt.getRoundExtPO().setPlayerCard2Mode(null);
roundExt.getRoundExtPO().setPlayerCard2Number(null);
break;
case 2:
roundExt.getRoundExtPO().setBankCard1Mode(null);
roundExt.getRoundExtPO().setBankCard1Number(null);
break;
case 3:
roundExt.getRoundExtPO().setBankCard2Mode(null);
roundExt.getRoundExtPO().setBankCard2Number(null);
break;
case 4:
roundExt.getRoundExtPO().setPlayerCard3Mode(null);
roundExt.getRoundExtPO().setPlayerCard3Number(null);
break;
case 5:
roundExt.getRoundExtPO().setBankCard3Mode(null);
roundExt.getRoundExtPO().setBankCard3Number(null);
break;
}
}
public User getDealer() {
return dealer;
}
public void setDealer(User dealer) {
this.dealer = dealer;
}
public Round getRound() {
return round;
}
public void setRound(Round round) {
this.round = round;
}
public RoundExt getRoundExt() {
return roundExt;
}
public void setRoundExt(RoundExt roundExt) {
this.roundExt = roundExt;
}
public List<Round> getRounds() {
return rounds;
}
public void setRounds(List<Round> rounds) {
this.rounds = rounds;
}
public User getCheckers() {
return checkers;
}
public void setCheckers(User checkers) {
this.checkers = checkers;
}
public List<Play> getPlayList() {
return playList;
}
public void setPlayList(List<Play> playList) {
this.playList = playList;
}
public Date getBootStartTime() {
return bootStartTime;
}
public void setBootStartTime(Date bootStartTime) {
this.bootStartTime = bootStartTime;
}
public int getChangeDealerNum() {
return changeDealerNum;
}
public void setChangeDealerNum(int changeDealerNum) {
this.changeDealerNum = changeDealerNum;
}
public AtomicLong getCoundDown() {
return coundDown;
}
public void setCoundDown(AtomicLong coundDown) {
this.coundDown = coundDown;
}
public Map<TradeItemEnum, Set<User>> getBankPlayerMap() {
return bankPlayerMap;
}
public Set<User> getBankPlayerMap(TradeItemEnum tradeItemEnum) {
if(bankPlayerMap == null ||tradeItemEnum == null){
return null;
}
return bankPlayerMap.get(tradeItemEnum);
}
public void setBankPlayerMap(Map<TradeItemEnum, Set<User>> bankPlayerMap) {
this.bankPlayerMap = bankPlayerMap;
}
public AtomicLong getMiCardDownSeat() {
return miCardDownSeat;
}
public void setMiCardDownSeat(AtomicLong miCardDownSeat) {
this.miCardDownSeat = miCardDownSeat;
}
public Date getCoundDownDate() {
return coundDownDate;
}
public void setCoundDownDate(Date coundDownDate) {
this.coundDownDate = coundDownDate;
}
/**
* 返回指定交易项ID的交易项。
* @param tradeItemId
* @return
*/
@JSONField(deserialize=false,serialize = false)
public TradeItem getTradeItemById(Integer tradeItemId){
for(Play play : this.playList){
Optional<TradeItem> opt = play.getTradeList().stream().filter(item->item.getId().equals(tradeItemId)).findFirst();
if(opt.isPresent()){
return opt.get();
}
}
return null;
}
@JSONField(deserialize=false,serialize = false)
public GameTableInstantStateEnum getInstantStateEnum() {
if(instantState==null)return null;
return GameTableInstantStateEnum.get(instantState);
}
public void setInstantStateEnum(GameTableInstantStateEnum instantStateEnum) {
log.debug("【桌子】: " + this.getGameTablePO().getId() + ",瞬时状态: " + this.instantState +",修改为: " + instantStateEnum);
this.instantState = instantStateEnum.get();
}
@JSONField(deserialize=false,serialize = false)
public Integer getInstantState() {
return instantState;
}
public void setInstantState(Integer instantState) {
this.instantState = instantState;
}
public GameTablePO getGameTablePO() {
return gameTablePO;
}
public void setGameTablePO(GameTablePO gameTablePO) {
this.gameTablePO = gameTablePO;
}
public CheckLimitRule getLimitRule() {
return limitRule;
}
public void setLimitRule(CheckLimitRule limitRule) {
this.limitRule = limitRule;
}
public String getShowStatus() {
GameTableTypeEnum gameTableTypeEnum = this.getGameTablePO().getTypeEnum();
RoundStatusEnum roundStatusEnum = this.round.getRoundPO().getStatusEnum();
if(gameTableTypeEnum == GameTableTypeEnum.MI_BEING
|| gameTableTypeEnum == GameTableTypeEnum.MI_NORMAL ) {
if(roundStatusEnum == RoundStatusEnum.IDLE
|| roundStatusEnum == RoundStatusEnum.SHUFFLE) {
return "洗牌中";
} else if(roundStatusEnum == RoundStatusEnum.NEWGAME
|| roundStatusEnum == RoundStatusEnum.BETTING) {
return "下注中";
} else if(roundStatusEnum == RoundStatusEnum.AWAITING_RESULT) {
return "咪牌中";
} else if(roundStatusEnum == RoundStatusEnum.FINISH) {
return "结算中";
} else if (roundStatusEnum == RoundStatusEnum.PAUSE) {
return "暂停中";
}
} else {
if(roundStatusEnum == RoundStatusEnum.IDLE
|| roundStatusEnum == RoundStatusEnum.SHUFFLE) {
return "洗牌中";
} else if(roundStatusEnum == RoundStatusEnum.NEWGAME
|| roundStatusEnum == RoundStatusEnum.BETTING) {
return "下注中";
} else if(roundStatusEnum == RoundStatusEnum.AWAITING_RESULT
|| roundStatusEnum == RoundStatusEnum.FINISH) {
return "结算中";
} else if (roundStatusEnum == RoundStatusEnum.PAUSE) {
return "暂停中";
}
}
return "空闲中";
}
public Integer getCountDownSeconds() {
return countDownSeconds;
}
public void setCountDownSeconds(Integer countDownSeconds) {
this.countDownSeconds = countDownSeconds;
}
}
| 10,038 | 0.712397 | 0.707025 | 422 | 21.938389 | 22.921894 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.004739 | false | false | 13 |
6a501cb32ec39fb8f0aaa5da1866cdc5a1238706 | 2,456,721,318,037 | 707676c7d213c6814c64f8cf6fdeaed9380e0bb6 | /src/main/java/com/mj/dao/UserDaoImpl.java | 12c38043819a5a414100078831fb193acbd9aca6 | [] | no_license | yjj8353/MyBatis-JavaConfig | https://github.com/yjj8353/MyBatis-JavaConfig | fe544ba6d2caec944405429491da1d1041b54da1 | 79ec48f75a5a637a7e65c6467d64e8a1633d614c | refs/heads/master | 2020-05-07T12:57:53.931000 | 2019-04-19T15:51:48 | 2019-04-19T15:51:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mj.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mj.mapper.UserMapper;
import com.mj.vo.User;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private UserMapper userMapper;
@Override
public void createDummyUser() {
userMapper.createDummyUser();
}
@Override
public User getUserByNoJava(int no) {
return userMapper.getUserByNoJava(no);
}
@Override
public User getUserByNoXml(int no) {
return userMapper.getUserByNoXml(no);
}
@Override
public int createUser(User user) {
userMapper.createUser(user);
int createdUserNo = user.getNo();
return createdUserNo;
}
}
| UTF-8 | Java | 727 | java | UserDaoImpl.java | Java | [] | null | [] | package com.mj.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mj.mapper.UserMapper;
import com.mj.vo.User;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private UserMapper userMapper;
@Override
public void createDummyUser() {
userMapper.createDummyUser();
}
@Override
public User getUserByNoJava(int no) {
return userMapper.getUserByNoJava(no);
}
@Override
public User getUserByNoXml(int no) {
return userMapper.getUserByNoXml(no);
}
@Override
public int createUser(User user) {
userMapper.createUser(user);
int createdUserNo = user.getNo();
return createdUserNo;
}
}
| 727 | 0.757909 | 0.757909 | 37 | 18.648649 | 17.448328 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.243243 | false | false | 13 |
18ddc56c1751f4f2e77cffcb2e2c42c2a1194781 | 38,534,446,585,547 | ce6e01e56935d98c0c0836da64bdf8f5ec7e2219 | /mavenproject1/src/main/java/com/alkanza/utils/ServiceResponse.java | 6672a10bc7fc651089929976a800412903a819d2 | [] | no_license | teddyamora/AlkanzaTest | https://github.com/teddyamora/AlkanzaTest | 04ef5c2ae12a09657f56ded6a69fc46c98340177 | 212c39a1a576daadfc0146e87e6e821f01fb5338 | refs/heads/master | 2021-07-16T17:24:45.357000 | 2017-10-24T00:55:53 | 2017-10-24T00:55:53 | 108,056,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 com.alkanza.utils;
import java.io.Serializable;
/**
* Representacion de objeto para retorno, una vez consumida la API
*
* @author Teddy
*/
public class ServiceResponse implements Serializable {
/**
* Constante con codigo de transaccion exitosa
*/
public static final int SUCCESS = 200;
public static final int POST_SUCCESS = 201;
/**
* Constante con codigo de informacion faltante
*/
public static final int MISSING_INFO = 400;
/**
* Constante con codigo para informar que no fue posible retornar
* informacion
*/
public static final int NOT_FOUND = 404;
/**
* Constante con codigo de error
*/
public static final int ERROR = 500;
int code;
Object message;
/**
* Constructor de la clase ReturnOperation
*
* @param code
* @param message
*/
public ServiceResponse(int code, String message) {
this.code = code;
this.message = message;
}
/**
* Constructor por defecto
*/
public ServiceResponse() {
this.code = ServiceResponse.SUCCESS;
this.message = "OK";
}
/**
*
* @return
*/
public int getCode() {
return code;
}
/**
*
* @param code
*/
public void setCode(int code) {
this.code = code;
}
/**
*
* @return
*/
public Object getMessage() {
return message;
}
/**
*
* @param message
*/
public void setMessage(Object message) {
this.message = message;
}
}
| UTF-8 | Java | 1,881 | java | ServiceResponse.java | Java | [
{
"context": " retorno, una vez consumida la API\r\n *\r\n * @author Teddy\r\n */\r\npublic class ServiceResponse implements Ser",
"end": 345,
"score": 0.9985494613647461,
"start": 340,
"tag": "NAME",
"value": "Teddy"
}
] | null | [] | /*
* 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 com.alkanza.utils;
import java.io.Serializable;
/**
* Representacion de objeto para retorno, una vez consumida la API
*
* @author Teddy
*/
public class ServiceResponse implements Serializable {
/**
* Constante con codigo de transaccion exitosa
*/
public static final int SUCCESS = 200;
public static final int POST_SUCCESS = 201;
/**
* Constante con codigo de informacion faltante
*/
public static final int MISSING_INFO = 400;
/**
* Constante con codigo para informar que no fue posible retornar
* informacion
*/
public static final int NOT_FOUND = 404;
/**
* Constante con codigo de error
*/
public static final int ERROR = 500;
int code;
Object message;
/**
* Constructor de la clase ReturnOperation
*
* @param code
* @param message
*/
public ServiceResponse(int code, String message) {
this.code = code;
this.message = message;
}
/**
* Constructor por defecto
*/
public ServiceResponse() {
this.code = ServiceResponse.SUCCESS;
this.message = "OK";
}
/**
*
* @return
*/
public int getCode() {
return code;
}
/**
*
* @param code
*/
public void setCode(int code) {
this.code = code;
}
/**
*
* @return
*/
public Object getMessage() {
return message;
}
/**
*
* @param message
*/
public void setMessage(Object message) {
this.message = message;
}
}
| 1,881 | 0.548113 | 0.540138 | 96 | 17.59375 | 18.766979 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.229167 | false | false | 9 |
d78f99a1a374fb83a42e7cb724f567d39c55af6a | 18,777,597,074,058 | 2a2f4515fb736ffd17894448115c0d22827071d5 | /parkingpay/src/main/java/net/itgoo/parkingpay/ui/park/ParkingParkFragment.java | f4543de23aad6fa5264277aa7c80b5dc695d13be | [] | no_license | bjhuitou/parking-pay-android | https://github.com/bjhuitou/parking-pay-android | c9bd8f613604bee5d0e05c2ad0e6be18b3b6e361 | 0dd23226af624d417596760c6bce3e1b9658b036 | refs/heads/master | 2022-11-12T09:18:01.380000 | 2020-07-02T07:36:29 | 2020-07-02T07:36:29 | 271,713,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.itgoo.parkingpay.ui.park;
import android.os.Bundle;
import net.itgoo.parkingpay.R;
import net.itgoo.parkingpay.vendor.mvp.ParkingMVPUtils;
import net.itgoo.parkingpay.vendor.widget.fragment.ParkingBaseFragment;
public class ParkingParkFragment extends ParkingBaseFragment {
public static ParkingParkFragment newInstance() {
return new ParkingParkFragment();
}
@Override
protected int getLayoutResourceID() {
return R.layout.parking_fragment_park;
}
@Override
protected void initUI(Bundle savedInstanceState) {
initChildFragment();
}
@Override
protected void initData(Bundle savedInstanceState) {
}
private void initChildFragment() {
ParkingParkChildFragment fragment =
(ParkingParkChildFragment) getChildFragmentManager().findFragmentById(R.id.parking_fragment_park_content_fl);
if (fragment == null) {
fragment = ParkingParkChildFragment.newInstance();
ParkingMVPUtils.addFragmentToActivity(getChildFragmentManager(),
fragment, R.id.parking_fragment_park_content_fl);
}
new ParkingParkPresenter(fragment, new ParkingParkDataRepository());
}
}
| UTF-8 | Java | 1,235 | java | ParkingParkFragment.java | Java | [] | null | [] | package net.itgoo.parkingpay.ui.park;
import android.os.Bundle;
import net.itgoo.parkingpay.R;
import net.itgoo.parkingpay.vendor.mvp.ParkingMVPUtils;
import net.itgoo.parkingpay.vendor.widget.fragment.ParkingBaseFragment;
public class ParkingParkFragment extends ParkingBaseFragment {
public static ParkingParkFragment newInstance() {
return new ParkingParkFragment();
}
@Override
protected int getLayoutResourceID() {
return R.layout.parking_fragment_park;
}
@Override
protected void initUI(Bundle savedInstanceState) {
initChildFragment();
}
@Override
protected void initData(Bundle savedInstanceState) {
}
private void initChildFragment() {
ParkingParkChildFragment fragment =
(ParkingParkChildFragment) getChildFragmentManager().findFragmentById(R.id.parking_fragment_park_content_fl);
if (fragment == null) {
fragment = ParkingParkChildFragment.newInstance();
ParkingMVPUtils.addFragmentToActivity(getChildFragmentManager(),
fragment, R.id.parking_fragment_park_content_fl);
}
new ParkingParkPresenter(fragment, new ParkingParkDataRepository());
}
}
| 1,235 | 0.707692 | 0.707692 | 42 | 28.404762 | 29.59654 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 9 |
f8af86829de440188d99a6ea55f957206c31df5b | 22,162,031,299,388 | 739af9cc4590114233df30bd7c88a1522806a0df | /Spring/exercicioum/exercicioum/src/main/java/com/exercicioum/exercicioum/ExercicioumApplication.java | 7cc85ab66c57acb3e8fcad512b7b3cf52de8429c | [] | no_license | stefanitosi2/turmajava30 | https://github.com/stefanitosi2/turmajava30 | 133b6fe31f300b1779456d5028ef154138c84dc6 | 966a6f69c8d008127767ad3194b1559f7b90918b | refs/heads/main | 2023-08-02T02:49:40.274000 | 2021-09-14T11:54:53 | 2021-09-14T11:54:53 | 388,225,308 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exercicioum.exercicioum;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExercicioumApplication {
public static void main(String[] args) {
SpringApplication.run(ExercicioumApplication.class, args);
}
}
| UTF-8 | Java | 330 | java | ExercicioumApplication.java | Java | [] | null | [] | package com.exercicioum.exercicioum;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExercicioumApplication {
public static void main(String[] args) {
SpringApplication.run(ExercicioumApplication.class, args);
}
}
| 330 | 0.830303 | 0.830303 | 13 | 24.384615 | 24.54051 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 9 |
a013157557d25f78a8d4f76c2fab890f4f668e16 | 2,233,383,011,727 | 3878c754df99c18921028d4a69d7012b9f936976 | /src/main/java/Leetcode387.java | 033b5b39e8ca6c26e4994f6d64d6fb72d45487ce | [
"Apache-2.0"
] | permissive | LiuQ1ang/leetcode | https://github.com/LiuQ1ang/leetcode | 111e28e81d8a1f1f0c34fcd9703d51bd8e919219 | 90df283bf08e6ad64b10eceec0ba03f5155298ee | refs/heads/master | 2022-09-20T09:02:23.427000 | 2020-06-03T13:30:12 | 2020-06-03T13:30:12 | 268,797,954 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.HashMap;
import java.util.Map;
/**
* @author: liuqiang
* @create: 2020-01-19 19:22
*
* 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
*
* 案例:
*
* s = "leetcode"
* 返回 0.
*
* s = "loveleetcode",
* 返回 2.
*
*
* 注意事项:您可以假定该字符串只包含小写字母。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
public class Leetcode387 {
public int firstUniqChar(String s) {
Map<Character, Integer> characterMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
characterMap.put(c, characterMap.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (characterMap.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}
| UTF-8 | Java | 1,101 | java | Leetcode387.java | Java | [
{
"context": "il.HashMap;\nimport java.util.Map;\n\n/**\n * @author: liuqiang\n * @create: 2020-01-19 19:22\n *\n * 给定一个字符串,找到它的第一",
"end": 73,
"score": 0.778627872467041,
"start": 65,
"tag": "USERNAME",
"value": "liuqiang"
}
] | null | [] | import java.util.HashMap;
import java.util.Map;
/**
* @author: liuqiang
* @create: 2020-01-19 19:22
*
* 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
*
* 案例:
*
* s = "leetcode"
* 返回 0.
*
* s = "loveleetcode",
* 返回 2.
*
*
* 注意事项:您可以假定该字符串只包含小写字母。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
public class Leetcode387 {
public int firstUniqChar(String s) {
Map<Character, Integer> characterMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
characterMap.put(c, characterMap.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (characterMap.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}
| 1,101 | 0.545662 | 0.518265 | 42 | 19.857143 | 20.055365 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 9 |
a4a85c7cd3849a6cf1b7b110fdfc5f0cc0a99dd4 | 18,769,007,095,650 | 598c3b7cd354d227d9b908f9809ae2c292e3468a | /Java_advanced/多线程&socket/test/Show.java | 91124ac871afde6c3e30808d93a8f44db422e55e | [] | no_license | chaizhidream/Training_Events | https://github.com/chaizhidream/Training_Events | 35d9c071ba4336be9d52b1ad27252c4cf14a1e7b | 8d9a9ed3284416216aff0b481db029e69d49ce23 | refs/heads/master | 2021-06-29T20:12:35.609000 | 2017-09-19T14:16:43 | 2017-09-19T14:16:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import java.util.Date;
public class Show implements Runnable{
public Show() {
// TODO 自动生成的构造函数存根
}
public void showTime(){
System.out.println(Thread.currentThread().getName()+"输出时间"+new Date());
}
@Override
public synchronized void run() {
for (int i = 0; i <1000; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| GB18030 | Java | 510 | java | Show.java | Java | [] | null | [] | package test;
import java.util.Date;
public class Show implements Runnable{
public Show() {
// TODO 自动生成的构造函数存根
}
public void showTime(){
System.out.println(Thread.currentThread().getName()+"输出时间"+new Date());
}
@Override
public synchronized void run() {
for (int i = 0; i <1000; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 510 | 0.635417 | 0.622917 | 28 | 16.142857 | 18.991943 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.642857 | false | false | 9 |
d7f3cb4d9a6225a93276287a4d48a11c03eae15a | 8,924,942,091,638 | 8e17c72f50d78c52a9ba5837cbf28e0a05470424 | /src/main/java/com/laotek/churchguru/web/client/widget/RoundedCornerPanel.java | 72e12519225bf9baedf7244e8164c580e102fd81 | [] | no_license | larryoke/churchguru-web | https://github.com/larryoke/churchguru-web | 7cbaf6ccfabc96727b9ce13b519c59ec9c449a0f | 2d33a30a59a82d56a8e827e2a59286abf84e70a1 | refs/heads/master | 2021-01-11T14:58:31.286000 | 2018-12-05T17:18:46 | 2018-12-05T17:18:46 | 80,263,931 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.laotek.churchguru.web.client.widget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class RoundedCornerPanel extends Composite {
private SimplePanel topLeftCorner = new SimplePanel();
private SimplePanel topRightCorner = new SimplePanel();
private SimplePanel bottomLeftCorner = new SimplePanel();
private SimplePanel bottomRightCorner = new SimplePanel();
private SimplePanel topSide = new SimplePanel();
private SimplePanel rightSide = new SimplePanel();
private SimplePanel leftSide = new SimplePanel();
private SimplePanel bottomSide = new SimplePanel();
public RoundedCornerPanel(String title, Widget widget) {
VerticalPanel vPanel = new VerticalPanel();
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
vPanel.add(new HTML("<h2>" + title + "</h2>"));
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
public RoundedCornerPanel(Widget widget, Button button) {
button.getElement().setAttribute("style", "margin:0px 40px 0px 25px;");
String label = button.getHTML();
button.setHTML("<img border='0' src='images/app/button-add.png' />"
+ label);
VerticalPanel vPanel = new VerticalPanel();
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
vPanel.add(button);
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
public RoundedCornerPanel(Widget widget, Button button1, Button button2) {
VerticalPanel vPanel = new VerticalPanel();
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.getElement().setAttribute("style",
"margin:0px 40px 0px 25px;");
buttonPanel.add(button1);
buttonPanel.add(new HTML(" "));
buttonPanel.add(new HTML(" "));
buttonPanel.add(new HTML(" "));
buttonPanel.add(button2);
String label = button1.getHTML();
button1.setHTML("<img border='0' src='images/app/button-add.png' />"
+ label);
label = button2.getHTML();
button2.setHTML("<img border='0' src='images/app/button-add.png' />"
+ label);
vPanel.add(buttonPanel);
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
public RoundedCornerPanel(Widget widget) {
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
private SimplePanel initPanel(final Widget widget) {
// style
topLeftCorner.setStylePrimaryName("cornerTL");
topRightCorner.setStylePrimaryName("cornerTR");
bottomLeftCorner.setStylePrimaryName("cornerBL");
bottomRightCorner.setStylePrimaryName("cornerBR");
// style
topSide.setStylePrimaryName("topSide");
rightSide.setStylePrimaryName("rightSide");
leftSide.setStylePrimaryName("leftSide");
bottomSide.setStylePrimaryName("bottomSide");
// add
topRightCorner.add(widget);
topLeftCorner.add(topRightCorner);
bottomRightCorner.add(topLeftCorner);
bottomLeftCorner.add(bottomRightCorner);
// add
rightSide.add(bottomLeftCorner);
leftSide.add(rightSide);
bottomSide.add(leftSide);
topSide.add(bottomSide);
return topSide;
}
}
| UTF-8 | Java | 3,570 | java | RoundedCornerPanel.java | Java | [] | null | [] | package com.laotek.churchguru.web.client.widget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class RoundedCornerPanel extends Composite {
private SimplePanel topLeftCorner = new SimplePanel();
private SimplePanel topRightCorner = new SimplePanel();
private SimplePanel bottomLeftCorner = new SimplePanel();
private SimplePanel bottomRightCorner = new SimplePanel();
private SimplePanel topSide = new SimplePanel();
private SimplePanel rightSide = new SimplePanel();
private SimplePanel leftSide = new SimplePanel();
private SimplePanel bottomSide = new SimplePanel();
public RoundedCornerPanel(String title, Widget widget) {
VerticalPanel vPanel = new VerticalPanel();
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
vPanel.add(new HTML("<h2>" + title + "</h2>"));
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
public RoundedCornerPanel(Widget widget, Button button) {
button.getElement().setAttribute("style", "margin:0px 40px 0px 25px;");
String label = button.getHTML();
button.setHTML("<img border='0' src='images/app/button-add.png' />"
+ label);
VerticalPanel vPanel = new VerticalPanel();
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
vPanel.add(button);
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
public RoundedCornerPanel(Widget widget, Button button1, Button button2) {
VerticalPanel vPanel = new VerticalPanel();
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.getElement().setAttribute("style",
"margin:0px 40px 0px 25px;");
buttonPanel.add(button1);
buttonPanel.add(new HTML(" "));
buttonPanel.add(new HTML(" "));
buttonPanel.add(new HTML(" "));
buttonPanel.add(button2);
String label = button1.getHTML();
button1.setHTML("<img border='0' src='images/app/button-add.png' />"
+ label);
label = button2.getHTML();
button2.setHTML("<img border='0' src='images/app/button-add.png' />"
+ label);
vPanel.add(buttonPanel);
vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
public RoundedCornerPanel(Widget widget) {
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(initPanel(widget));
this.initWidget(vPanel);
}
private SimplePanel initPanel(final Widget widget) {
// style
topLeftCorner.setStylePrimaryName("cornerTL");
topRightCorner.setStylePrimaryName("cornerTR");
bottomLeftCorner.setStylePrimaryName("cornerBL");
bottomRightCorner.setStylePrimaryName("cornerBR");
// style
topSide.setStylePrimaryName("topSide");
rightSide.setStylePrimaryName("rightSide");
leftSide.setStylePrimaryName("leftSide");
bottomSide.setStylePrimaryName("bottomSide");
// add
topRightCorner.add(widget);
topLeftCorner.add(topRightCorner);
bottomRightCorner.add(topLeftCorner);
bottomLeftCorner.add(bottomRightCorner);
// add
rightSide.add(bottomLeftCorner);
leftSide.add(rightSide);
bottomSide.add(leftSide);
topSide.add(bottomSide);
return topSide;
}
}
| 3,570 | 0.764146 | 0.757143 | 103 | 33.660194 | 22.506763 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.378641 | false | false | 9 |
865890df24647916cca4b1c17b70e779f6126713 | 300,647,728,546 | a33cb104caa787a4e3804ea6883efdd484d1a55a | /Project/src/pakage/Main.java | db9b06b8942dff7c5dc8068c56fe95312859f31f | [] | no_license | vanikk7/LAB4 | https://github.com/vanikk7/LAB4 | bc4891fd875f5e2f1a1118472e1757e6ced35cd1 | 06321d0adf7f08d1489e8ee2812962cb6e8188bf | refs/heads/master | 2023-01-31T05:40:55.893000 | 2020-12-18T17:55:51 | 2020-12-18T17:55:51 | 322,667,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pakage;
import java.io.IOException;
public class Main {
/**
* @param args - по умолчанию
* @throws IOException исключение в связи с тех. необходимостями
*/
public static void main(String[] args) throws IOException {
Reader reader = new Reader("name.csv");
Staff[] staff = new Staff[reader.k - 1];
int j = 1;
int i = 0;
while (i < staff.length) {
staff[i] = new Staff(reader.output[j]);
j++;
i++;
}
System.out.println(staff[0].toString());
System.out.println(staff[staff.length - 1].toString());
ReaderTest readerTest = new ReaderTest();
readerTest.TestRead();
}
}
| UTF-8 | Java | 763 | java | Main.java | Java | [] | null | [] | package pakage;
import java.io.IOException;
public class Main {
/**
* @param args - по умолчанию
* @throws IOException исключение в связи с тех. необходимостями
*/
public static void main(String[] args) throws IOException {
Reader reader = new Reader("name.csv");
Staff[] staff = new Staff[reader.k - 1];
int j = 1;
int i = 0;
while (i < staff.length) {
staff[i] = new Staff(reader.output[j]);
j++;
i++;
}
System.out.println(staff[0].toString());
System.out.println(staff[staff.length - 1].toString());
ReaderTest readerTest = new ReaderTest();
readerTest.TestRead();
}
}
| 763 | 0.560669 | 0.553696 | 25 | 27.68 | 21.025166 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 9 |
5d0ea6c525c1b38505a54c32433728439b899eab | 16,166,256,926,901 | 2e74bdd7a4d9bd4337f20cb03a9b42435aa7cae5 | /src/main/java/com/hamusuta/quartzcollect/job/JobInt.java | 28de18a32caf89acb9a85220476ba22c1aa888b1 | [] | no_license | jbw00/quartzcollect | https://github.com/jbw00/quartzcollect | f511235b13ee6d48b0df844ef4e11f866e7474aa | 93d9b7bd91ddf6b87fdf5cc31fb3c4b3a490ff13 | refs/heads/master | 2021-06-14T23:09:33.349000 | 2019-12-26T08:56:09 | 2019-12-26T08:56:09 | 203,814,997 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hamusuta.quartzcollect.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public interface JobInt extends Job{
@Override
void execute(JobExecutionContext context) throws JobExecutionException;
}
| UTF-8 | Java | 275 | java | JobInt.java | Java | [] | null | [] | package com.hamusuta.quartzcollect.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public interface JobInt extends Job{
@Override
void execute(JobExecutionContext context) throws JobExecutionException;
}
| 275 | 0.818182 | 0.818182 | 11 | 24 | 22.970337 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
bf846675a317b6300ab42a9a0b75ee605914f25e | 30,880,814,900,338 | 9e0e4869485bda9d98262d8c246cb6100533949e | /src/main/java/app/hibernate1/ManageEmployee.java | 47c3bc282dce816eeb87bf21740cd32c7994c30a | [] | no_license | angular-git-user/vehicle_configurator | https://github.com/angular-git-user/vehicle_configurator | b7b613ea6fc2fd2ba6d00dfdc54df62744efb3bc | 2cca317fbb04c46def2030b5dece75e65e94b9b2 | refs/heads/master | 2020-05-25T15:42:14.890000 | 2016-09-20T08:16:30 | 2016-09-20T08:16:30 | 64,409,101 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.hibernate1;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main1(String[] args) {
try{
factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
/*Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, 1);
System.out.println(employee);*/
/* Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);*/
/* ME.listEmployees();
ME.updateEmployee(empID1, 5000);
ME.deleteEmployee(empID2);
ME.listEmployees();*/
Session session = factory.openSession();
String hql = "select * from EMPLOYEE e join STD_FACT s on e.ID = s.ID";
//select * from EMPLOYEE e join STD_FACT s on e.ID = s.ID
SQLQuery query = session.createSQLQuery(hql);
query.addEntity(Employee.class).addJoin("e", "e.id");
@SuppressWarnings("rawtypes")
List results = query.list();
System.out.println(results);
}
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
@SuppressWarnings("rawtypes")
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
| UTF-8 | Java | 4,342 | java | ManageEmployee.java | Java | [
{
"context": "\t \n\t /* Integer empID1 = ME.addEmployee(\"Zara\", \"Ali\", 1000);\n\t \tInteger empID2 = ME.addEm",
"end": 982,
"score": 0.9995304942131042,
"start": 978,
"tag": "NAME",
"value": "Zara"
},
{
"context": "\t /* Integer empID1 = ME.addEmployee(\"Zara\"... | null | [] | package app.hibernate1;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main1(String[] args) {
try{
factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
/*Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, 1);
System.out.println(employee);*/
/* Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);*/
/* ME.listEmployees();
ME.updateEmployee(empID1, 5000);
ME.deleteEmployee(empID2);
ME.listEmployees();*/
Session session = factory.openSession();
String hql = "select * from EMPLOYEE e join STD_FACT s on e.ID = s.ID";
//select * from EMPLOYEE e join STD_FACT s on e.ID = s.ID
SQLQuery query = session.createSQLQuery(hql);
query.addEntity(Employee.class).addJoin("e", "e.id");
@SuppressWarnings("rawtypes")
List results = query.list();
System.out.println(results);
}
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
@SuppressWarnings("rawtypes")
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
| 4,342 | 0.586826 | 0.581069 | 128 | 32.921875 | 20.858006 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.679688 | false | false | 9 |
53797510d54cdb79b5bbbab95c06e08f55e71a11 | 29,721,173,738,658 | a3ea54467bd6a5cb7677355eaedaa1b57844ff62 | / lemmings-ricm2013/Lemmings/src/lemmings/Moteur.java | 3c64329fabe489236f9d141b27499e6fc301b73a | [] | no_license | jejeLaVedette/lemmings-ricm2013 | https://github.com/jejeLaVedette/lemmings-ricm2013 | 4fcc219796d9c354342dda4690c183717b368548 | acd25e8a4670ba76c867a07150acec34c5a538a7 | refs/heads/master | 2021-01-21T12:26:40.922000 | 2013-06-23T22:01:27 | 2013-06-23T22:01:27 | 32,139,049 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lemmings;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Moteur implements Constantes {
private static int relief=0;
public static boolean trace = false;
public static void miseAJourObservables() throws IOException
{
for(int i=0;i<Carte.obs.size();i++) {
// Analyse de l'element courant
// Si on a un Lemming
Lemming lem = (Lemming) Carte.obs.get(i);
int x = lem.getX();
int y = lem.getY();
// S'il est sur le point de sortie, +- une certaine tolerance
if(Math.abs(x-Carte.sortie.x)<(toleranceSortie/2) && Math.abs(y-Carte.sortie.y)<toleranceSortie) {
Carte.lemmingSauf++;
Carte.obs.remove(i);
}
// S'il est mort, et ben... il est mort !
if(!Carte.estValide(x, y)) {
Carte.obs.remove(i);
continue;
}
// Analyse de l'environnement du lemming courant
String cond;
int inter = y-1-coeff*3/4;
if(!Carte.estValide(x-1, inter) || !Carte.estValide(x+1, inter) || !Carte.estValide(x, y+1)) {
Carte.obs.remove(i);
continue;
}
// Si presence d'un plafond
if (Carte.map[x][y-1-coeff*3/4].isSol() && Carte.map[x-1][y-1-coeff*3/4].isSol() && Carte.map[x+1][y-1-coeff*3/4].isSol() ||
x>4 && Carte.map[x-5][y].isSol() && Carte.map[x-4][y].isSol() && Carte.map[x-3][y].isSol() &&
Carte.map[x-2][y].isSol() && Carte.map[x][y].isSol() && Carte.map[x+1][y].isSol() &&
Carte.map[x+2][y].isSol() && Carte.map[x+3][y].isSol() && Carte.map[x+4][y].isSol()
&& Carte.map[x+5][y].isSol())
{ cond = "sol"; }
// Presence d'un vide
else
if( ( lem.getDirection()==gauche && Carte.map[x][y+1].isAir() ) ||
( lem.getDirection()==droite && Carte.map[x][y+1].isAir() ) )
cond = "vide";
// Presence d'un mur
else if( (x==0 && lem.getDirection()==gauche) ||
(x==Carte.LARGEUR_CARTE-1 && lem.getDirection()==1) ||
(lem.getDirection()==gauche && Carte.map[x-1][y].isSol() && Carte.map[x-1][y-1].isSol() && Carte.map[x-1][y-2].isSol())||
(lem.getDirection()==droite && Carte.map[x+1][y].isSol() && Carte.map[x+1][y-1].isSol() && Carte.map[x+1][y-2].isSol())
)
{ cond = "mur"; }
else
{ cond = "sol"; }
if (cond=="sol" && Carte.map[lem.getX()][lem.getY()+1].type == typeSolTrampoline) {
if(lem.getDirection()==gauche)
//lem.angle = Math.PI*3/4;
Carte.obs.add(new Lemming(lem.getX(),lem.getY()-1,Math.PI*5/8,30));
else
//lem.angle = Math.PI*3/8;
Carte.obs.add(new Lemming(lem.getX(),lem.getY()-1,Math.PI*3/8,30));
Carte.obs.remove(i);
}
// Calcul du relief
if(cond=="sol") {
relief = 0;
if(lem.getDirection()==gauche) {
if(Carte.map[x-1][y].isSol()) {
relief--;
if(Carte.map[x-1][y-1].isSol()) {
relief--;
if(Carte.map[x-1][y-2].isSol()) relief--;
}
}
if(Carte.map[x-1][y+1].isAir()) {
relief++;
if(Carte.map[x-1][y+2].isAir()) {
relief++;
}
}
}
else {
if(Carte.map[x+1][y].isSol()) {
relief--;
if(Carte.map[x+1][y-1].isSol()) {
relief--;
if(Carte.map[x+1][y-2].isSol()) relief--;
}
}
if(Carte.map[x+1][y+1].isAir()) {
relief++;
if(Carte.map[x+1][y+2].isAir()) {
relief++;
}
}
}
}
// S'il est mort, et ben... il est mort !
if(lem.getEtat()==etatMort && (cond.equals("sol")||cond.equals("mur"))) {
Carte.obs.remove(i);
continue;
}
if(lem.getEtat()==etatMort && cond.equals("vide")) {
tomber(lem);
continue;
}
// Recherche de l'automate correspondant
Automate aut = null;
for(int m=0;m<Jeu.listeAutomates.size();m++) {
if(Jeu.listeAutomates.get(m).identifiant == lem.type) {
aut = Jeu.listeAutomates.get(m); break;
}
}
if(aut == null) {
System.out.println("Modele d'automate introuvable !");
System.exit(1);
}
// Recherche de la transition dans l'automate
int k=0;
while(k<aut.listeTransitions.size()) {
if( aut.listeTransitions.get(k).getEtatInitial()==lem.getEtat() &&
(aut.listeTransitions.get(k).getCondition().equals(cond) || aut.listeTransitions.get(k).getCondition().equals("any"))) break;
k++;
}
if(k==aut.listeTransitions.size()) {
System.out.println("Automate n."+ aut.identifiant +" non-deterministe !");
System.exit(1);
}
// On applique les actions associees
if (aut.listeTransitions.get(k).getActions() != null)
{
for(int l=0;l<aut.listeTransitions.get(k).getActions().size();l++) {
appliquerAction(aut.listeTransitions.get(k).getActions().get(l),lem);
}
}
// On met a jour le champs condPrecedente et eventuellement la micro-action
if(lem.getCondPrecedente()!=cond)
lem.setSousAction(0);
lem.setCondPrecedente(cond);
// On change d'etat, sauf si on n'a pas fini les micro-actions
if(lem.getSousAction()==0)
lem.setEtat(aut.listeTransitions.get(k).getEtatFinal());
} // Fin for(i)
}
private static void appliquerAction(String s, Lemming l) throws IOException {
if(s.equals("marcher"))
marcher(l);
else if(s.equals("retourner"))
retourner(l);
else if(s.equals("tomber"))
tomber(l);
else if(s.equals("bloquer"))
bloquer(l);
else if(s.equals("tomberParapluie"))
tomberParapluie(l);
else if(s.equals("creuser"))
creuser(l);
else if(s.equals("voler"))
voler(l);
else if(s.equals("rebondirsol"))
rebondirsol(l);
else if(s.equals("rebondirmur"))
rebondirmur(l);
else if(s.equals("grimper"))
grimper(l);
else if(s.equals("construireEscalier"))
construireEscalier(l);
else if(s.equals("construire"))
construire(l);
else if(s.equals("construireTrampoline"))
construireTrampoline(l);
else if(s.equals("initTrajectoire"))
initTrajectoire(l);
else if(s.equals("initLemmingBase"))
initLemmingBase(l);
else if(s.equals("exploser"))
exploser(l);
else if(s.equals(" "))
{}
else {
System.out.println("Action invalide !");
System.exit(1);
}
}
private static void marcher(Lemming l) {
if(l.getDirection()==gauche) {
l.image = "Images/lemmingBaseGauche2.png";
l.setX(l.getX()-1);
l.setY(l.getY()+relief);
}
else if(l.getDirection()==droite) {
l.setX(l.getX()+1);
l.setY(l.getY()+relief);
l.image = "Images/lemmingBaseDroite2.png";
}
}
private static void retourner(Lemming l) {
if(l.getDirection()==gauche) {
l.setDirection(1);
l.image = "Images/lemmingBaseGauche2.png";
}
else if(l.getDirection()==droite) {
l.setDirection(0);
l.image = "Images/lemmingBaseDroite2.png";
}
}
private static void tomber(Lemming l) {
if(l.getSousAction()>hauteurLetale) {
l.setEtat(etatMort);
}
else
l.setSousAction(l.getSousAction()+1);
l.setY(l.getY()+1);
l.image = "Images/tombe2.png";
}
private static void bloquer(Lemming l) {
l.image = "Images/lemmingStop2.png";
Carte.map[l.getX()][l.getY()].type = typeSolInvisible;
Carte.map[l.getX()][l.getY()-1].type = typeSolInvisible;
Carte.map[l.getX()][l.getY()-2].type = typeSolInvisible;
Carte.map[l.getX()][l.getY()-3].type = typeSolInvisible;
}
private static void tomberParapluie(Lemming l) {
l.setY(l.getY()+1);
l.image = "Images/parapluie2.png";
}
private static void creuser(Lemming l) throws IOException {
if(l.getSousAction()%delaiSousAction==0) {
int x,y;
y = l.getY();
x = l.getX();
BufferedImage arrierePlan=ImageIO.read(new File(Carte.background));
for(int i=0;i<(coeff/2);i++) {
Carte.map[x+i][y] = new Air(new Color(arrierePlan.getRGB(x+i,y)));
Carte.map[x-i][y] = new Air(new Color(arrierePlan.getRGB(x-i,y)));
}
l.setY(y+1);
}
l.setSousAction((l.getSousAction()+1)%(profondeurCreuser*delaiSousAction));
}
private static void initTrajectoire(Lemming l) {
trajectoireparaphysique t=new trajectoireparaphysique(l.getX(),l.getY(),l.puissance,l.angle,1);
l.setTrajpara(t);
if(l.getDirection()==droite)
l.image = "Images/catapulteDroite2.png";
else
l.image = "Images/catapulteGauche2.png";
}
private static void voler(Lemming l) {
trajectoireparaphysique t = l.getTrajH();
Point traj=t.trajectoire(l.time);
double x=traj.getX();
double y=traj.getY();
Point pReel = Moteur.collisionTrajectoire(new Point(l.getX(),l.getY()), new Point((int)t.calculx(l.time),(int)t.calculy(l.time)));
if(hasColision(x,y)){
l.setX(pReel.x);
l.setY(pReel.y);
}
else{
l.setX((int)x);
l.setY((int)y);
}
l.setTime();
if(trace && Carte.estValide(l.getX(), l.getY())) Carte.map[l.getX()][l.getY()].couleur = new Color(255,0,0);
}
private static void rebondirsol(Lemming l) {
trajectoireparaphysique t= l.getTrajH();
Point traj=t.trajectoire(l.time);
Point trajprec=t.trajectoire(l.time-2*deltat);
double x=traj.getX();
double y=traj.getY();
double xp=trajprec.getX();
double yp=trajprec.getY();
l.setXp(xp);
l.setYp(yp);
l.setX((int)xp);
l.setY((int)yp);
t.calculcolision(x, y, l.getXp() , l.getYp(),l.getX(),l.getY() , l.getElasticite(),0.2, false);
if (Math.sqrt(t.getVx()*t.getVx() +t.getVy()*t.getVy()) > 1){
l.setTrajpara(t);
if (trace && Carte.estValide(l.getX(), l.getY())) Carte.map[l.getX()][l.getY()].couleur = new Color(0,0,255);
l.resetTime();
voler(l);
}
}
private static void rebondirmur(Lemming l) {
trajectoireparaphysique t= l.getTrajH() ;
Point traj=t.trajectoire(l.time);
Point trajprec=t.trajectoire(l.time-2*deltat);
double x=traj.getX();
double y=traj.getY();
double xp=trajprec.getX();
double yp=trajprec.getY();
l.setXp(xp);
l.setYp(yp);
l.setX((int)xp);
l.setY((int)yp);
t.calculcolision(x, y, l.getXp() , l.getYp(),l.getX(),l.getY() , l.getElasticite(),0.5, true);
retourner(l);
if (Math.sqrt(t.getVx()*t.getVx() +t.getVy()*t.getVy()) > 1){
l.setTrajpara(t);
if (trace && Carte.estValide(l.getX(), l.getY())) Carte.map[l.getX()][l.getY()].couleur = new Color(0,255,0);
l.resetTime();
voler(l);
}
}
private static void grimper(Lemming l) {
l.setY(l.getY()-1);
}
private static void initLemmingBase(Lemming l) {
l.setType(lemmingBase);
l.setEtat(etatInitial);
}
private static void construire(Lemming l) {
int x,y;
y = l.getY();
x = l.getX();
if(l.direction==droite)
for(int i=0;i<(coeff/2);i++) {
if(Carte.map[x+i][y].isAir())
Carte.map[x+i][y] = new Sol(new Color(150,0,0));
}
else
for(int i=0;i<(coeff/2);i++) {
Carte.map[x-i][y] = new Sol(new Color(150,0,0));
}
}
private static void construireTrampoline(Lemming l) {
int x,y;
y = l.getY();
x = l.getX();
if(l.direction==droite) {
for(int i=0;i<(coeff);i++) {
if(Carte.map[x+i][y].isAir())
Carte.map[x+i][y] = new Sol(new Color(0,255,255));
}
Carte.map[x+coeff/2][y] = new Sol(new Color(0,255,255),typeSolTrampoline);
}
else {
for(int i=0;i<(coeff);i++) {
if (Carte.estValide(x-i, y))
Carte.map[x-i][y] = new Sol(new Color(0,255,255));
}
Carte.map[x-coeff/2][y] = new Sol(new Color(0,255,255),typeSolTrampoline);
}
}
private static void construireEscalier(Lemming l) {
if(l.getSousAction()%delaiSousAction==0)
construire(l);
if(l.getSousAction()%delaiSousAction==1)
marcher(l);
l.setSousAction((l.getSousAction()+1)%(nbMarche*delaiSousAction));
}
private static void exploser(Lemming l) throws IOException {
double fi;
int x,y;
BufferedImage arrierePlan=ImageIO.read(new File(Carte.background));
for(double rayon=0;rayon<rayonBombe;rayon++) {
for(fi=0;fi<2*Math.PI;fi+=0.001) {
x = l.getX() + (int)(rayon*Math.cos(fi));
y = l.getY() + (int)(rayon*Math.sin(fi));
if(Carte.estValide(x, y))
Carte.map[x][y] = new Air(new Color(arrierePlan.getRGB(x,y)));
}
}
Carte.obs.remove(l);
}
public static Point collisionTrajectoire (Point pCourant, Point pDest) {
int coeffDirecteur;
int yCourant = pCourant.y;
Point rep= new Point(0,0);
int i=0;
if((pDest.x - pCourant.x)!=0){
coeffDirecteur = (int)((pDest.getY() - pCourant.getY())/(pDest.getX() - pCourant.getX()));
int constante = pCourant.y - coeffDirecteur * pCourant.x;
i = pCourant.x;
if (pCourant.x < pDest.getX()) {
while (i< pDest.getX() ) {
yCourant = coeffDirecteur * i + constante;
if (!Carte.estValide(i, yCourant) || Carte.map[i][yCourant].isSol()){
break; }
i++;
}
rep.x=i;
rep.y=coeffDirecteur * i + constante;
}
else {
while (i> pDest.x) {
yCourant = coeffDirecteur * i + constante;
if (!Carte.estValide(i, yCourant) || Carte.map[i][yCourant].isSol()){
break;
}
i--;
}
rep.x=i;
rep.y=coeffDirecteur * i + constante;
}
}
else{
i=pCourant.y;
if (pCourant.y < pDest.getY()){
while(i<pDest.getY()){
if (!Carte.estValide(pCourant.x, i) || Carte.map[pCourant.x][i].isSol()){
break;
}
i++;
}
rep.x=pCourant.x;
rep.y=i;
}
else{
while(i>pDest.getY()){
if (!Carte.estValide(pCourant.x, i) || Carte.map[pCourant.x][i].isSol()){
break;
}
i--;
}
rep.x=pCourant.x;
rep.y=i;
}
}
return rep;
}
public static boolean hasColision(double x,double y){
if ((int)x<0 || (int)x>Carte.LARGEUR_CARTE-1 || (int)y<0 || (int)y>Carte.HAUTEUR_CARTE-1 || Carte.map[(int)x][(int)y].isSol()){
return true;
}
else
return false;
}
} | UTF-8 | Java | 13,636 | java | Moteur.java | Java | [] | null | [] | package lemmings;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Moteur implements Constantes {
private static int relief=0;
public static boolean trace = false;
public static void miseAJourObservables() throws IOException
{
for(int i=0;i<Carte.obs.size();i++) {
// Analyse de l'element courant
// Si on a un Lemming
Lemming lem = (Lemming) Carte.obs.get(i);
int x = lem.getX();
int y = lem.getY();
// S'il est sur le point de sortie, +- une certaine tolerance
if(Math.abs(x-Carte.sortie.x)<(toleranceSortie/2) && Math.abs(y-Carte.sortie.y)<toleranceSortie) {
Carte.lemmingSauf++;
Carte.obs.remove(i);
}
// S'il est mort, et ben... il est mort !
if(!Carte.estValide(x, y)) {
Carte.obs.remove(i);
continue;
}
// Analyse de l'environnement du lemming courant
String cond;
int inter = y-1-coeff*3/4;
if(!Carte.estValide(x-1, inter) || !Carte.estValide(x+1, inter) || !Carte.estValide(x, y+1)) {
Carte.obs.remove(i);
continue;
}
// Si presence d'un plafond
if (Carte.map[x][y-1-coeff*3/4].isSol() && Carte.map[x-1][y-1-coeff*3/4].isSol() && Carte.map[x+1][y-1-coeff*3/4].isSol() ||
x>4 && Carte.map[x-5][y].isSol() && Carte.map[x-4][y].isSol() && Carte.map[x-3][y].isSol() &&
Carte.map[x-2][y].isSol() && Carte.map[x][y].isSol() && Carte.map[x+1][y].isSol() &&
Carte.map[x+2][y].isSol() && Carte.map[x+3][y].isSol() && Carte.map[x+4][y].isSol()
&& Carte.map[x+5][y].isSol())
{ cond = "sol"; }
// Presence d'un vide
else
if( ( lem.getDirection()==gauche && Carte.map[x][y+1].isAir() ) ||
( lem.getDirection()==droite && Carte.map[x][y+1].isAir() ) )
cond = "vide";
// Presence d'un mur
else if( (x==0 && lem.getDirection()==gauche) ||
(x==Carte.LARGEUR_CARTE-1 && lem.getDirection()==1) ||
(lem.getDirection()==gauche && Carte.map[x-1][y].isSol() && Carte.map[x-1][y-1].isSol() && Carte.map[x-1][y-2].isSol())||
(lem.getDirection()==droite && Carte.map[x+1][y].isSol() && Carte.map[x+1][y-1].isSol() && Carte.map[x+1][y-2].isSol())
)
{ cond = "mur"; }
else
{ cond = "sol"; }
if (cond=="sol" && Carte.map[lem.getX()][lem.getY()+1].type == typeSolTrampoline) {
if(lem.getDirection()==gauche)
//lem.angle = Math.PI*3/4;
Carte.obs.add(new Lemming(lem.getX(),lem.getY()-1,Math.PI*5/8,30));
else
//lem.angle = Math.PI*3/8;
Carte.obs.add(new Lemming(lem.getX(),lem.getY()-1,Math.PI*3/8,30));
Carte.obs.remove(i);
}
// Calcul du relief
if(cond=="sol") {
relief = 0;
if(lem.getDirection()==gauche) {
if(Carte.map[x-1][y].isSol()) {
relief--;
if(Carte.map[x-1][y-1].isSol()) {
relief--;
if(Carte.map[x-1][y-2].isSol()) relief--;
}
}
if(Carte.map[x-1][y+1].isAir()) {
relief++;
if(Carte.map[x-1][y+2].isAir()) {
relief++;
}
}
}
else {
if(Carte.map[x+1][y].isSol()) {
relief--;
if(Carte.map[x+1][y-1].isSol()) {
relief--;
if(Carte.map[x+1][y-2].isSol()) relief--;
}
}
if(Carte.map[x+1][y+1].isAir()) {
relief++;
if(Carte.map[x+1][y+2].isAir()) {
relief++;
}
}
}
}
// S'il est mort, et ben... il est mort !
if(lem.getEtat()==etatMort && (cond.equals("sol")||cond.equals("mur"))) {
Carte.obs.remove(i);
continue;
}
if(lem.getEtat()==etatMort && cond.equals("vide")) {
tomber(lem);
continue;
}
// Recherche de l'automate correspondant
Automate aut = null;
for(int m=0;m<Jeu.listeAutomates.size();m++) {
if(Jeu.listeAutomates.get(m).identifiant == lem.type) {
aut = Jeu.listeAutomates.get(m); break;
}
}
if(aut == null) {
System.out.println("Modele d'automate introuvable !");
System.exit(1);
}
// Recherche de la transition dans l'automate
int k=0;
while(k<aut.listeTransitions.size()) {
if( aut.listeTransitions.get(k).getEtatInitial()==lem.getEtat() &&
(aut.listeTransitions.get(k).getCondition().equals(cond) || aut.listeTransitions.get(k).getCondition().equals("any"))) break;
k++;
}
if(k==aut.listeTransitions.size()) {
System.out.println("Automate n."+ aut.identifiant +" non-deterministe !");
System.exit(1);
}
// On applique les actions associees
if (aut.listeTransitions.get(k).getActions() != null)
{
for(int l=0;l<aut.listeTransitions.get(k).getActions().size();l++) {
appliquerAction(aut.listeTransitions.get(k).getActions().get(l),lem);
}
}
// On met a jour le champs condPrecedente et eventuellement la micro-action
if(lem.getCondPrecedente()!=cond)
lem.setSousAction(0);
lem.setCondPrecedente(cond);
// On change d'etat, sauf si on n'a pas fini les micro-actions
if(lem.getSousAction()==0)
lem.setEtat(aut.listeTransitions.get(k).getEtatFinal());
} // Fin for(i)
}
private static void appliquerAction(String s, Lemming l) throws IOException {
if(s.equals("marcher"))
marcher(l);
else if(s.equals("retourner"))
retourner(l);
else if(s.equals("tomber"))
tomber(l);
else if(s.equals("bloquer"))
bloquer(l);
else if(s.equals("tomberParapluie"))
tomberParapluie(l);
else if(s.equals("creuser"))
creuser(l);
else if(s.equals("voler"))
voler(l);
else if(s.equals("rebondirsol"))
rebondirsol(l);
else if(s.equals("rebondirmur"))
rebondirmur(l);
else if(s.equals("grimper"))
grimper(l);
else if(s.equals("construireEscalier"))
construireEscalier(l);
else if(s.equals("construire"))
construire(l);
else if(s.equals("construireTrampoline"))
construireTrampoline(l);
else if(s.equals("initTrajectoire"))
initTrajectoire(l);
else if(s.equals("initLemmingBase"))
initLemmingBase(l);
else if(s.equals("exploser"))
exploser(l);
else if(s.equals(" "))
{}
else {
System.out.println("Action invalide !");
System.exit(1);
}
}
private static void marcher(Lemming l) {
if(l.getDirection()==gauche) {
l.image = "Images/lemmingBaseGauche2.png";
l.setX(l.getX()-1);
l.setY(l.getY()+relief);
}
else if(l.getDirection()==droite) {
l.setX(l.getX()+1);
l.setY(l.getY()+relief);
l.image = "Images/lemmingBaseDroite2.png";
}
}
private static void retourner(Lemming l) {
if(l.getDirection()==gauche) {
l.setDirection(1);
l.image = "Images/lemmingBaseGauche2.png";
}
else if(l.getDirection()==droite) {
l.setDirection(0);
l.image = "Images/lemmingBaseDroite2.png";
}
}
private static void tomber(Lemming l) {
if(l.getSousAction()>hauteurLetale) {
l.setEtat(etatMort);
}
else
l.setSousAction(l.getSousAction()+1);
l.setY(l.getY()+1);
l.image = "Images/tombe2.png";
}
private static void bloquer(Lemming l) {
l.image = "Images/lemmingStop2.png";
Carte.map[l.getX()][l.getY()].type = typeSolInvisible;
Carte.map[l.getX()][l.getY()-1].type = typeSolInvisible;
Carte.map[l.getX()][l.getY()-2].type = typeSolInvisible;
Carte.map[l.getX()][l.getY()-3].type = typeSolInvisible;
}
private static void tomberParapluie(Lemming l) {
l.setY(l.getY()+1);
l.image = "Images/parapluie2.png";
}
private static void creuser(Lemming l) throws IOException {
if(l.getSousAction()%delaiSousAction==0) {
int x,y;
y = l.getY();
x = l.getX();
BufferedImage arrierePlan=ImageIO.read(new File(Carte.background));
for(int i=0;i<(coeff/2);i++) {
Carte.map[x+i][y] = new Air(new Color(arrierePlan.getRGB(x+i,y)));
Carte.map[x-i][y] = new Air(new Color(arrierePlan.getRGB(x-i,y)));
}
l.setY(y+1);
}
l.setSousAction((l.getSousAction()+1)%(profondeurCreuser*delaiSousAction));
}
private static void initTrajectoire(Lemming l) {
trajectoireparaphysique t=new trajectoireparaphysique(l.getX(),l.getY(),l.puissance,l.angle,1);
l.setTrajpara(t);
if(l.getDirection()==droite)
l.image = "Images/catapulteDroite2.png";
else
l.image = "Images/catapulteGauche2.png";
}
private static void voler(Lemming l) {
trajectoireparaphysique t = l.getTrajH();
Point traj=t.trajectoire(l.time);
double x=traj.getX();
double y=traj.getY();
Point pReel = Moteur.collisionTrajectoire(new Point(l.getX(),l.getY()), new Point((int)t.calculx(l.time),(int)t.calculy(l.time)));
if(hasColision(x,y)){
l.setX(pReel.x);
l.setY(pReel.y);
}
else{
l.setX((int)x);
l.setY((int)y);
}
l.setTime();
if(trace && Carte.estValide(l.getX(), l.getY())) Carte.map[l.getX()][l.getY()].couleur = new Color(255,0,0);
}
private static void rebondirsol(Lemming l) {
trajectoireparaphysique t= l.getTrajH();
Point traj=t.trajectoire(l.time);
Point trajprec=t.trajectoire(l.time-2*deltat);
double x=traj.getX();
double y=traj.getY();
double xp=trajprec.getX();
double yp=trajprec.getY();
l.setXp(xp);
l.setYp(yp);
l.setX((int)xp);
l.setY((int)yp);
t.calculcolision(x, y, l.getXp() , l.getYp(),l.getX(),l.getY() , l.getElasticite(),0.2, false);
if (Math.sqrt(t.getVx()*t.getVx() +t.getVy()*t.getVy()) > 1){
l.setTrajpara(t);
if (trace && Carte.estValide(l.getX(), l.getY())) Carte.map[l.getX()][l.getY()].couleur = new Color(0,0,255);
l.resetTime();
voler(l);
}
}
private static void rebondirmur(Lemming l) {
trajectoireparaphysique t= l.getTrajH() ;
Point traj=t.trajectoire(l.time);
Point trajprec=t.trajectoire(l.time-2*deltat);
double x=traj.getX();
double y=traj.getY();
double xp=trajprec.getX();
double yp=trajprec.getY();
l.setXp(xp);
l.setYp(yp);
l.setX((int)xp);
l.setY((int)yp);
t.calculcolision(x, y, l.getXp() , l.getYp(),l.getX(),l.getY() , l.getElasticite(),0.5, true);
retourner(l);
if (Math.sqrt(t.getVx()*t.getVx() +t.getVy()*t.getVy()) > 1){
l.setTrajpara(t);
if (trace && Carte.estValide(l.getX(), l.getY())) Carte.map[l.getX()][l.getY()].couleur = new Color(0,255,0);
l.resetTime();
voler(l);
}
}
private static void grimper(Lemming l) {
l.setY(l.getY()-1);
}
private static void initLemmingBase(Lemming l) {
l.setType(lemmingBase);
l.setEtat(etatInitial);
}
private static void construire(Lemming l) {
int x,y;
y = l.getY();
x = l.getX();
if(l.direction==droite)
for(int i=0;i<(coeff/2);i++) {
if(Carte.map[x+i][y].isAir())
Carte.map[x+i][y] = new Sol(new Color(150,0,0));
}
else
for(int i=0;i<(coeff/2);i++) {
Carte.map[x-i][y] = new Sol(new Color(150,0,0));
}
}
private static void construireTrampoline(Lemming l) {
int x,y;
y = l.getY();
x = l.getX();
if(l.direction==droite) {
for(int i=0;i<(coeff);i++) {
if(Carte.map[x+i][y].isAir())
Carte.map[x+i][y] = new Sol(new Color(0,255,255));
}
Carte.map[x+coeff/2][y] = new Sol(new Color(0,255,255),typeSolTrampoline);
}
else {
for(int i=0;i<(coeff);i++) {
if (Carte.estValide(x-i, y))
Carte.map[x-i][y] = new Sol(new Color(0,255,255));
}
Carte.map[x-coeff/2][y] = new Sol(new Color(0,255,255),typeSolTrampoline);
}
}
private static void construireEscalier(Lemming l) {
if(l.getSousAction()%delaiSousAction==0)
construire(l);
if(l.getSousAction()%delaiSousAction==1)
marcher(l);
l.setSousAction((l.getSousAction()+1)%(nbMarche*delaiSousAction));
}
private static void exploser(Lemming l) throws IOException {
double fi;
int x,y;
BufferedImage arrierePlan=ImageIO.read(new File(Carte.background));
for(double rayon=0;rayon<rayonBombe;rayon++) {
for(fi=0;fi<2*Math.PI;fi+=0.001) {
x = l.getX() + (int)(rayon*Math.cos(fi));
y = l.getY() + (int)(rayon*Math.sin(fi));
if(Carte.estValide(x, y))
Carte.map[x][y] = new Air(new Color(arrierePlan.getRGB(x,y)));
}
}
Carte.obs.remove(l);
}
public static Point collisionTrajectoire (Point pCourant, Point pDest) {
int coeffDirecteur;
int yCourant = pCourant.y;
Point rep= new Point(0,0);
int i=0;
if((pDest.x - pCourant.x)!=0){
coeffDirecteur = (int)((pDest.getY() - pCourant.getY())/(pDest.getX() - pCourant.getX()));
int constante = pCourant.y - coeffDirecteur * pCourant.x;
i = pCourant.x;
if (pCourant.x < pDest.getX()) {
while (i< pDest.getX() ) {
yCourant = coeffDirecteur * i + constante;
if (!Carte.estValide(i, yCourant) || Carte.map[i][yCourant].isSol()){
break; }
i++;
}
rep.x=i;
rep.y=coeffDirecteur * i + constante;
}
else {
while (i> pDest.x) {
yCourant = coeffDirecteur * i + constante;
if (!Carte.estValide(i, yCourant) || Carte.map[i][yCourant].isSol()){
break;
}
i--;
}
rep.x=i;
rep.y=coeffDirecteur * i + constante;
}
}
else{
i=pCourant.y;
if (pCourant.y < pDest.getY()){
while(i<pDest.getY()){
if (!Carte.estValide(pCourant.x, i) || Carte.map[pCourant.x][i].isSol()){
break;
}
i++;
}
rep.x=pCourant.x;
rep.y=i;
}
else{
while(i>pDest.getY()){
if (!Carte.estValide(pCourant.x, i) || Carte.map[pCourant.x][i].isSol()){
break;
}
i--;
}
rep.x=pCourant.x;
rep.y=i;
}
}
return rep;
}
public static boolean hasColision(double x,double y){
if ((int)x<0 || (int)x>Carte.LARGEUR_CARTE-1 || (int)y<0 || (int)y>Carte.HAUTEUR_CARTE-1 || Carte.map[(int)x][(int)y].isSol()){
return true;
}
else
return false;
}
} | 13,636 | 0.603256 | 0.588589 | 526 | 24.925856 | 26.008192 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.095057 | false | false | 9 |
486300dd7689fac5cb75091fad590b8de87c17f4 | 29,111,288,390,907 | 2e0ee666fb3e8cbdcf5b03e8d779bf0cf26120d7 | /cn/edu/sdut/goods/dao/goodsDao.java | 4a47df9074a1194376b4e9cdd062667fd36c739f | [] | no_license | allen-alt/lovebox | https://github.com/allen-alt/lovebox | da1a10471619d2e37cdfbd512f121c0c765c5222 | 6dbd593f0403f6e0073da1d8b9c20dbfb2a0e0d6 | refs/heads/master | 2022-11-26T23:09:28.563000 | 2020-07-14T03:29:29 | 2020-07-14T03:29:29 | 276,781,723 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.sdut.goods.dao;
import java.util.List;
import cn.edu.sdut.goods.entity.Goods;
public interface goodsDao {
List<Goods> queryAllGoods(Goods goods);
Goods queryGoodsById(Integer goodsid);
int updateGoods(Goods goods);
//新增商品
int addGoods(Goods goods);
//删除商品
int deleteGoods(Integer goodsid);
}
| UTF-8 | Java | 351 | java | goodsDao.java | Java | [] | null | [] | package cn.edu.sdut.goods.dao;
import java.util.List;
import cn.edu.sdut.goods.entity.Goods;
public interface goodsDao {
List<Goods> queryAllGoods(Goods goods);
Goods queryGoodsById(Integer goodsid);
int updateGoods(Goods goods);
//新增商品
int addGoods(Goods goods);
//删除商品
int deleteGoods(Integer goodsid);
}
| 351 | 0.722388 | 0.722388 | 16 | 18.9375 | 15.46152 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
93ac726d16400c1dc62948de67ad427d91e2362e | 32,409,823,247,702 | 210902bf7cb3a2545f65cb92c952ed9d5c7c48bb | /src/com/gpstaxi/map/GPSTaxiMapper.java | ac50e86f9415dd10aea9df57681c8617b5bc5388 | [] | no_license | ranjitsaurav/TodaiWork | https://github.com/ranjitsaurav/TodaiWork | 48b3d54a6f2652765c1aba85a6a051f630f61ea2 | fcc1c41f04be63793818cbb965e3a7cba16c002a | refs/heads/master | 2016-09-14T12:21:47.705000 | 2016-08-16T06:04:29 | 2016-08-16T06:04:29 | 59,256,818 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gpstaxi.map;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import com.gpstaxi.filternoise.CheckErrorImei;
import com.gpstaxi.gpsdatapoint.CustomDataType;
import com.gpstaxi.gpsdatapoint.GPSDataPoint;
import com.gpstaxi.index.CreateSpatialIndex;
import com.gpstaxi.index.GPSDataCollection;
import com.gpstaxi.index.SearchSpatialIndexHd;
import com.gpstaxi.utility.DateParser;
import com.gpstaxi.utility.TimeMapper;
public class GPSTaxiMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, CustomDataType> {
private Text key = new Text();
private CustomDataType value = new CustomDataType();
public HashMap<String, String> imei_with_time = new HashMap<String, String>();
DecimalFormat df = new DecimalFormat("0.000");
int imei_hashcode = 0;
SearchSpatialIndexHd search_GPS_point = new SearchSpatialIndexHd();
boolean isFirstInstance = true;
private String ROADLINK;
public void configure(JobConf conf) {
ROADLINK = conf.get("ROADLINK");
}
@Override
public void map(LongWritable _key, Text _values, OutputCollector<Text, CustomDataType> _output, Reporter _reporter)
throws IOException {
String unix_date_time = "";
String[] date_time;
try {
String temp_row_value = _values.toString();
GPSDataPoint record = GPSDataPoint.parse(temp_row_value);
//System.out.println(record.imei);
if (record != null) {
// date_time format yyyy-MMM-dd HH:mm:ss
// date_time[0] yyyy-MMM-dd
// date_time[1] HH:mm:ss
unix_date_time = DateParser.parseUnixTimeStamp(record.timestamp);
date_time = unix_date_time.split(" ");
String key_grid_time = String
.valueOf(TimeMapper.mapTimeOneHour(DateParser.timeToMinutes(date_time[1].trim())));
Long searched_link_id = record.id;
//key = new Text(searched_link_id + "," + key_grid_time + "," + index_data_collection.timestamp_); // This is related to the sorting of the data
key = new Text(searched_link_id + "," + key_grid_time);
value.set(record.imei, record.latitude, record.longitude, record.speed, record.direction,
record.errordop, record.acceleration, record.meter, record.timestamp, record.datasource);
_output.collect(key, value);
/*
Map<String, GPSDataCollection> index_collection =
search_GPS_point.index_collection;
if (!index_collection.isEmpty()) {
Iterator iterator_collection =
index_collection.entrySet().iterator();
while (iterator_collection.hasNext()) { Map.Entry
key_value_pair = (Map.Entry) iterator_collection.next();
GPSDataCollection gps_data_parameter = (GPSDataCollection)
key_value_pair.getValue();
key = new Text(key_value_pair.getKey() + "," + key_grid_time
+ "," + gps_data_parameter.timestamp_); //key = new
Text(key_value_pair.getKey() + "," + key_grid_time);
value.set(gps_data_parameter.imei_,
gps_data_parameter.latitude_, gps_data_parameter.longitude_,
gps_data_parameter.speed_, gps_data_parameter.direction_,
gps_data_parameter.errordop_,
gps_data_parameter.acceleration_, gps_data_parameter.meter_,
gps_data_parameter.timestamp_,
gps_data_parameter.datasource_);
_output.collect(key, value);
iterator_collection.remove();
}
search_GPS_point.index_collection.clear(); } */
}
} catch (Exception ex) {
System.out.println("Mapper : " + ex.toString());
ex.printStackTrace();
} finally {
}
}
}
| UTF-8 | Java | 3,795 | java | GPSTaxiMapper.java | Java | [] | null | [] | package com.gpstaxi.map;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import com.gpstaxi.filternoise.CheckErrorImei;
import com.gpstaxi.gpsdatapoint.CustomDataType;
import com.gpstaxi.gpsdatapoint.GPSDataPoint;
import com.gpstaxi.index.CreateSpatialIndex;
import com.gpstaxi.index.GPSDataCollection;
import com.gpstaxi.index.SearchSpatialIndexHd;
import com.gpstaxi.utility.DateParser;
import com.gpstaxi.utility.TimeMapper;
public class GPSTaxiMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, CustomDataType> {
private Text key = new Text();
private CustomDataType value = new CustomDataType();
public HashMap<String, String> imei_with_time = new HashMap<String, String>();
DecimalFormat df = new DecimalFormat("0.000");
int imei_hashcode = 0;
SearchSpatialIndexHd search_GPS_point = new SearchSpatialIndexHd();
boolean isFirstInstance = true;
private String ROADLINK;
public void configure(JobConf conf) {
ROADLINK = conf.get("ROADLINK");
}
@Override
public void map(LongWritable _key, Text _values, OutputCollector<Text, CustomDataType> _output, Reporter _reporter)
throws IOException {
String unix_date_time = "";
String[] date_time;
try {
String temp_row_value = _values.toString();
GPSDataPoint record = GPSDataPoint.parse(temp_row_value);
//System.out.println(record.imei);
if (record != null) {
// date_time format yyyy-MMM-dd HH:mm:ss
// date_time[0] yyyy-MMM-dd
// date_time[1] HH:mm:ss
unix_date_time = DateParser.parseUnixTimeStamp(record.timestamp);
date_time = unix_date_time.split(" ");
String key_grid_time = String
.valueOf(TimeMapper.mapTimeOneHour(DateParser.timeToMinutes(date_time[1].trim())));
Long searched_link_id = record.id;
//key = new Text(searched_link_id + "," + key_grid_time + "," + index_data_collection.timestamp_); // This is related to the sorting of the data
key = new Text(searched_link_id + "," + key_grid_time);
value.set(record.imei, record.latitude, record.longitude, record.speed, record.direction,
record.errordop, record.acceleration, record.meter, record.timestamp, record.datasource);
_output.collect(key, value);
/*
Map<String, GPSDataCollection> index_collection =
search_GPS_point.index_collection;
if (!index_collection.isEmpty()) {
Iterator iterator_collection =
index_collection.entrySet().iterator();
while (iterator_collection.hasNext()) { Map.Entry
key_value_pair = (Map.Entry) iterator_collection.next();
GPSDataCollection gps_data_parameter = (GPSDataCollection)
key_value_pair.getValue();
key = new Text(key_value_pair.getKey() + "," + key_grid_time
+ "," + gps_data_parameter.timestamp_); //key = new
Text(key_value_pair.getKey() + "," + key_grid_time);
value.set(gps_data_parameter.imei_,
gps_data_parameter.latitude_, gps_data_parameter.longitude_,
gps_data_parameter.speed_, gps_data_parameter.direction_,
gps_data_parameter.errordop_,
gps_data_parameter.acceleration_, gps_data_parameter.meter_,
gps_data_parameter.timestamp_,
gps_data_parameter.datasource_);
_output.collect(key, value);
iterator_collection.remove();
}
search_GPS_point.index_collection.clear(); } */
}
} catch (Exception ex) {
System.out.println("Mapper : " + ex.toString());
ex.printStackTrace();
} finally {
}
}
}
| 3,795 | 0.700922 | 0.698814 | 119 | 30.882353 | 28.239128 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.932773 | false | false | 9 |
5d119b94714bfcdfa508931c33e0c2e26f6c5bb4 | 8,143,258,034,428 | c63943257304cd49240d7cba490575f1c4d38330 | /src/gestion_parc_informatique/view/ActionListener/Salle/ValiderFormulaireSupprimerSalleActionListener.java | c92c80f3a10ec366631322c1775973f0eb8b9ca9 | [] | no_license | pierro72/gpi | https://github.com/pierro72/gpi | e21e7b90801892ba6b590e74dc2a0b1ce0b9874a | e533e90a7ae2b35d877931981bdfed3bb0357d8c | refs/heads/master | 2016-08-09T13:39:15.508000 | 2016-01-25T08:12:59 | 2016-01-25T08:12:59 | 49,444,702 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 gestion_parc_informatique.view.ActionListener.Salle;
import gestion_parc_informatique.view.fenetre.Salle.FormulaireSupprimerSalle;
import gestion_parc_informatique.view.fenetre.ViewFenetre;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* ActionListener pour valider la suppression d'une salle
* @author dquantin
*/
public class ValiderFormulaireSupprimerSalleActionListener implements ActionListener{
private FormulaireSupprimerSalle supprimerSalle;
private ViewFenetre view;
private String idSalle;
//Constructeur
public ValiderFormulaireSupprimerSalleActionListener(FormulaireSupprimerSalle supprimerSalle){
this.supprimerSalle = supprimerSalle;
this.view = this.supprimerSalle.getView();
}
public String TraitementIDsalle (){
//recuperation choix salle
this.idSalle = supprimerSalle.gettChoixID().getText();
return idSalle;
}
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Validation Bouton");
TraitementIDsalle();
//creer un message type string
this.supprimerSalle.getView().getMessage().setAction("delete");
this.supprimerSalle.getView().getMessage().setContenu("salle");
this.supprimerSalle.getView().getMessage().setIdSalle(idSalle);
this.supprimerSalle.getView().notifyAllObservers();
}
}
| UTF-8 | Java | 1,728 | java | ValiderFormulaireSupprimerSalleActionListener.java | Java | [
{
"context": "our valider la suppression d'une salle\r\n * @author dquantin\r\n */\r\npublic class ValiderFormulaireSupprimerSall",
"end": 553,
"score": 0.9957398772239685,
"start": 545,
"tag": "USERNAME",
"value": "dquantin"
}
] | null | [] | /*
* 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 gestion_parc_informatique.view.ActionListener.Salle;
import gestion_parc_informatique.view.fenetre.Salle.FormulaireSupprimerSalle;
import gestion_parc_informatique.view.fenetre.ViewFenetre;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* ActionListener pour valider la suppression d'une salle
* @author dquantin
*/
public class ValiderFormulaireSupprimerSalleActionListener implements ActionListener{
private FormulaireSupprimerSalle supprimerSalle;
private ViewFenetre view;
private String idSalle;
//Constructeur
public ValiderFormulaireSupprimerSalleActionListener(FormulaireSupprimerSalle supprimerSalle){
this.supprimerSalle = supprimerSalle;
this.view = this.supprimerSalle.getView();
}
public String TraitementIDsalle (){
//recuperation choix salle
this.idSalle = supprimerSalle.gettChoixID().getText();
return idSalle;
}
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Validation Bouton");
TraitementIDsalle();
//creer un message type string
this.supprimerSalle.getView().getMessage().setAction("delete");
this.supprimerSalle.getView().getMessage().setContenu("salle");
this.supprimerSalle.getView().getMessage().setIdSalle(idSalle);
this.supprimerSalle.getView().notifyAllObservers();
}
}
| 1,728 | 0.686343 | 0.686343 | 52 | 31.23077 | 27.367594 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403846 | false | false | 9 |
520552405e45de9c15517f07629ff19e0ab308e4 | 19,774,029,457,313 | 4815ad168af3c64c9a2ac3c7453e3f343dfbc4cc | /jvmcli/src/main/java/com/willowtreeapps/namegame/jvmcli/ImageConverter.java | ab320a41000bdb10ade1c048c51ea320a2192d64 | [] | no_license | patjackson52/NameGameKotlinMpp | https://github.com/patjackson52/NameGameKotlinMpp | aa619718a6ee4ef2c3651cd4acd5d53e3edf6564 | f2234c36be457e7a75ebe54a7aebbcb05304097d | refs/heads/master | 2020-04-29T05:32:31.280000 | 2019-08-22T12:30:21 | 2019-08-22T12:30:21 | 175,886,704 | 3 | 0 | null | false | 2019-08-22T12:30:22 | 2019-03-15T20:27:58 | 2019-07-24T18:10:27 | 2019-08-22T12:30:22 | 3,338 | 1 | 0 | 0 | Kotlin | false | false | /*
Created by Eric Mikulin, 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Image to ASCII Art Converter
Designed for a SWCHS CompSci Club fortnight challenge
Challenge Components: Speed, Input variety and Output Aesthetics
*/
package com.willowtreeapps.namegame.jvmcli;
//Import the Packages
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
public class ImageConverter implements Runnable {
//Create a map to map between darknesses (int) and characters (ASCII based on darkness). See mapit(); for detail
static Map<Integer, Character> asciiMap = new HashMap<Integer, Character>();
//Create the image and link
static BufferedImage image;
static URL link;
public static void displayImage(String url) throws IOException {
//Create the thread for loading the image
ImageConverter load = new ImageConverter(); //create another instance of this class
Thread loadThread = new Thread(load); //Turn that into a thread
//Map characters to integers
mapit();
link = new URL(url);
loadThread.start(); //Start the thread
//Ask for the "Line Skip Coefficient"
//Basically, this is the amount the x and y values of the coordinate increase each time. Larger = smaller image.
//Anything above 2 usually doesn't work too well
int skipC = 2;
//Test if the thread is still running, then wait for it to finish if it is
if (loadThread.isAlive()) {
try {
loadThread.join(); //Wait for thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Get the length and width of the image, storx`e as integer values
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
//This is the conversion loop, goes through every x for each y line
for (int y = 0; y < imgHeight; y += 2 * skipC) {
for (int x = 0; x < imgWidth; x += skipC) {
System.out.print(convert(image.getRGB(x, y)));
}
System.out.println();
}
}
//Converts the RGB int value to a char, based on the amount of color in the pixel
private static char convert(int value) {
//Grab the three values for each red, green and blue (and alpha)
int alpha = (value >> 24) & 0xFF;
int red = (value >> 16) & 0xFF;
int green = (value >> 8) & 0xFF;
int blue = (value) & 0xFF;
//Covert to a unified integer value between 0 and 26.
//This is done by averaging, then dividing by 10 (RGB values range from 0 to 255)
int darkness = ((int) ((0.21 * red) + (0.72 * green) + (0.07 * blue) / 3) / 10);
//If alpha is completely clear, assume white
if (alpha == 0)
darkness = 26;
//Output the respective char, grabbing it from the hashmap
char chart = asciiMap.get(darkness);
return chart;
}
//This function creates the actual link from the integers and chars
private static void mapit() {
//Map an integer darkness value to an ASCII character
//The value of darkness for the chars I determined from some other random Internet source
asciiMap.put(0, '@');
asciiMap.put(1, '@');
asciiMap.put(2, '@');
asciiMap.put(3, '@');
asciiMap.put(4, '@');
asciiMap.put(5, '@');
asciiMap.put(6, 'N');
asciiMap.put(7, '%');
asciiMap.put(8, 'W');
asciiMap.put(9, '$');
asciiMap.put(10, 'D');
asciiMap.put(11, 'd');
asciiMap.put(12, 'x');
asciiMap.put(13, '6');
asciiMap.put(14, 'E');
asciiMap.put(15, '5');
asciiMap.put(16, '{');
asciiMap.put(17, 's');
asciiMap.put(18, '?');
asciiMap.put(19, '!');
asciiMap.put(20, ';');
asciiMap.put(21, '"');
asciiMap.put(22, ':');
asciiMap.put(23, '_');
asciiMap.put(24, '\'');
asciiMap.put(25, '`');
asciiMap.put(26, ' ');
}
//The function run for when you need multi-thread
public void run() {
try {
image = ImageIO.read(link); //Load the image from the web
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 5,073 | java | ImageConverter.java | Java | [
{
"context": "/*\n \tCreated by Eric Mikulin, 2015\n\n\tThis program is free software: you can re",
"end": 28,
"score": 0.999864935874939,
"start": 16,
"tag": "NAME",
"value": "Eric Mikulin"
}
] | null | [] | /*
Created by <NAME>, 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Image to ASCII Art Converter
Designed for a SWCHS CompSci Club fortnight challenge
Challenge Components: Speed, Input variety and Output Aesthetics
*/
package com.willowtreeapps.namegame.jvmcli;
//Import the Packages
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
public class ImageConverter implements Runnable {
//Create a map to map between darknesses (int) and characters (ASCII based on darkness). See mapit(); for detail
static Map<Integer, Character> asciiMap = new HashMap<Integer, Character>();
//Create the image and link
static BufferedImage image;
static URL link;
public static void displayImage(String url) throws IOException {
//Create the thread for loading the image
ImageConverter load = new ImageConverter(); //create another instance of this class
Thread loadThread = new Thread(load); //Turn that into a thread
//Map characters to integers
mapit();
link = new URL(url);
loadThread.start(); //Start the thread
//Ask for the "Line Skip Coefficient"
//Basically, this is the amount the x and y values of the coordinate increase each time. Larger = smaller image.
//Anything above 2 usually doesn't work too well
int skipC = 2;
//Test if the thread is still running, then wait for it to finish if it is
if (loadThread.isAlive()) {
try {
loadThread.join(); //Wait for thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Get the length and width of the image, storx`e as integer values
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
//This is the conversion loop, goes through every x for each y line
for (int y = 0; y < imgHeight; y += 2 * skipC) {
for (int x = 0; x < imgWidth; x += skipC) {
System.out.print(convert(image.getRGB(x, y)));
}
System.out.println();
}
}
//Converts the RGB int value to a char, based on the amount of color in the pixel
private static char convert(int value) {
//Grab the three values for each red, green and blue (and alpha)
int alpha = (value >> 24) & 0xFF;
int red = (value >> 16) & 0xFF;
int green = (value >> 8) & 0xFF;
int blue = (value) & 0xFF;
//Covert to a unified integer value between 0 and 26.
//This is done by averaging, then dividing by 10 (RGB values range from 0 to 255)
int darkness = ((int) ((0.21 * red) + (0.72 * green) + (0.07 * blue) / 3) / 10);
//If alpha is completely clear, assume white
if (alpha == 0)
darkness = 26;
//Output the respective char, grabbing it from the hashmap
char chart = asciiMap.get(darkness);
return chart;
}
//This function creates the actual link from the integers and chars
private static void mapit() {
//Map an integer darkness value to an ASCII character
//The value of darkness for the chars I determined from some other random Internet source
asciiMap.put(0, '@');
asciiMap.put(1, '@');
asciiMap.put(2, '@');
asciiMap.put(3, '@');
asciiMap.put(4, '@');
asciiMap.put(5, '@');
asciiMap.put(6, 'N');
asciiMap.put(7, '%');
asciiMap.put(8, 'W');
asciiMap.put(9, '$');
asciiMap.put(10, 'D');
asciiMap.put(11, 'd');
asciiMap.put(12, 'x');
asciiMap.put(13, '6');
asciiMap.put(14, 'E');
asciiMap.put(15, '5');
asciiMap.put(16, '{');
asciiMap.put(17, 's');
asciiMap.put(18, '?');
asciiMap.put(19, '!');
asciiMap.put(20, ';');
asciiMap.put(21, '"');
asciiMap.put(22, ':');
asciiMap.put(23, '_');
asciiMap.put(24, '\'');
asciiMap.put(25, '`');
asciiMap.put(26, ' ');
}
//The function run for when you need multi-thread
public void run() {
try {
image = ImageIO.read(link); //Load the image from the web
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 5,067 | 0.603982 | 0.586438 | 149 | 33.046978 | 27.192413 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.778524 | false | false | 9 |
983eb4e92e8c18d7d92bef44b5daa4bfecc8ea9b | 23,450,521,476,251 | 17d18ae97dbb535795a46b40ff1a9d4e39339929 | /archive/interviewstreet/CommentTask.java | aa6a67eaa53efb9b1b88c5ce553b109cc08624ec | [] | no_license | kingder/DailyContest | https://github.com/kingder/DailyContest | 54f10886dbcb86673a2d1faa4214042b9e632245 | ba909255ff871ccd149de59555a51349171fb87e | refs/heads/master | 2016-08-05T19:31:46.922000 | 2013-05-13T02:47:45 | 2013-05-13T02:47:45 | 4,014,761 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2012. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package my.mypackage;
import net.kingder.utils.io.MyInputReader;
import net.kingder.utils.io.MyOutputWriter;
import java.util.Arrays;
public class CommentTask {
static final int Mod = 1000000007;
static final int[] table = {1,
2,
7,
38,
291,
2932,
36961,
561948,
10026505,
205608536,
767440651,
373202347,
630085432,
282234652,
673322462,
131935485,
402081845,
678170376,
436468013,
464104160,
835315027,
281872976,
496721330,
148734173,
562024850,
222330769,
629123368,
219900207,
311664840,
114974372,
356056332,
835506954,
47512108,
256278981,
616519893,
32313045,
117134122,
852198063,
659742994,
547964402};
public void solve(int testNumber, MyInputReader in, MyOutputWriter out) {
int n = in.nextInt();
int[] D = new int[n];
int degreeSum = 0;
int notDetermined = 0;
int[] degreeCnt = new int[n + 1], degreeCount = new int[n + 1];
for (int i = 0; i < n; i++) {
D[i] = in.nextInt();
notDetermined += D[i] == -1 ? 1 : 0;
if (D[i] != -1) {
degreeSum += D[i];
degreeCnt[D[i] + 1] += D[i];
degreeCount[D[i] + 1] += 1;
}
}
if (notDetermined == n) {
out.printLine(table[n - 1]);
return;
}
long ret = 1;
if (notDetermined == 0) {
Arrays.sort(D);
int presum = 0;
for (int i = 0; i < n; i++) {
presum += D[i];
if (presum < choose(i + 1, 2)) {
ret = 0;
break;
}
if (i == n - 1 && presum != choose(n, 2))
ret = 0;
}
out.printLine(ret);
return;
}
for (int i = 1; i <= n; i++) {
degreeCnt[i] += degreeCnt[i - 1];
degreeCount[i] += degreeCount[i - 1];
}
for (int[] o : C) Arrays.fill(o, -1);
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
C[i][j] = choose(i, j);
degreeSum = choose(n, 2) - degreeSum;
if (degreeSum < 0) {
out.printLine(0);
return;
}
int M = Math.min(n, degreeSum + 1);
long[][][] dp = new long[notDetermined + 1][M + 1][degreeSum + 1];
//boolean [][][] isok = new boolean[ notDetermined + 1][ M + 1 ][ degreeSum + 1];
// for( int i = 0 ; i < dp.length ; i ++ )
// for( int j = 0 ; j < dp[i].length ; j ++ ){
// Arrays.fill( dp[i][j] , 0 );
//
// }
//for( int it : degreeCnt ) System.out.print( it + " "); System.out.print("\n");
//for( int it : degreeCount ) System.out.print( it + " "); System.out.print("\n");
dp[0][0][0] = 1;
//out.printLine( degreeCount[1] , degreeCount[0]);
//out.printLine( notDetermined , M , degreeSum );
for (int i = 0; i < notDetermined; i++)
for (int j = 0; j <= M; j++)
for (int k = 0; k <= degreeSum; k++)
if (dp[i][j][k] > 0) {
//if (k + (notDetermined - i) * M < degreeSum) continue;
int presum = degreeCnt[j];
int precnt = degreeCount[j];
for (int it = j + 1; it <= M; it++) {
int x = degreeCount[it] - degreeCount[it - 1];
if (k + presum - C[precnt + i][2] < x * (1 - it + precnt + i) + C[x][2])
break;
presum = degreeCnt[it];
precnt = degreeCount[it];
//if( !ok ) break;
//out.printLine( i , j , k , x, precnt , presum , it);
for (int nt = 1; i + nt <= notDetermined && k + nt * (it - 1) <= degreeSum; nt++) {
if (presum + nt * (it - 1) + k >= C[nt + precnt + i][2]) {
dp[i + nt][it][k + nt * (it - 1)] = (dp[i + nt][it][k + nt * (it - 1)] + C[notDetermined - i][nt]
* dp[i][j][k]) % Mod;
//if( i+nt == 2 && it == 6 && k+nt*(it-1) == 8 )
// out.printLine( "(",i , j , k ,')',"->", "(", i+nt , it , k+nt*(it-1),")");
} else break;
}
}
}
ret = 0;
for (int i = 1; i <= M; i++) {
int presum = degreeCnt[i];
int precnt = degreeCount[i];
boolean ok = true;
for (int it = i + 1; it <= M && ok; it++) {
int x = degreeCount[it] - degreeCount[it - 1];
if (degreeSum + presum - choose(notDetermined + precnt, 2) < x * (1 - it + notDetermined + precnt) + choose(x, 2)) {
ok = false;
break;
}
presum = degreeCnt[it];
precnt = degreeCount[it];
}
if (!ok) continue;
ret = (ret + dp[notDetermined][i][degreeSum]) % Mod;
}
out.printLine(ret);
// if( notDetermined < 7 ){
// Arrays.sort( D );
// for( int i = 0 ; i < D.length / 2 ; i ++ ){
// int t = D[ i ] ;
// D[i] = D[ D.length - i - 1] ;
// D[ D.length-i-1 ]= t;
//
// }
// out.printLine( "brute force:" , brute_force( D ));
// }
//out.printLine(getMethods(4, 4, 6));
}
static final int MAXN = 40 + 10;
int[][] C = new int[MAXN][MAXN];
private int choose(int n, int k) {
if (n < 0 || k < 0 || n < k) return 0;
if (n == k || k == 0) return 1;
if (C[n][k] != -1) return C[n][k];
return C[n][k] = (choose(n - 1, k - 1) + choose(n - 1, k)) % Mod;
}
int ans;
public int brute_force(int[] D) {
ans = 0;
int sum = 0;
for (int o : D) sum += o == -1 ? 0 : o;
//for( int it : D ) System.out.print( it + " "); System.out.print("\n");
bsolve(D, sum);
return ans;
}
private void bsolve(int[] d, int sm) {
boolean more = false;
//for( int it : d ) System.out.print( it + " "); System.out.print("\n"); System.out.println(sm);
for (int i = 0; i < d.length; i++) {
if (d[i] == -1) {
more = true;
for (int j = 0; j < d.length; j++)
if (sm + j <= choose(d.length, 2)) {
d[i] = j;
bsolve(d, sm + j);
}
d[i] = -1;
break;
}
}
if (!more && sm == choose(d.length, 2)) {
int[] s = Arrays.copyOf(d, d.length);
Arrays.sort(s);
//for( int it : d ) System.out.print( it + " "); System.out.print("\n");
//for( int it : s ) System.out.print( it + " "); System.out.print("\n");
int p = 0;
for (int i = 0; i < s.length; i++) {
p += s[i];
if (p < choose(i + 1, 2)) return;
}
//for( int it : d ) System.out.print( it + " "); System.out.print("\n");
ans++;
}
}
private int getMethods(int limit, int n, int k) {
int[] A = new int[k + 1];
int[] C = new int[k + 1];
for (int i = 0; i <= Math.min(n - 1, k); i++) A[i] = 1;
for (int it = 0; it < limit - 1; it++) {
for (int j = 0; j <= Math.min(n - 1, k); j++) {
for (int i = 0; i + j <= k; i++)
C[i + j] = (C[i + j] + A[i]) % Mod;
}
int[] tmp = C;
C = A;
A = tmp;
Arrays.fill(C, 0);
// for( int i = 0 ; i <= k ; i++ ) System.out.printf("%d ",C[i]);System.out.println();
// for( int i = 0 ; i <= k ; i++ ) System.out.printf("%d ",A[i]);System.out.println();
}
// for (int i = 0; i <= k; i++) System.out.printf("%d ", A[i]);
// System.out.println();
// System.out.println(n + " " + k + " " + A[k]);
return A[k];
}
}
| UTF-8 | Java | 9,181 | java | CommentTask.java | Java | [] | null | [] | /*
* Copyright (c) 2012. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package my.mypackage;
import net.kingder.utils.io.MyInputReader;
import net.kingder.utils.io.MyOutputWriter;
import java.util.Arrays;
public class CommentTask {
static final int Mod = 1000000007;
static final int[] table = {1,
2,
7,
38,
291,
2932,
36961,
561948,
10026505,
205608536,
767440651,
373202347,
630085432,
282234652,
673322462,
131935485,
402081845,
678170376,
436468013,
464104160,
835315027,
281872976,
496721330,
148734173,
562024850,
222330769,
629123368,
219900207,
311664840,
114974372,
356056332,
835506954,
47512108,
256278981,
616519893,
32313045,
117134122,
852198063,
659742994,
547964402};
public void solve(int testNumber, MyInputReader in, MyOutputWriter out) {
int n = in.nextInt();
int[] D = new int[n];
int degreeSum = 0;
int notDetermined = 0;
int[] degreeCnt = new int[n + 1], degreeCount = new int[n + 1];
for (int i = 0; i < n; i++) {
D[i] = in.nextInt();
notDetermined += D[i] == -1 ? 1 : 0;
if (D[i] != -1) {
degreeSum += D[i];
degreeCnt[D[i] + 1] += D[i];
degreeCount[D[i] + 1] += 1;
}
}
if (notDetermined == n) {
out.printLine(table[n - 1]);
return;
}
long ret = 1;
if (notDetermined == 0) {
Arrays.sort(D);
int presum = 0;
for (int i = 0; i < n; i++) {
presum += D[i];
if (presum < choose(i + 1, 2)) {
ret = 0;
break;
}
if (i == n - 1 && presum != choose(n, 2))
ret = 0;
}
out.printLine(ret);
return;
}
for (int i = 1; i <= n; i++) {
degreeCnt[i] += degreeCnt[i - 1];
degreeCount[i] += degreeCount[i - 1];
}
for (int[] o : C) Arrays.fill(o, -1);
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
C[i][j] = choose(i, j);
degreeSum = choose(n, 2) - degreeSum;
if (degreeSum < 0) {
out.printLine(0);
return;
}
int M = Math.min(n, degreeSum + 1);
long[][][] dp = new long[notDetermined + 1][M + 1][degreeSum + 1];
//boolean [][][] isok = new boolean[ notDetermined + 1][ M + 1 ][ degreeSum + 1];
// for( int i = 0 ; i < dp.length ; i ++ )
// for( int j = 0 ; j < dp[i].length ; j ++ ){
// Arrays.fill( dp[i][j] , 0 );
//
// }
//for( int it : degreeCnt ) System.out.print( it + " "); System.out.print("\n");
//for( int it : degreeCount ) System.out.print( it + " "); System.out.print("\n");
dp[0][0][0] = 1;
//out.printLine( degreeCount[1] , degreeCount[0]);
//out.printLine( notDetermined , M , degreeSum );
for (int i = 0; i < notDetermined; i++)
for (int j = 0; j <= M; j++)
for (int k = 0; k <= degreeSum; k++)
if (dp[i][j][k] > 0) {
//if (k + (notDetermined - i) * M < degreeSum) continue;
int presum = degreeCnt[j];
int precnt = degreeCount[j];
for (int it = j + 1; it <= M; it++) {
int x = degreeCount[it] - degreeCount[it - 1];
if (k + presum - C[precnt + i][2] < x * (1 - it + precnt + i) + C[x][2])
break;
presum = degreeCnt[it];
precnt = degreeCount[it];
//if( !ok ) break;
//out.printLine( i , j , k , x, precnt , presum , it);
for (int nt = 1; i + nt <= notDetermined && k + nt * (it - 1) <= degreeSum; nt++) {
if (presum + nt * (it - 1) + k >= C[nt + precnt + i][2]) {
dp[i + nt][it][k + nt * (it - 1)] = (dp[i + nt][it][k + nt * (it - 1)] + C[notDetermined - i][nt]
* dp[i][j][k]) % Mod;
//if( i+nt == 2 && it == 6 && k+nt*(it-1) == 8 )
// out.printLine( "(",i , j , k ,')',"->", "(", i+nt , it , k+nt*(it-1),")");
} else break;
}
}
}
ret = 0;
for (int i = 1; i <= M; i++) {
int presum = degreeCnt[i];
int precnt = degreeCount[i];
boolean ok = true;
for (int it = i + 1; it <= M && ok; it++) {
int x = degreeCount[it] - degreeCount[it - 1];
if (degreeSum + presum - choose(notDetermined + precnt, 2) < x * (1 - it + notDetermined + precnt) + choose(x, 2)) {
ok = false;
break;
}
presum = degreeCnt[it];
precnt = degreeCount[it];
}
if (!ok) continue;
ret = (ret + dp[notDetermined][i][degreeSum]) % Mod;
}
out.printLine(ret);
// if( notDetermined < 7 ){
// Arrays.sort( D );
// for( int i = 0 ; i < D.length / 2 ; i ++ ){
// int t = D[ i ] ;
// D[i] = D[ D.length - i - 1] ;
// D[ D.length-i-1 ]= t;
//
// }
// out.printLine( "brute force:" , brute_force( D ));
// }
//out.printLine(getMethods(4, 4, 6));
}
static final int MAXN = 40 + 10;
int[][] C = new int[MAXN][MAXN];
private int choose(int n, int k) {
if (n < 0 || k < 0 || n < k) return 0;
if (n == k || k == 0) return 1;
if (C[n][k] != -1) return C[n][k];
return C[n][k] = (choose(n - 1, k - 1) + choose(n - 1, k)) % Mod;
}
int ans;
public int brute_force(int[] D) {
ans = 0;
int sum = 0;
for (int o : D) sum += o == -1 ? 0 : o;
//for( int it : D ) System.out.print( it + " "); System.out.print("\n");
bsolve(D, sum);
return ans;
}
private void bsolve(int[] d, int sm) {
boolean more = false;
//for( int it : d ) System.out.print( it + " "); System.out.print("\n"); System.out.println(sm);
for (int i = 0; i < d.length; i++) {
if (d[i] == -1) {
more = true;
for (int j = 0; j < d.length; j++)
if (sm + j <= choose(d.length, 2)) {
d[i] = j;
bsolve(d, sm + j);
}
d[i] = -1;
break;
}
}
if (!more && sm == choose(d.length, 2)) {
int[] s = Arrays.copyOf(d, d.length);
Arrays.sort(s);
//for( int it : d ) System.out.print( it + " "); System.out.print("\n");
//for( int it : s ) System.out.print( it + " "); System.out.print("\n");
int p = 0;
for (int i = 0; i < s.length; i++) {
p += s[i];
if (p < choose(i + 1, 2)) return;
}
//for( int it : d ) System.out.print( it + " "); System.out.print("\n");
ans++;
}
}
private int getMethods(int limit, int n, int k) {
int[] A = new int[k + 1];
int[] C = new int[k + 1];
for (int i = 0; i <= Math.min(n - 1, k); i++) A[i] = 1;
for (int it = 0; it < limit - 1; it++) {
for (int j = 0; j <= Math.min(n - 1, k); j++) {
for (int i = 0; i + j <= k; i++)
C[i + j] = (C[i + j] + A[i]) % Mod;
}
int[] tmp = C;
C = A;
A = tmp;
Arrays.fill(C, 0);
// for( int i = 0 ; i <= k ; i++ ) System.out.printf("%d ",C[i]);System.out.println();
// for( int i = 0 ; i <= k ; i++ ) System.out.printf("%d ",A[i]);System.out.println();
}
// for (int i = 0; i <= k; i++) System.out.printf("%d ", A[i]);
// System.out.println();
// System.out.println(n + " " + k + " " + A[k]);
return A[k];
}
}
| 9,181 | 0.391896 | 0.343318 | 267 | 33.385769 | 26.08322 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.026217 | false | false | 9 |
d856bc12449a1d6a438640a432b8d728849c6612 | 21,509,196,232,779 | 2a6d09b404a1a505e359e8236a150028fc016cd8 | /cidadao_auditor_parent/cidadao_auditor/src/main/java/br/net/proex/controller/factory/filter/AppCorsFilter.java | 539ebccf4fa5f41045acf358d2644d24f18ce6fa | [] | no_license | rafael-souza/cidadao_auditor_adm | https://github.com/rafael-souza/cidadao_auditor_adm | 4497322e7ab96d652461d96d40c445bace7a8267 | bd5c735c895e6c7219d08a0420a661b397d93709 | refs/heads/master | 2021-09-07T00:57:24.842000 | 2018-02-14T13:13:55 | 2018-02-14T13:13:55 | 111,393,231 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.net.proex.controller.factory.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AppCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println("Request " + request.getMethod());
HttpServletResponse resp = (HttpServletResponse) servletResponse;
// resp.addHeader("Access-Control-Allow-Origin","http://localhost:8080'");
// resp.addHeader("Access-Control-Allow-Methods","GET,POST");
// resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");
resp.setHeader("Access-Control-Allow-Credentials", "true");
// Just ACCEPT and REPLY OK if OPTIONS
if ( request.getMethod().equals("OPTIONS") ) {
resp.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(request, servletResponse);
}
@Override
public void destroy() {
}
}
| UTF-8 | Java | 1,547 | java | AppCorsFilter.java | Java | [] | null | [] | package br.net.proex.controller.factory.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AppCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println("Request " + request.getMethod());
HttpServletResponse resp = (HttpServletResponse) servletResponse;
// resp.addHeader("Access-Control-Allow-Origin","http://localhost:8080'");
// resp.addHeader("Access-Control-Allow-Methods","GET,POST");
// resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");
resp.setHeader("Access-Control-Allow-Credentials", "true");
// Just ACCEPT and REPLY OK if OPTIONS
if ( request.getMethod().equals("OPTIONS") ) {
resp.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(request, servletResponse);
}
@Override
public void destroy() {
}
}
| 1,547 | 0.719457 | 0.714286 | 41 | 36.731709 | 35.678116 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.658537 | false | false | 9 |
9054e27d79964b9eb351a418bb5fe5a038cfa58d | 12,936,441,514,518 | 168f53cfdd6c9194c115d64eb6ad219089e95c88 | /core/src/main/java/cl/core/ds/Pair.java | c5838af49292ffa7d87ecc7e8b127e4683eef2ab | [
"MIT"
] | permissive | vmazheru/codeless | https://github.com/vmazheru/codeless | f90a94d2b908b077209ce32a75945b794b7e155e | 1eb0f998b4b8065760acc490992c1f88d8b808c2 | refs/heads/master | 2021-05-01T14:03:42.567000 | 2018-01-22T19:38:19 | 2018-01-22T19:38:19 | 55,106,765 | 1 | 0 | null | false | 2018-01-20T17:23:53 | 2016-03-31T00:15:29 | 2016-11-22T17:47:11 | 2018-01-20T17:23:53 | 291 | 0 | 0 | 0 | Java | false | null | package cl.core.ds;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Represents a tuple of two elements.
*
* @param <T> type of the first element
* @param <U> type of the second element
*/
public final class Pair<T,U> {
private final T first;
private final U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
/**
* Return the first element of the pair.
*/
public T _1() {
return first;
}
/**
* Return the second element of the pair.
*/
public U _2() {
return second;
}
/**
* Convert this pair to an array of {@code Object}s of size two.
*/
public Object[] asArray() {
return new Object[] {first, second};
}
/**
* Convert a pair to a list, assuming that both elements are of the same type.
*/
public static <T> List<T> asList(Pair<T,T> pair) {
return Arrays.<T>asList(pair._1(), pair._2());
}
@Override
public String toString() {
return new StringBuilder("[").append(Objects.toString(first)).append(",")
.append(Objects.toString(second)).append("]").toString();
}
}
| UTF-8 | Java | 1,254 | java | Pair.java | Java | [] | null | [] | package cl.core.ds;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Represents a tuple of two elements.
*
* @param <T> type of the first element
* @param <U> type of the second element
*/
public final class Pair<T,U> {
private final T first;
private final U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
/**
* Return the first element of the pair.
*/
public T _1() {
return first;
}
/**
* Return the second element of the pair.
*/
public U _2() {
return second;
}
/**
* Convert this pair to an array of {@code Object}s of size two.
*/
public Object[] asArray() {
return new Object[] {first, second};
}
/**
* Convert a pair to a list, assuming that both elements are of the same type.
*/
public static <T> List<T> asList(Pair<T,T> pair) {
return Arrays.<T>asList(pair._1(), pair._2());
}
@Override
public String toString() {
return new StringBuilder("[").append(Objects.toString(first)).append(",")
.append(Objects.toString(second)).append("]").toString();
}
}
| 1,254 | 0.562998 | 0.559809 | 57 | 21 | 21.330318 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.350877 | false | false | 9 |
ce7927ea442826af9a5c004e758e77439357d510 | 17,093,969,904,284 | 473fc28d466ddbe9758ca49c7d4fb42e7d82586e | /app/src/main/java/com/syd/source/aosp/cts/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleRepo.java | eb67cc852ad6f3b373be690a63cd851019d62672 | [] | no_license | lz-purple/Source | https://github.com/lz-purple/Source | a7788070623f2965a8caa3264778f48d17372bab | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | refs/heads/master | 2020-12-23T17:03:12.412000 | 2020-01-31T01:54:37 | 2020-01-31T01:54:37 | 237,205,127 | 4 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.compatibility.common.tradefed.testtype;
import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
import com.android.compatibility.common.tradefed.result.TestRunHandler;
import com.android.compatibility.common.tradefed.util.LinearPartition;
import com.android.compatibility.common.tradefed.util.UniqueModuleCountUtil;
import com.android.compatibility.common.util.TestFilter;
import com.android.ddmlib.Log.LogLevel;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.config.ConfigurationException;
import com.android.tradefed.config.ConfigurationFactory;
import com.android.tradefed.config.IConfiguration;
import com.android.tradefed.config.IConfigurationFactory;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.testtype.IStrictShardableTest;
import com.android.tradefed.testtype.ITestFileFilterReceiver;
import com.android.tradefed.testtype.ITestFilterReceiver;
import com.android.tradefed.util.AbiUtils;
import com.android.tradefed.util.FileUtil;
import com.android.tradefed.util.MultiMap;
import com.android.tradefed.util.TimeUtil;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Retrieves Compatibility test module definitions from the repository.
*/
public class ModuleRepo implements IModuleRepo {
private static final String CONFIG_EXT = ".config";
private static final Map<String, Integer> ENDING_MODULES = new HashMap<>();
static {
// b/62732298 put testFullDisk in the end to accommodate CTSMediaStressTest temporally
ENDING_MODULES.put("CtsAppSecurityHostTestCases", 1);
ENDING_MODULES.put("CtsMonkeyTestCases", 2);
}
// Synchronization objects for Token Modules.
private int mInitCount = 0;
private Set<IModuleDef> mTokenModuleScheduled;
private static Object lock = new Object();
private int mTotalShards;
private Integer mShardIndex;
private Map<String, Set<String>> mDeviceTokens = new HashMap<>();
private Map<String, Map<String, List<String>>> mTestArgs = new HashMap<>();
private Map<String, Map<String, List<String>>> mModuleArgs = new HashMap<>();
private boolean mIncludeAll;
private Map<String, List<TestFilter>> mIncludeFilters = new HashMap<>();
private Map<String, List<TestFilter>> mExcludeFilters = new HashMap<>();
private IConfigurationFactory mConfigFactory = ConfigurationFactory.getInstance();
private volatile boolean mInitialized = false;
// Holds all the tests with tokens waiting to be run. Meaning the DUT must have a specific token.
private List<IModuleDef> mTokenModules = new ArrayList<>();
private List<IModuleDef> mNonTokenModules = new ArrayList<>();
/**
* {@inheritDoc}
*/
@Override
public int getNumberOfShards() {
return mTotalShards;
}
/**
* Returns the device tokens of this module repo. Exposed for testing.
*/
protected Map<String, Set<String>> getDeviceTokens() {
return mDeviceTokens;
}
/**
* A {@link FilenameFilter} to find all modules in a directory who match the given pattern.
*/
public static class NameFilter implements FilenameFilter {
private String mPattern;
public NameFilter(String pattern) {
mPattern = pattern;
}
/**
* {@inheritDoc}
*/
@Override
public boolean accept(File dir, String name) {
return name.contains(mPattern) && name.endsWith(CONFIG_EXT);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<IModuleDef> getNonTokenModules() {
return mNonTokenModules;
}
/**
* {@inheritDoc}
*/
@Override
public List<IModuleDef> getTokenModules() {
return mTokenModules;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getModuleIds() {
Set<String> moduleIdSet = new HashSet<>();
for (IModuleDef moduleDef : mNonTokenModules) {
moduleIdSet.add(moduleDef.getId());
}
for (IModuleDef moduleDef : mTokenModules) {
moduleIdSet.add(moduleDef.getId());
}
return moduleIdSet.toArray(new String[moduleIdSet.size()]);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isInitialized() {
return mInitialized;
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(int totalShards, Integer shardIndex, File testsDir, Set<IAbi> abis,
List<String> deviceTokens, List<String> testArgs, List<String> moduleArgs,
Set<String> includeFilters, Set<String> excludeFilters,
MultiMap<String, String> metadataIncludeFilters,
MultiMap<String, String> metadataExcludeFilters,
IBuildInfo buildInfo) {
CLog.d("Initializing ModuleRepo\nShards:%d\nTests Dir:%s\nABIs:%s\nDevice Tokens:%s\n" +
"Test Args:%s\nModule Args:%s\nIncludes:%s\nExcludes:%s",
totalShards, testsDir.getAbsolutePath(), abis, deviceTokens, testArgs, moduleArgs,
includeFilters, excludeFilters);
mInitialized = true;
mTotalShards = totalShards;
mShardIndex = shardIndex;
synchronized (lock) {
if (mTokenModuleScheduled == null) {
mTokenModuleScheduled = new HashSet<>();
}
}
for (String line : deviceTokens) {
String[] parts = line.split(":");
if (parts.length == 2) {
String key = parts[0];
String value = parts[1];
Set<String> list = mDeviceTokens.get(key);
if (list == null) {
list = new HashSet<>();
mDeviceTokens.put(key, list);
}
list.add(value);
} else {
throw new IllegalArgumentException(
String.format("Could not parse device token: %s", line));
}
}
putArgs(testArgs, mTestArgs);
putArgs(moduleArgs, mModuleArgs);
mIncludeAll = includeFilters.isEmpty();
// Include all the inclusions
addFilters(includeFilters, mIncludeFilters, abis);
// Exclude all the exclusions
addFilters(excludeFilters, mExcludeFilters, abis);
File[] configFiles = testsDir.listFiles(new ConfigFilter());
if (configFiles.length == 0) {
throw new IllegalArgumentException(
String.format("No config files found in %s", testsDir.getAbsolutePath()));
}
Map<String, Integer> shardedTestCounts = new HashMap<>();
for (File configFile : configFiles) {
final String name = configFile.getName().replace(CONFIG_EXT, "");
final String[] pathArg = new String[] { configFile.getAbsolutePath() };
try {
// Invokes parser to process the test module config file
// Need to generate a different config for each ABI as we cannot guarantee the
// configs are idempotent. This however means we parse the same file multiple times
for (IAbi abi : abis) {
String id = AbiUtils.createId(abi.getName(), name);
if (!shouldRunModule(id)) {
// If the module should not run tests based on the state of filters,
// skip this name/abi combination.
continue;
}
IConfiguration config = mConfigFactory.createConfigurationFromArgs(pathArg);
if (!filterByConfigMetadata(config,
metadataIncludeFilters, metadataExcludeFilters)) {
// if the module config did not pass the metadata filters, it's excluded
// from execution
continue;
}
Map<String, List<String>> args = new HashMap<>();
if (mModuleArgs.containsKey(name)) {
args.putAll(mModuleArgs.get(name));
}
if (mModuleArgs.containsKey(id)) {
args.putAll(mModuleArgs.get(id));
}
injectOptionsToConfig(args, config);
List<IRemoteTest> tests = config.getTests();
for (IRemoteTest test : tests) {
prepareTestClass(name, abi, config, test);
}
List<IRemoteTest> shardedTests = tests;
if (mTotalShards > 1) {
shardedTests = splitShardableTests(tests, buildInfo);
}
if (shardedTests.size() > 1) {
shardedTestCounts.put(id, shardedTests.size());
}
for (IRemoteTest test : shardedTests) {
addModuleDef(name, abi, test, pathArg);
}
}
} catch (ConfigurationException e) {
throw new RuntimeException(String.format("error parsing config file: %s",
configFile.getName()), e);
}
}
mExcludeFilters.clear();
TestRunHandler.setTestRuns(new CompatibilityBuildHelper(buildInfo), shardedTestCounts);
}
/**
* Prepare to run test classes.
*
* @param name module name
* @param abi IAbi object that contains abi information
* @param config IConfiguration object created from config file
* @param test test class
* @throws ConfigurationException
*/
protected void prepareTestClass(final String name, IAbi abi, IConfiguration config,
IRemoteTest test) throws ConfigurationException {
String className = test.getClass().getName();
Map<String, List<String>> testArgsMap = new HashMap<>();
if (mTestArgs.containsKey(className)) {
testArgsMap.putAll(mTestArgs.get(className));
}
injectOptionsToConfig(testArgsMap, config);
addFiltersToTest(test, abi, name);
}
/**
* Helper to inject options to a config.
*/
@VisibleForTesting
void injectOptionsToConfig(Map<String, List<String>> optionMap, IConfiguration config)
throws ConfigurationException{
for (Entry<String, List<String>> entry : optionMap.entrySet()) {
for (String entryValue : entry.getValue()) {
String entryName = entry.getKey();
if (entryValue.contains(":=")) {
// entryValue is key-value pair
String key = entryValue.substring(0, entryValue.indexOf(":="));
String value = entryValue.substring(entryValue.indexOf(":=") + 2);
config.injectOptionValue(entryName, key, value);
} else {
// entryValue is just the argument value
config.injectOptionValue(entryName, entryValue);
}
}
}
}
private List<IRemoteTest> splitShardableTests(List<IRemoteTest> tests, IBuildInfo buildInfo) {
ArrayList<IRemoteTest> shardedList = new ArrayList<>(tests.size());
for (IRemoteTest test : tests) {
if (test instanceof IBuildReceiver) {
((IBuildReceiver)test).setBuild(buildInfo);
}
if (mShardIndex != null && test instanceof IStrictShardableTest) {
for (int i = 0; i < mTotalShards; i++) {
shardedList.add(((IStrictShardableTest)test).getTestShard(mTotalShards, i));
}
} else {
shardedList.add(test);
}
}
return shardedList;
}
private void addFilters(Set<String> stringFilters,
Map<String, List<TestFilter>> filters, Set<IAbi> abis) {
for (String filterString : stringFilters) {
TestFilter filter = TestFilter.createFrom(filterString);
String abi = filter.getAbi();
if (abi == null) {
for (IAbi a : abis) {
addFilter(a.getName(), filter, filters);
}
} else {
addFilter(abi, filter, filters);
}
}
}
private void addFilter(String abi, TestFilter filter,
Map<String, List<TestFilter>> filters) {
getFilter(filters, AbiUtils.createId(abi, filter.getName())).add(filter);
}
private List<TestFilter> getFilter(Map<String, List<TestFilter>> filters, String id) {
List<TestFilter> fs = filters.get(id);
if (fs == null) {
fs = new ArrayList<>();
filters.put(id, fs);
}
return fs;
}
protected void addModuleDef(String name, IAbi abi, IRemoteTest test, String[] configPaths)
throws ConfigurationException {
// Invokes parser to process the test module config file
IConfiguration config = mConfigFactory.createConfigurationFromArgs(configPaths);
addModuleDef(new ModuleDef(name, abi, test, config.getTargetPreparers(),
config.getConfigurationDescription()));
}
protected void addModuleDef(IModuleDef moduleDef) {
Set<String> tokens = moduleDef.getTokens();
if (tokens != null && !tokens.isEmpty()) {
mTokenModules.add(moduleDef);
} else {
mNonTokenModules.add(moduleDef);
}
}
private void addFiltersToTest(IRemoteTest test, IAbi abi, String name) {
String moduleId = AbiUtils.createId(abi.getName(), name);
if (!(test instanceof ITestFilterReceiver)) {
throw new IllegalArgumentException(String.format(
"Test in module %s must implement ITestFilterReceiver.", moduleId));
}
List<TestFilter> mdIncludes = getFilter(mIncludeFilters, moduleId);
List<TestFilter> mdExcludes = getFilter(mExcludeFilters, moduleId);
if (!mdIncludes.isEmpty()) {
addTestIncludes((ITestFilterReceiver) test, mdIncludes, name);
}
if (!mdExcludes.isEmpty()) {
addTestExcludes((ITestFilterReceiver) test, mdExcludes, name);
}
}
@VisibleForTesting
protected boolean filterByConfigMetadata(IConfiguration config,
MultiMap<String, String> include, MultiMap<String, String> exclude) {
MultiMap<String, String> metadata = config.getConfigurationDescription().getAllMetaData();
boolean shouldInclude = false;
for (String key : include.keySet()) {
Set<String> filters = new HashSet<>(include.get(key));
if (metadata.containsKey(key)) {
filters.retainAll(metadata.get(key));
if (!filters.isEmpty()) {
// inclusion filter is not empty and there's at least one matching inclusion
// rule so there's no need to match other inclusion rules
shouldInclude = true;
break;
}
}
}
if (!include.isEmpty() && !shouldInclude) {
// if inclusion filter is not empty and we didn't find a match, the module will not be
// included
return false;
}
// Now evaluate exclusion rules, this ordering also means that exclusion rules may override
// inclusion rules: a config already matched for inclusion may still be excluded if matching
// rules exist
for (String key : exclude.keySet()) {
Set<String> filters = new HashSet<>(exclude.get(key));
if (metadata.containsKey(key)) {
filters.retainAll(metadata.get(key));
if (!filters.isEmpty()) {
// we found at least one matching exclusion rules, so we are excluding this
// this module
return false;
}
}
}
// we've matched at least one inclusion rule (if there's any) AND we didn't match any of the
// exclusion rules (if there's any)
return true;
}
private boolean shouldRunModule(String moduleId) {
List<TestFilter> mdIncludes = getFilter(mIncludeFilters, moduleId);
List<TestFilter> mdExcludes = getFilter(mExcludeFilters, moduleId);
// if including all modules or includes exist for this module, and there are not excludes
// for the entire module, this module should be run.
return (mIncludeAll || !mdIncludes.isEmpty()) && !containsModuleExclude(mdExcludes);
}
private void addTestIncludes(ITestFilterReceiver test, List<TestFilter> includes,
String name) {
if (test instanceof ITestFileFilterReceiver) {
File includeFile = createFilterFile(name, ".include", includes);
((ITestFileFilterReceiver)test).setIncludeTestFile(includeFile);
} else {
// add test includes one at a time
for (TestFilter include : includes) {
String filterTestName = include.getTest();
if (filterTestName != null) {
test.addIncludeFilter(filterTestName);
}
}
}
}
private void addTestExcludes(ITestFilterReceiver test, List<TestFilter> excludes,
String name) {
if (test instanceof ITestFileFilterReceiver) {
File excludeFile = createFilterFile(name, ".exclude", excludes);
((ITestFileFilterReceiver)test).setExcludeTestFile(excludeFile);
} else {
// add test excludes one at a time
for (TestFilter exclude : excludes) {
test.addExcludeFilter(exclude.getTest());
}
}
}
private File createFilterFile(String prefix, String suffix, List<TestFilter> filters) {
File filterFile = null;
PrintWriter out = null;
try {
filterFile = FileUtil.createTempFile(prefix, suffix);
out = new PrintWriter(filterFile);
for (TestFilter filter : filters) {
String filterTest = filter.getTest();
if (filterTest != null) {
out.println(filterTest);
}
}
out.flush();
} catch (IOException e) {
throw new RuntimeException("Failed to create filter file");
} finally {
if (out != null) {
out.close();
}
}
filterFile.deleteOnExit();
return filterFile;
}
/*
* Returns true iff one or more test filters in excludes apply to the entire module.
*/
private boolean containsModuleExclude(Collection<TestFilter> excludes) {
for (TestFilter exclude : excludes) {
if (exclude.getTest() == null) {
return true;
}
}
return false;
}
/**
* A {@link FilenameFilter} to find all the config files in a directory.
*/
public static class ConfigFilter implements FilenameFilter {
/**
* {@inheritDoc}
*/
@Override
public boolean accept(File dir, String name) {
CLog.d("%s/%s", dir.getAbsolutePath(), name);
return name.endsWith(CONFIG_EXT);
}
}
/**
* {@inheritDoc}
*/
@Override
public LinkedList<IModuleDef> getModules(String serial, int shardIndex) {
Collections.sort(mNonTokenModules, new ExecutionOrderComparator());
List<IModuleDef> modules = getShard(mNonTokenModules, shardIndex, mTotalShards);
if (modules == null) {
modules = new LinkedList<IModuleDef>();
}
long estimatedTime = 0;
for (IModuleDef def : modules) {
estimatedTime += def.getRuntimeHint();
}
// FIXME: Token Modules are the only last part that is not deterministic.
synchronized (lock) {
// Get tokens from the device
Set<String> tokens = mDeviceTokens.get(serial);
if (tokens != null && !tokens.isEmpty()) {
// if it matches any of the token modules, add them
for (IModuleDef def : mTokenModules) {
if (!mTokenModuleScheduled.contains(def)) {
if (tokens.equals(def.getTokens())) {
modules.add(def);
CLog.d("Adding %s to scheduled token", def);
mTokenModuleScheduled.add(def);
}
}
}
}
// the last shard going through may add everything remaining.
if (mInitCount == (mTotalShards - 1) &&
mTokenModuleScheduled.size() != mTokenModules.size()) {
mTokenModules.removeAll(mTokenModuleScheduled);
if (mTotalShards != 1) {
// Only print the warnings if we are sharding.
CLog.e("Could not find any token for %s. Adding to last shard.", mTokenModules);
}
modules.addAll(mTokenModules);
}
mInitCount++;
}
Collections.sort(modules, new ExecutionOrderComparator());
int uniqueCount = UniqueModuleCountUtil.countUniqueModules(modules);
CLog.logAndDisplay(LogLevel.INFO, "%s running %s test sub-modules, expected to complete "
+ "in %s.", serial, uniqueCount, TimeUtil.formatElapsedTime(estimatedTime));
CLog.d("module list for this shard: %s", modules);
LinkedList<IModuleDef> tests = new LinkedList<>();
tests.addAll(modules);
return tests;
}
/**
* Helper to linearly split the list into shards with balanced runtimeHint.
* Exposed for testing.
*/
protected List<IModuleDef> getShard(List<IModuleDef> fullList, int shardIndex, int totalShard) {
List<List<IModuleDef>> res = LinearPartition.split(fullList, totalShard);
if (res.isEmpty()) {
return null;
}
if (shardIndex >= res.size()) {
// If we could not shard up to expectation
return null;
}
return res.get(shardIndex);
}
/**
* @return the {@link List} of modules whose name contains the given pattern.
*/
public static List<String> getModuleNamesMatching(File directory, String pattern) {
String[] names = directory.list(new NameFilter(pattern));
List<String> modules = new ArrayList<String>(names.length);
for (String name : names) {
int index = name.indexOf(CONFIG_EXT);
if (index > 0) {
String module = name.substring(0, index);
if (module.equals(pattern)) {
// Pattern represents a single module, just return a single-item list
modules = new ArrayList<>(1);
modules.add(module);
return modules;
}
modules.add(module);
}
}
return modules;
}
private static void putArgs(List<String> args,
Map<String, Map<String, List<String>>> argsMap) {
for (String arg : args) {
String[] parts = arg.split(":");
String target = parts[0];
String name = parts[1];
String value;
if (parts.length == 4) {
// key and value given, keep the pair delimited by ':' and stored as value
value = String.format("%s:%s", parts[2], parts[3]);
} else {
value = parts[2];
}
Map<String, List<String>> map = argsMap.get(target);
if (map == null) {
map = new HashMap<>();
argsMap.put(target, map);
}
List<String> valueList = map.get(name);
if (valueList == null) {
valueList = new ArrayList<>();
map.put(name, valueList);
}
valueList.add(value);
}
}
/**
* Sort by name and use runtimeHint for separation, shortest test first.
*/
private static class ExecutionOrderComparator implements Comparator<IModuleDef> {
@Override
public int compare(IModuleDef def1, IModuleDef def2) {
int value1 = 0;
int value2 = 0;
if (ENDING_MODULES.containsKey(def1.getName())) {
value1 = ENDING_MODULES.get(def1.getName());
}
if (ENDING_MODULES.containsKey(def2.getName())) {
value2 = ENDING_MODULES.get(def2.getName());
}
if (value1 == 0 && value2 == 0) {
int time = (int) Math.signum(def1.getRuntimeHint() - def2.getRuntimeHint());
if (time == 0) {
return def1.getName().compareTo(def2.getName());
}
return time;
}
return (int) Math.signum(value1 - value2);
}
}
/**
* {@inheritDoc}
*/
@Override
public void tearDown() {
mNonTokenModules.clear();
mTokenModules.clear();
mIncludeFilters.clear();
mExcludeFilters.clear();
mTestArgs.clear();
mModuleArgs.clear();
}
/**
* @return the mConfigFactory
*/
protected IConfigurationFactory getConfigFactory() {
return mConfigFactory;
}
}
| UTF-8 | Java | 26,837 | java | ModuleRepo.java | Java | [] | null | [] | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.compatibility.common.tradefed.testtype;
import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
import com.android.compatibility.common.tradefed.result.TestRunHandler;
import com.android.compatibility.common.tradefed.util.LinearPartition;
import com.android.compatibility.common.tradefed.util.UniqueModuleCountUtil;
import com.android.compatibility.common.util.TestFilter;
import com.android.ddmlib.Log.LogLevel;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.config.ConfigurationException;
import com.android.tradefed.config.ConfigurationFactory;
import com.android.tradefed.config.IConfiguration;
import com.android.tradefed.config.IConfigurationFactory;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.testtype.IStrictShardableTest;
import com.android.tradefed.testtype.ITestFileFilterReceiver;
import com.android.tradefed.testtype.ITestFilterReceiver;
import com.android.tradefed.util.AbiUtils;
import com.android.tradefed.util.FileUtil;
import com.android.tradefed.util.MultiMap;
import com.android.tradefed.util.TimeUtil;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Retrieves Compatibility test module definitions from the repository.
*/
public class ModuleRepo implements IModuleRepo {
private static final String CONFIG_EXT = ".config";
private static final Map<String, Integer> ENDING_MODULES = new HashMap<>();
static {
// b/62732298 put testFullDisk in the end to accommodate CTSMediaStressTest temporally
ENDING_MODULES.put("CtsAppSecurityHostTestCases", 1);
ENDING_MODULES.put("CtsMonkeyTestCases", 2);
}
// Synchronization objects for Token Modules.
private int mInitCount = 0;
private Set<IModuleDef> mTokenModuleScheduled;
private static Object lock = new Object();
private int mTotalShards;
private Integer mShardIndex;
private Map<String, Set<String>> mDeviceTokens = new HashMap<>();
private Map<String, Map<String, List<String>>> mTestArgs = new HashMap<>();
private Map<String, Map<String, List<String>>> mModuleArgs = new HashMap<>();
private boolean mIncludeAll;
private Map<String, List<TestFilter>> mIncludeFilters = new HashMap<>();
private Map<String, List<TestFilter>> mExcludeFilters = new HashMap<>();
private IConfigurationFactory mConfigFactory = ConfigurationFactory.getInstance();
private volatile boolean mInitialized = false;
// Holds all the tests with tokens waiting to be run. Meaning the DUT must have a specific token.
private List<IModuleDef> mTokenModules = new ArrayList<>();
private List<IModuleDef> mNonTokenModules = new ArrayList<>();
/**
* {@inheritDoc}
*/
@Override
public int getNumberOfShards() {
return mTotalShards;
}
/**
* Returns the device tokens of this module repo. Exposed for testing.
*/
protected Map<String, Set<String>> getDeviceTokens() {
return mDeviceTokens;
}
/**
* A {@link FilenameFilter} to find all modules in a directory who match the given pattern.
*/
public static class NameFilter implements FilenameFilter {
private String mPattern;
public NameFilter(String pattern) {
mPattern = pattern;
}
/**
* {@inheritDoc}
*/
@Override
public boolean accept(File dir, String name) {
return name.contains(mPattern) && name.endsWith(CONFIG_EXT);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<IModuleDef> getNonTokenModules() {
return mNonTokenModules;
}
/**
* {@inheritDoc}
*/
@Override
public List<IModuleDef> getTokenModules() {
return mTokenModules;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getModuleIds() {
Set<String> moduleIdSet = new HashSet<>();
for (IModuleDef moduleDef : mNonTokenModules) {
moduleIdSet.add(moduleDef.getId());
}
for (IModuleDef moduleDef : mTokenModules) {
moduleIdSet.add(moduleDef.getId());
}
return moduleIdSet.toArray(new String[moduleIdSet.size()]);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isInitialized() {
return mInitialized;
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(int totalShards, Integer shardIndex, File testsDir, Set<IAbi> abis,
List<String> deviceTokens, List<String> testArgs, List<String> moduleArgs,
Set<String> includeFilters, Set<String> excludeFilters,
MultiMap<String, String> metadataIncludeFilters,
MultiMap<String, String> metadataExcludeFilters,
IBuildInfo buildInfo) {
CLog.d("Initializing ModuleRepo\nShards:%d\nTests Dir:%s\nABIs:%s\nDevice Tokens:%s\n" +
"Test Args:%s\nModule Args:%s\nIncludes:%s\nExcludes:%s",
totalShards, testsDir.getAbsolutePath(), abis, deviceTokens, testArgs, moduleArgs,
includeFilters, excludeFilters);
mInitialized = true;
mTotalShards = totalShards;
mShardIndex = shardIndex;
synchronized (lock) {
if (mTokenModuleScheduled == null) {
mTokenModuleScheduled = new HashSet<>();
}
}
for (String line : deviceTokens) {
String[] parts = line.split(":");
if (parts.length == 2) {
String key = parts[0];
String value = parts[1];
Set<String> list = mDeviceTokens.get(key);
if (list == null) {
list = new HashSet<>();
mDeviceTokens.put(key, list);
}
list.add(value);
} else {
throw new IllegalArgumentException(
String.format("Could not parse device token: %s", line));
}
}
putArgs(testArgs, mTestArgs);
putArgs(moduleArgs, mModuleArgs);
mIncludeAll = includeFilters.isEmpty();
// Include all the inclusions
addFilters(includeFilters, mIncludeFilters, abis);
// Exclude all the exclusions
addFilters(excludeFilters, mExcludeFilters, abis);
File[] configFiles = testsDir.listFiles(new ConfigFilter());
if (configFiles.length == 0) {
throw new IllegalArgumentException(
String.format("No config files found in %s", testsDir.getAbsolutePath()));
}
Map<String, Integer> shardedTestCounts = new HashMap<>();
for (File configFile : configFiles) {
final String name = configFile.getName().replace(CONFIG_EXT, "");
final String[] pathArg = new String[] { configFile.getAbsolutePath() };
try {
// Invokes parser to process the test module config file
// Need to generate a different config for each ABI as we cannot guarantee the
// configs are idempotent. This however means we parse the same file multiple times
for (IAbi abi : abis) {
String id = AbiUtils.createId(abi.getName(), name);
if (!shouldRunModule(id)) {
// If the module should not run tests based on the state of filters,
// skip this name/abi combination.
continue;
}
IConfiguration config = mConfigFactory.createConfigurationFromArgs(pathArg);
if (!filterByConfigMetadata(config,
metadataIncludeFilters, metadataExcludeFilters)) {
// if the module config did not pass the metadata filters, it's excluded
// from execution
continue;
}
Map<String, List<String>> args = new HashMap<>();
if (mModuleArgs.containsKey(name)) {
args.putAll(mModuleArgs.get(name));
}
if (mModuleArgs.containsKey(id)) {
args.putAll(mModuleArgs.get(id));
}
injectOptionsToConfig(args, config);
List<IRemoteTest> tests = config.getTests();
for (IRemoteTest test : tests) {
prepareTestClass(name, abi, config, test);
}
List<IRemoteTest> shardedTests = tests;
if (mTotalShards > 1) {
shardedTests = splitShardableTests(tests, buildInfo);
}
if (shardedTests.size() > 1) {
shardedTestCounts.put(id, shardedTests.size());
}
for (IRemoteTest test : shardedTests) {
addModuleDef(name, abi, test, pathArg);
}
}
} catch (ConfigurationException e) {
throw new RuntimeException(String.format("error parsing config file: %s",
configFile.getName()), e);
}
}
mExcludeFilters.clear();
TestRunHandler.setTestRuns(new CompatibilityBuildHelper(buildInfo), shardedTestCounts);
}
/**
* Prepare to run test classes.
*
* @param name module name
* @param abi IAbi object that contains abi information
* @param config IConfiguration object created from config file
* @param test test class
* @throws ConfigurationException
*/
protected void prepareTestClass(final String name, IAbi abi, IConfiguration config,
IRemoteTest test) throws ConfigurationException {
String className = test.getClass().getName();
Map<String, List<String>> testArgsMap = new HashMap<>();
if (mTestArgs.containsKey(className)) {
testArgsMap.putAll(mTestArgs.get(className));
}
injectOptionsToConfig(testArgsMap, config);
addFiltersToTest(test, abi, name);
}
/**
* Helper to inject options to a config.
*/
@VisibleForTesting
void injectOptionsToConfig(Map<String, List<String>> optionMap, IConfiguration config)
throws ConfigurationException{
for (Entry<String, List<String>> entry : optionMap.entrySet()) {
for (String entryValue : entry.getValue()) {
String entryName = entry.getKey();
if (entryValue.contains(":=")) {
// entryValue is key-value pair
String key = entryValue.substring(0, entryValue.indexOf(":="));
String value = entryValue.substring(entryValue.indexOf(":=") + 2);
config.injectOptionValue(entryName, key, value);
} else {
// entryValue is just the argument value
config.injectOptionValue(entryName, entryValue);
}
}
}
}
private List<IRemoteTest> splitShardableTests(List<IRemoteTest> tests, IBuildInfo buildInfo) {
ArrayList<IRemoteTest> shardedList = new ArrayList<>(tests.size());
for (IRemoteTest test : tests) {
if (test instanceof IBuildReceiver) {
((IBuildReceiver)test).setBuild(buildInfo);
}
if (mShardIndex != null && test instanceof IStrictShardableTest) {
for (int i = 0; i < mTotalShards; i++) {
shardedList.add(((IStrictShardableTest)test).getTestShard(mTotalShards, i));
}
} else {
shardedList.add(test);
}
}
return shardedList;
}
private void addFilters(Set<String> stringFilters,
Map<String, List<TestFilter>> filters, Set<IAbi> abis) {
for (String filterString : stringFilters) {
TestFilter filter = TestFilter.createFrom(filterString);
String abi = filter.getAbi();
if (abi == null) {
for (IAbi a : abis) {
addFilter(a.getName(), filter, filters);
}
} else {
addFilter(abi, filter, filters);
}
}
}
private void addFilter(String abi, TestFilter filter,
Map<String, List<TestFilter>> filters) {
getFilter(filters, AbiUtils.createId(abi, filter.getName())).add(filter);
}
private List<TestFilter> getFilter(Map<String, List<TestFilter>> filters, String id) {
List<TestFilter> fs = filters.get(id);
if (fs == null) {
fs = new ArrayList<>();
filters.put(id, fs);
}
return fs;
}
protected void addModuleDef(String name, IAbi abi, IRemoteTest test, String[] configPaths)
throws ConfigurationException {
// Invokes parser to process the test module config file
IConfiguration config = mConfigFactory.createConfigurationFromArgs(configPaths);
addModuleDef(new ModuleDef(name, abi, test, config.getTargetPreparers(),
config.getConfigurationDescription()));
}
protected void addModuleDef(IModuleDef moduleDef) {
Set<String> tokens = moduleDef.getTokens();
if (tokens != null && !tokens.isEmpty()) {
mTokenModules.add(moduleDef);
} else {
mNonTokenModules.add(moduleDef);
}
}
private void addFiltersToTest(IRemoteTest test, IAbi abi, String name) {
String moduleId = AbiUtils.createId(abi.getName(), name);
if (!(test instanceof ITestFilterReceiver)) {
throw new IllegalArgumentException(String.format(
"Test in module %s must implement ITestFilterReceiver.", moduleId));
}
List<TestFilter> mdIncludes = getFilter(mIncludeFilters, moduleId);
List<TestFilter> mdExcludes = getFilter(mExcludeFilters, moduleId);
if (!mdIncludes.isEmpty()) {
addTestIncludes((ITestFilterReceiver) test, mdIncludes, name);
}
if (!mdExcludes.isEmpty()) {
addTestExcludes((ITestFilterReceiver) test, mdExcludes, name);
}
}
@VisibleForTesting
protected boolean filterByConfigMetadata(IConfiguration config,
MultiMap<String, String> include, MultiMap<String, String> exclude) {
MultiMap<String, String> metadata = config.getConfigurationDescription().getAllMetaData();
boolean shouldInclude = false;
for (String key : include.keySet()) {
Set<String> filters = new HashSet<>(include.get(key));
if (metadata.containsKey(key)) {
filters.retainAll(metadata.get(key));
if (!filters.isEmpty()) {
// inclusion filter is not empty and there's at least one matching inclusion
// rule so there's no need to match other inclusion rules
shouldInclude = true;
break;
}
}
}
if (!include.isEmpty() && !shouldInclude) {
// if inclusion filter is not empty and we didn't find a match, the module will not be
// included
return false;
}
// Now evaluate exclusion rules, this ordering also means that exclusion rules may override
// inclusion rules: a config already matched for inclusion may still be excluded if matching
// rules exist
for (String key : exclude.keySet()) {
Set<String> filters = new HashSet<>(exclude.get(key));
if (metadata.containsKey(key)) {
filters.retainAll(metadata.get(key));
if (!filters.isEmpty()) {
// we found at least one matching exclusion rules, so we are excluding this
// this module
return false;
}
}
}
// we've matched at least one inclusion rule (if there's any) AND we didn't match any of the
// exclusion rules (if there's any)
return true;
}
private boolean shouldRunModule(String moduleId) {
List<TestFilter> mdIncludes = getFilter(mIncludeFilters, moduleId);
List<TestFilter> mdExcludes = getFilter(mExcludeFilters, moduleId);
// if including all modules or includes exist for this module, and there are not excludes
// for the entire module, this module should be run.
return (mIncludeAll || !mdIncludes.isEmpty()) && !containsModuleExclude(mdExcludes);
}
private void addTestIncludes(ITestFilterReceiver test, List<TestFilter> includes,
String name) {
if (test instanceof ITestFileFilterReceiver) {
File includeFile = createFilterFile(name, ".include", includes);
((ITestFileFilterReceiver)test).setIncludeTestFile(includeFile);
} else {
// add test includes one at a time
for (TestFilter include : includes) {
String filterTestName = include.getTest();
if (filterTestName != null) {
test.addIncludeFilter(filterTestName);
}
}
}
}
private void addTestExcludes(ITestFilterReceiver test, List<TestFilter> excludes,
String name) {
if (test instanceof ITestFileFilterReceiver) {
File excludeFile = createFilterFile(name, ".exclude", excludes);
((ITestFileFilterReceiver)test).setExcludeTestFile(excludeFile);
} else {
// add test excludes one at a time
for (TestFilter exclude : excludes) {
test.addExcludeFilter(exclude.getTest());
}
}
}
private File createFilterFile(String prefix, String suffix, List<TestFilter> filters) {
File filterFile = null;
PrintWriter out = null;
try {
filterFile = FileUtil.createTempFile(prefix, suffix);
out = new PrintWriter(filterFile);
for (TestFilter filter : filters) {
String filterTest = filter.getTest();
if (filterTest != null) {
out.println(filterTest);
}
}
out.flush();
} catch (IOException e) {
throw new RuntimeException("Failed to create filter file");
} finally {
if (out != null) {
out.close();
}
}
filterFile.deleteOnExit();
return filterFile;
}
/*
* Returns true iff one or more test filters in excludes apply to the entire module.
*/
private boolean containsModuleExclude(Collection<TestFilter> excludes) {
for (TestFilter exclude : excludes) {
if (exclude.getTest() == null) {
return true;
}
}
return false;
}
/**
* A {@link FilenameFilter} to find all the config files in a directory.
*/
public static class ConfigFilter implements FilenameFilter {
/**
* {@inheritDoc}
*/
@Override
public boolean accept(File dir, String name) {
CLog.d("%s/%s", dir.getAbsolutePath(), name);
return name.endsWith(CONFIG_EXT);
}
}
/**
* {@inheritDoc}
*/
@Override
public LinkedList<IModuleDef> getModules(String serial, int shardIndex) {
Collections.sort(mNonTokenModules, new ExecutionOrderComparator());
List<IModuleDef> modules = getShard(mNonTokenModules, shardIndex, mTotalShards);
if (modules == null) {
modules = new LinkedList<IModuleDef>();
}
long estimatedTime = 0;
for (IModuleDef def : modules) {
estimatedTime += def.getRuntimeHint();
}
// FIXME: Token Modules are the only last part that is not deterministic.
synchronized (lock) {
// Get tokens from the device
Set<String> tokens = mDeviceTokens.get(serial);
if (tokens != null && !tokens.isEmpty()) {
// if it matches any of the token modules, add them
for (IModuleDef def : mTokenModules) {
if (!mTokenModuleScheduled.contains(def)) {
if (tokens.equals(def.getTokens())) {
modules.add(def);
CLog.d("Adding %s to scheduled token", def);
mTokenModuleScheduled.add(def);
}
}
}
}
// the last shard going through may add everything remaining.
if (mInitCount == (mTotalShards - 1) &&
mTokenModuleScheduled.size() != mTokenModules.size()) {
mTokenModules.removeAll(mTokenModuleScheduled);
if (mTotalShards != 1) {
// Only print the warnings if we are sharding.
CLog.e("Could not find any token for %s. Adding to last shard.", mTokenModules);
}
modules.addAll(mTokenModules);
}
mInitCount++;
}
Collections.sort(modules, new ExecutionOrderComparator());
int uniqueCount = UniqueModuleCountUtil.countUniqueModules(modules);
CLog.logAndDisplay(LogLevel.INFO, "%s running %s test sub-modules, expected to complete "
+ "in %s.", serial, uniqueCount, TimeUtil.formatElapsedTime(estimatedTime));
CLog.d("module list for this shard: %s", modules);
LinkedList<IModuleDef> tests = new LinkedList<>();
tests.addAll(modules);
return tests;
}
/**
* Helper to linearly split the list into shards with balanced runtimeHint.
* Exposed for testing.
*/
protected List<IModuleDef> getShard(List<IModuleDef> fullList, int shardIndex, int totalShard) {
List<List<IModuleDef>> res = LinearPartition.split(fullList, totalShard);
if (res.isEmpty()) {
return null;
}
if (shardIndex >= res.size()) {
// If we could not shard up to expectation
return null;
}
return res.get(shardIndex);
}
/**
* @return the {@link List} of modules whose name contains the given pattern.
*/
public static List<String> getModuleNamesMatching(File directory, String pattern) {
String[] names = directory.list(new NameFilter(pattern));
List<String> modules = new ArrayList<String>(names.length);
for (String name : names) {
int index = name.indexOf(CONFIG_EXT);
if (index > 0) {
String module = name.substring(0, index);
if (module.equals(pattern)) {
// Pattern represents a single module, just return a single-item list
modules = new ArrayList<>(1);
modules.add(module);
return modules;
}
modules.add(module);
}
}
return modules;
}
private static void putArgs(List<String> args,
Map<String, Map<String, List<String>>> argsMap) {
for (String arg : args) {
String[] parts = arg.split(":");
String target = parts[0];
String name = parts[1];
String value;
if (parts.length == 4) {
// key and value given, keep the pair delimited by ':' and stored as value
value = String.format("%s:%s", parts[2], parts[3]);
} else {
value = parts[2];
}
Map<String, List<String>> map = argsMap.get(target);
if (map == null) {
map = new HashMap<>();
argsMap.put(target, map);
}
List<String> valueList = map.get(name);
if (valueList == null) {
valueList = new ArrayList<>();
map.put(name, valueList);
}
valueList.add(value);
}
}
/**
* Sort by name and use runtimeHint for separation, shortest test first.
*/
private static class ExecutionOrderComparator implements Comparator<IModuleDef> {
@Override
public int compare(IModuleDef def1, IModuleDef def2) {
int value1 = 0;
int value2 = 0;
if (ENDING_MODULES.containsKey(def1.getName())) {
value1 = ENDING_MODULES.get(def1.getName());
}
if (ENDING_MODULES.containsKey(def2.getName())) {
value2 = ENDING_MODULES.get(def2.getName());
}
if (value1 == 0 && value2 == 0) {
int time = (int) Math.signum(def1.getRuntimeHint() - def2.getRuntimeHint());
if (time == 0) {
return def1.getName().compareTo(def2.getName());
}
return time;
}
return (int) Math.signum(value1 - value2);
}
}
/**
* {@inheritDoc}
*/
@Override
public void tearDown() {
mNonTokenModules.clear();
mTokenModules.clear();
mIncludeFilters.clear();
mExcludeFilters.clear();
mTestArgs.clear();
mModuleArgs.clear();
}
/**
* @return the mConfigFactory
*/
protected IConfigurationFactory getConfigFactory() {
return mConfigFactory;
}
}
| 26,837 | 0.586206 | 0.583858 | 687 | 38.064045 | 27.621563 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608442 | false | false | 9 |
b2a02b1c2118df9d3fd8f9319b6962bf6fffa713 | 24,618,752,543,418 | faad302e154c779ada4a77c2469fd46f3e9f8ae9 | /java2/lesson3.java2/src/ex3/Main3.java | 91193a59711ccc70268927bd8a1a25cc592ca7e9 | [] | no_license | SurferSteve/Idea-Projects | https://github.com/SurferSteve/Idea-Projects | 5b9495bee86c62b86fe2c7f853b03d735d5a0fd6 | 49ae728cf73f98185ed5232a77951379bdd4dafc | refs/heads/master | 2021-01-21T04:40:19.659000 | 2016-07-01T11:12:57 | 2016-07-01T11:13:45 | 51,777,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ex3;
import ex3.controller.LoginDialogController;
import ex3.view.LoginDialog;
/**
* Created by Steve on 24.06.2016.
*/
public class Main3 {
public static void main(String[] args) {
LoginDialogController controller = new LoginDialogController();
LoginDialog dialog = new LoginDialog();
dialog.setLoginDialogController(controller);
dialog.pack();
dialog.setVisible(true);
System.exit(0); // убрать, чтобы
}
}
| UTF-8 | Java | 487 | java | Main3.java | Java | [
{
"context": "r;\nimport ex3.view.LoginDialog;\n\n/**\n * Created by Steve on 24.06.2016.\n */\npublic class Main3 {\n publi",
"end": 112,
"score": 0.9939675331115723,
"start": 107,
"tag": "NAME",
"value": "Steve"
}
] | null | [] | package ex3;
import ex3.controller.LoginDialogController;
import ex3.view.LoginDialog;
/**
* Created by Steve on 24.06.2016.
*/
public class Main3 {
public static void main(String[] args) {
LoginDialogController controller = new LoginDialogController();
LoginDialog dialog = new LoginDialog();
dialog.setLoginDialogController(controller);
dialog.pack();
dialog.setVisible(true);
System.exit(0); // убрать, чтобы
}
}
| 487 | 0.676471 | 0.64916 | 18 | 25.444445 | 20.827925 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 9 |
70951379ce766c93b00a022e7552413cba1a9610 | 31,714,038,569,586 | 8ba7e66ca0c880a5b251e76309382e1bac17c3bd | /code/client/corepower/platform/src/com/chinaviponline/erp/corepower/api/pfl/sm/UserDetailInfo.java | d19a719c51b22bf4f518c57340cafceca0982cfd | [] | no_license | gongweichuan/gongweichuan | https://github.com/gongweichuan/gongweichuan | b80571d21f8d8d00163fc809ed36aae78887ae40 | 65c4033f95257cd8f33bfd5723ba643291beb8ca | refs/heads/master | 2016-09-05T20:12:18.033000 | 2013-04-09T15:53:28 | 2013-04-09T15:53:28 | 34,544,114 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.chinaviponline.erp.corepower.api.pfl.sm;
import java.util.Date;
/**
* <p>文件名称:UserDetailInfo.java</p>
* <p>文件描述:</p>
* <p>版权所有: 版权所有(C)2007-2017</p>
* <p>公 司: 与龙共舞独立工作室</p>
* <p>内容摘要: </p>
* <p>其他说明: </p>
* <p>完成日期:2008-6-17</p>
* <p>修改记录1:</p>
* <pre>
* 修改日期: 版本号: 修改人: 修改内容:
* </pre>
* <p>修改记录2:</p>
*
* @version 1.0
* @author 龚为川
* @email gongweichuan(AT)gmail.com
*/
public interface UserDetailInfo extends UserInfo
{
public static interface LoginLimitInfo
{
public abstract String getLoginType();
public abstract int getMaxConcurrentLogin();
}
public abstract void setName(String s);
public abstract void setFullName(String s);
public abstract void setDescription(String s);
public abstract void setPhoneNumber(String s);
public abstract void setEMailAddress(String s);
public abstract void setDepartmentID(int i);
public abstract String getPassword();
public abstract void setPassword(String s);
public abstract int getUserValidDays();
public abstract void setUserValidDays(int i);
public abstract int getPasswordValidDays();
public abstract void setPasswordValidDays(int i);
public abstract boolean isDisable();
public abstract void setDisable(boolean flag);
public abstract Date getCreateTime();
public abstract Date getPasswordEnableTime();
/**
* @deprecated Method getMaxConcurrentLogin is deprecated
*/
public abstract int getMaxConcurrentLogin();
public abstract int getMaxConcurrentLogin(String s);
public abstract LoginLimitInfo[] getConcurrentLoginLimit();
/**
* @deprecated Method setMaxConurrentLogin is deprecated
*/
public abstract void setMaxConurrentLogin(int i);
public abstract void setMaxConurrentLogin(String s, int i);
public abstract String getWorkTime();
public abstract void setWorkTime(String s);
public abstract int[] getRoleArray();
public abstract void setRoleArray(int ai[]);
public abstract int[] getRoleSetArray();
public abstract void setRoleSetArray(int ai[]);
public abstract int getCreatorID();
public abstract void setCreatorID(int i);
public abstract boolean isPasswordModifiable();
public abstract int getAutoLogoutTime();
}
| UTF-8 | Java | 2,495 | java | UserDetailInfo.java | Java | [
{
"context": "e>\n * <p>修改记录2:</p>\n *\n * @version 1.0\n * @author 龚为川\n * @email gongweichuan(AT)gmail.com\n */\npublic i",
"end": 386,
"score": 0.999842643737793,
"start": 383,
"tag": "NAME",
"value": "龚为川"
},
{
"context": ":</p>\n *\n * @version 1.0\n * @author 龚为川\n * @email g... | null | [] | /**
*
*/
package com.chinaviponline.erp.corepower.api.pfl.sm;
import java.util.Date;
/**
* <p>文件名称:UserDetailInfo.java</p>
* <p>文件描述:</p>
* <p>版权所有: 版权所有(C)2007-2017</p>
* <p>公 司: 与龙共舞独立工作室</p>
* <p>内容摘要: </p>
* <p>其他说明: </p>
* <p>完成日期:2008-6-17</p>
* <p>修改记录1:</p>
* <pre>
* 修改日期: 版本号: 修改人: 修改内容:
* </pre>
* <p>修改记录2:</p>
*
* @version 1.0
* @author 龚为川
* @email <EMAIL>(AT)gmail.com
*/
public interface UserDetailInfo extends UserInfo
{
public static interface LoginLimitInfo
{
public abstract String getLoginType();
public abstract int getMaxConcurrentLogin();
}
public abstract void setName(String s);
public abstract void setFullName(String s);
public abstract void setDescription(String s);
public abstract void setPhoneNumber(String s);
public abstract void setEMailAddress(String s);
public abstract void setDepartmentID(int i);
public abstract String getPassword();
public abstract void setPassword(String s);
public abstract int getUserValidDays();
public abstract void setUserValidDays(int i);
public abstract int getPasswordValidDays();
public abstract void setPasswordValidDays(int i);
public abstract boolean isDisable();
public abstract void setDisable(boolean flag);
public abstract Date getCreateTime();
public abstract Date getPasswordEnableTime();
/**
* @deprecated Method getMaxConcurrentLogin is deprecated
*/
public abstract int getMaxConcurrentLogin();
public abstract int getMaxConcurrentLogin(String s);
public abstract LoginLimitInfo[] getConcurrentLoginLimit();
/**
* @deprecated Method setMaxConurrentLogin is deprecated
*/
public abstract void setMaxConurrentLogin(int i);
public abstract void setMaxConurrentLogin(String s, int i);
public abstract String getWorkTime();
public abstract void setWorkTime(String s);
public abstract int[] getRoleArray();
public abstract void setRoleArray(int ai[]);
public abstract int[] getRoleSetArray();
public abstract void setRoleSetArray(int ai[]);
public abstract int getCreatorID();
public abstract void setCreatorID(int i);
public abstract boolean isPasswordModifiable();
public abstract int getAutoLogoutTime();
}
| 2,490 | 0.69073 | 0.682614 | 106 | 21.084906 | 22.213848 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.339623 | false | false | 9 |
0ccfa89986c7cc0a4d55fa9f5711855525cb0f35 | 19,885,698,646,011 | 55dcca65ed66a7b5c1fa4d607687104b4ada0e01 | /src/java/com/idega/block/process/data/CaseLogHomeImpl.java | ee9edaaa12316bf5adb22a72b29d50d46d85f94d | [] | no_license | shyboy2020/com.idega.block.process | https://github.com/shyboy2020/com.idega.block.process | 3e8f9a2f9cf6ca853997c22fac43668fabbdbd50 | 61e47d1e0f02669265e4c3512a6b4b2e08085275 | refs/heads/master | 2022-09-08T14:50:44.836000 | 2014-06-25T11:41:14 | 2014-06-25T11:41:14 | 296,477,481 | 1 | 0 | null | true | 2020-09-18T01:00:59 | 2020-09-18T01:00:58 | 2019-01-23T08:41:27 | 2020-06-04T07:29:01 | 1,055 | 0 | 0 | 0 | null | false | false | /*
* $Id: CaseLogHomeImpl.java 1.1 5.12.2004 laddi Exp $
* Created on 5.12.2004
*
* Copyright (C) 2004 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package com.idega.block.process.data;
import java.sql.Timestamp;
import java.util.Collection;
import javax.ejb.FinderException;
import com.idega.data.IDOException;
import com.idega.data.IDOFactory;
import com.idega.user.data.User;
/**
* Last modified: $Date: 2004/06/28 09:09:50 $ by $Author: laddi $
*
* @author <a href="mailto:laddi@idega.com">laddi</a>
* @version $Revision: 1.1 $
*/
public class CaseLogHomeImpl extends IDOFactory implements CaseLogHome {
private static final long serialVersionUID = 1L;
protected Class getEntityInterfaceClass() {
return CaseLog.class;
}
public CaseLog create() throws javax.ejb.CreateException {
return (CaseLog) super.createIDO();
}
public CaseLog findByPrimaryKey(Object pk) throws javax.ejb.FinderException {
return (CaseLog) super.findByPrimaryKeyIDO(pk);
}
public Collection findAllCaseLogsByCase(Case aCase) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCase(aCase);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByCaseOrderedByDate(Case aCase) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseOrderedByDate(aCase);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public CaseLog findLastCaseLogForCase(Case aCase) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
Object pk = ((CaseLogBMPBean) entity).ejbFindLastCaseLogForCase(aCase);
this.idoCheckInPooledEntity(entity);
return this.findByPrimaryKey(pk);
}
public Collection findAllCaseLogsByDate(Timestamp fromDate, Timestamp toDate) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByDate(fromDate, toDate);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByCaseAndDate(String caseCode, Timestamp fromDate, Timestamp toDate) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseAndDate(caseCode, fromDate, toDate);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
@Override
public Collection<CaseLog> findAllCaseLogs(Case theCase,
Timestamp fromDate, Timestamp toDate, User performer) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
Collection<Long> ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseAndDate(theCase, fromDate, toDate, performer);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByDateAndStatusChange(Timestamp fromDate, Timestamp toDate, String statusBefore, String statusAfter) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByDateAndStatusChange(fromDate, toDate, statusBefore, statusAfter);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByCaseAndDateAndStatusChange(String caseCode, Timestamp fromDate, Timestamp toDate, String statusBefore, String statusAfter) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseAndDateAndStatusChange(caseCode, fromDate, toDate, statusBefore, statusAfter);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public int getCountByStatusChange(Case theCase, String statusBefore, String statusAfter) throws IDOException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((CaseLogBMPBean) entity).ejbHomeGetCountByStatusChange(theCase, statusBefore, statusAfter);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
}
| UTF-8 | Java | 4,611 | java | CaseLogHomeImpl.java | Java | [
{
"context": "modified: $Date: 2004/06/28 09:09:50 $ by $Author: laddi $\n * \n * @author <a href=\"mailto:laddi@idega.com\"",
"end": 555,
"score": 0.9993014931678772,
"start": 550,
"tag": "USERNAME",
"value": "laddi"
},
{
"context": "y $Author: laddi $\n * \n * @author <a href=\"mai... | null | [] | /*
* $Id: CaseLogHomeImpl.java 1.1 5.12.2004 laddi Exp $
* Created on 5.12.2004
*
* Copyright (C) 2004 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package com.idega.block.process.data;
import java.sql.Timestamp;
import java.util.Collection;
import javax.ejb.FinderException;
import com.idega.data.IDOException;
import com.idega.data.IDOFactory;
import com.idega.user.data.User;
/**
* Last modified: $Date: 2004/06/28 09:09:50 $ by $Author: laddi $
*
* @author <a href="mailto:<EMAIL>">laddi</a>
* @version $Revision: 1.1 $
*/
public class CaseLogHomeImpl extends IDOFactory implements CaseLogHome {
private static final long serialVersionUID = 1L;
protected Class getEntityInterfaceClass() {
return CaseLog.class;
}
public CaseLog create() throws javax.ejb.CreateException {
return (CaseLog) super.createIDO();
}
public CaseLog findByPrimaryKey(Object pk) throws javax.ejb.FinderException {
return (CaseLog) super.findByPrimaryKeyIDO(pk);
}
public Collection findAllCaseLogsByCase(Case aCase) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCase(aCase);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByCaseOrderedByDate(Case aCase) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseOrderedByDate(aCase);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public CaseLog findLastCaseLogForCase(Case aCase) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
Object pk = ((CaseLogBMPBean) entity).ejbFindLastCaseLogForCase(aCase);
this.idoCheckInPooledEntity(entity);
return this.findByPrimaryKey(pk);
}
public Collection findAllCaseLogsByDate(Timestamp fromDate, Timestamp toDate) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByDate(fromDate, toDate);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByCaseAndDate(String caseCode, Timestamp fromDate, Timestamp toDate) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseAndDate(caseCode, fromDate, toDate);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
@Override
public Collection<CaseLog> findAllCaseLogs(Case theCase,
Timestamp fromDate, Timestamp toDate, User performer) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
Collection<Long> ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseAndDate(theCase, fromDate, toDate, performer);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByDateAndStatusChange(Timestamp fromDate, Timestamp toDate, String statusBefore, String statusAfter) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByDateAndStatusChange(fromDate, toDate, statusBefore, statusAfter);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public Collection findAllCaseLogsByCaseAndDateAndStatusChange(String caseCode, Timestamp fromDate, Timestamp toDate, String statusBefore, String statusAfter) throws FinderException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
java.util.Collection ids = ((CaseLogBMPBean) entity).ejbFindAllCaseLogsByCaseAndDateAndStatusChange(caseCode, fromDate, toDate, statusBefore, statusAfter);
this.idoCheckInPooledEntity(entity);
return this.getEntityCollectionForPrimaryKeys(ids);
}
public int getCountByStatusChange(Case theCase, String statusBefore, String statusAfter) throws IDOException {
com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity();
int theReturn = ((CaseLogBMPBean) entity).ejbHomeGetCountByStatusChange(theCase, statusBefore, statusAfter);
this.idoCheckInPooledEntity(entity);
return theReturn;
}
}
| 4,603 | 0.800694 | 0.79267 | 108 | 41.694443 | 41.015457 | 183 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.712963 | false | false | 9 |
8e66add933e4428135b4623c2860d5d9a77a1466 | 901,943,145,962 | 565fa305fba19ade71393109afe20d8a71a56854 | /src/ru/mk/gs/config/ConfigManager.java | 735bedf998192b57d4382ca22453736e278533f3 | [] | no_license | dumh/geospy | https://github.com/dumh/geospy | d214d97b34f069bcbec933648147763dae849744 | c464b0a70c8fe99196270d4a040c21848bd8b9dc | refs/heads/master | 2021-01-10T18:46:53.448000 | 2013-12-12T06:52:15 | 2013-12-12T06:52:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.mk.gs.config;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.util.Log;
import ru.mk.gs.GSApplication;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
/**
* @author mkasumov
*/
public class ConfigManager extends ContextWrapper {
public static final String URL = "url";
public static final String CREDENTIALS = "credentials";
public static final String MY_SUBJECT = "mySubject";
public static final String TRACKED_SUBJECTS = "trackedSubjects";
private GSApplication app;
private Config config;
public ConfigManager(GSApplication app) {
super(app);
this.app = app;
}
public Config getConfig() {
return config.clone();
}
public boolean isLoaded() {
return config != null;
}
// ----------------------------------------------------------------------------------------------------------------
private void setNewConfig(Config newConfig) {
if (newConfig.getUrl() == null) {
throw new RuntimeException("Missing URL");
}
if (newConfig.getMySubject() == null) {
throw new RuntimeException("My subject not specified");
}
this.config = newConfig;
}
public void loadFromProperties(Properties config) {
final Config newConfig = new Config();
try {
newConfig.setUrl(new URL(config.getProperty(URL)));
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid or missing URL", e);
}
newConfig.setCredentials(config.getProperty(CREDENTIALS));
newConfig.setMySubject(config.getProperty(MY_SUBJECT));
newConfig.setTrackedSubjects(explode(config.getProperty(TRACKED_SUBJECTS)));
setNewConfig(newConfig);
afterLoaded(true);
}
private List<String> explode(String value) {
if (value == null || value.trim().isEmpty()) {
return Collections.emptyList();
}
return Arrays.asList(value.split(","));
}
private String implode(List<String> list) {
if (list == null) {
return null;
}
final StringBuilder sb = new StringBuilder(list.size() * 5);
for (String value : list) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(value);
}
return sb.toString();
}
public void loadFromPreferences() {
final SharedPreferences pref = GSApplication.getSharedPreferences(this);
final Config newConfig = new Config();
try {
newConfig.setUrl(new URL(pref.getString(URL, null)));
} catch (MalformedURLException e) {
Log.e("GS", "URL in preferences is not found or invalid", e);
}
newConfig.setCredentials(pref.getString(CREDENTIALS, null));
newConfig.setMySubject(pref.getString(MY_SUBJECT, null));
newConfig.setTrackedSubjects(explode(pref.getString(TRACKED_SUBJECTS, null)));
setNewConfig(newConfig);
afterLoaded(false);
}
public void saveToPreferences() {
if (config == null) {
return;
}
final SharedPreferences pref = GSApplication.getSharedPreferences(this);
final SharedPreferences.Editor editor = pref.edit();
editor.putString(URL, config.getUrl().toString());
editor.putString(CREDENTIALS, config.getCredentials());
editor.putString(MY_SUBJECT, config.getMySubject());
editor.putString(TRACKED_SUBJECTS, implode(config.getTrackedSubjects()));
editor.commit();
}
private void afterLoaded(boolean saveToPreferences) {
if (saveToPreferences) {
saveToPreferences();
}
app.onConfigLoaded();
}
}
| UTF-8 | Java | 3,937 | java | ConfigManager.java | Java | [
{
"context": "List;\nimport java.util.Properties;\n\n/**\n * @author mkasumov\n */\npublic class ConfigManager extends ContextWra",
"end": 355,
"score": 0.999150812625885,
"start": 347,
"tag": "USERNAME",
"value": "mkasumov"
}
] | null | [] | package ru.mk.gs.config;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.util.Log;
import ru.mk.gs.GSApplication;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
/**
* @author mkasumov
*/
public class ConfigManager extends ContextWrapper {
public static final String URL = "url";
public static final String CREDENTIALS = "credentials";
public static final String MY_SUBJECT = "mySubject";
public static final String TRACKED_SUBJECTS = "trackedSubjects";
private GSApplication app;
private Config config;
public ConfigManager(GSApplication app) {
super(app);
this.app = app;
}
public Config getConfig() {
return config.clone();
}
public boolean isLoaded() {
return config != null;
}
// ----------------------------------------------------------------------------------------------------------------
private void setNewConfig(Config newConfig) {
if (newConfig.getUrl() == null) {
throw new RuntimeException("Missing URL");
}
if (newConfig.getMySubject() == null) {
throw new RuntimeException("My subject not specified");
}
this.config = newConfig;
}
public void loadFromProperties(Properties config) {
final Config newConfig = new Config();
try {
newConfig.setUrl(new URL(config.getProperty(URL)));
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid or missing URL", e);
}
newConfig.setCredentials(config.getProperty(CREDENTIALS));
newConfig.setMySubject(config.getProperty(MY_SUBJECT));
newConfig.setTrackedSubjects(explode(config.getProperty(TRACKED_SUBJECTS)));
setNewConfig(newConfig);
afterLoaded(true);
}
private List<String> explode(String value) {
if (value == null || value.trim().isEmpty()) {
return Collections.emptyList();
}
return Arrays.asList(value.split(","));
}
private String implode(List<String> list) {
if (list == null) {
return null;
}
final StringBuilder sb = new StringBuilder(list.size() * 5);
for (String value : list) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(value);
}
return sb.toString();
}
public void loadFromPreferences() {
final SharedPreferences pref = GSApplication.getSharedPreferences(this);
final Config newConfig = new Config();
try {
newConfig.setUrl(new URL(pref.getString(URL, null)));
} catch (MalformedURLException e) {
Log.e("GS", "URL in preferences is not found or invalid", e);
}
newConfig.setCredentials(pref.getString(CREDENTIALS, null));
newConfig.setMySubject(pref.getString(MY_SUBJECT, null));
newConfig.setTrackedSubjects(explode(pref.getString(TRACKED_SUBJECTS, null)));
setNewConfig(newConfig);
afterLoaded(false);
}
public void saveToPreferences() {
if (config == null) {
return;
}
final SharedPreferences pref = GSApplication.getSharedPreferences(this);
final SharedPreferences.Editor editor = pref.edit();
editor.putString(URL, config.getUrl().toString());
editor.putString(CREDENTIALS, config.getCredentials());
editor.putString(MY_SUBJECT, config.getMySubject());
editor.putString(TRACKED_SUBJECTS, implode(config.getTrackedSubjects()));
editor.commit();
}
private void afterLoaded(boolean saveToPreferences) {
if (saveToPreferences) {
saveToPreferences();
}
app.onConfigLoaded();
}
}
| 3,937 | 0.610871 | 0.610363 | 125 | 30.496 | 25.207499 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584 | false | false | 9 |
a90045188583c979598d64ea9ae95e8b5bfa1bd3 | 21,182,778,729,969 | 78f1a358d61fe4938779fbce9a2b657199c9c8fc | /src/org/jb/crm/cus/domain/CstLost.java | f0259f9cdc6592c5ed5c008f6eb1accddd78d7cc | [] | no_license | chineseluo/crm | https://github.com/chineseluo/crm | 090924e4ea34619ad12ad57cf19a8f061c23f946 | 8ce500cecf2e9189cde300f60f528696c7416a36 | refs/heads/master | 2021-04-28T03:51:40.785000 | 2018-02-20T02:50:40 | 2018-02-20T02:50:40 | 122,148,333 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jb.crm.cus.domain;
import java.util.Date;
import org.jb.common.domain.BaseDomain;
import org.jb.crm.sys.domain.SysUser;
public class CstLost extends BaseDomain{
private CstCustomer lstCustomer ;///////外键
private SysUser lstCustManager;
private String lstCustName;
private String lstCustManagerName;
private Date lstLastOrderDate;
private Date lstLostDate;
private String lstDelay;
private String lstReason;
private String lstStatus;
public CstCustomer getLstCustomer() {
return lstCustomer;
}
public SysUser getLstCustManager() {
return lstCustManager;
}
public String getLstCustName() {
return lstCustName;
}
public String getLstCustManagerName() {
return lstCustManagerName;
}
public Date getLstLastOrderDate() {
return lstLastOrderDate;
}
public Date getLstLostDate() {
return lstLostDate;
}
public String getLstDelay() {
return lstDelay;
}
public String getLstReason() {
return lstReason;
}
public String getLstStatus() {
return lstStatus;
}
public void setLstCustomer(CstCustomer lstCustomer) {
this.lstCustomer = lstCustomer;
}
public void setLstCustManager(SysUser lstCustManager) {
this.lstCustManager = lstCustManager;
}
public void setLstCustName(String lstCustName) {
this.lstCustName = lstCustName;
}
public void setLstCustManagerName(String lstCustManagerName) {
this.lstCustManagerName = lstCustManagerName;
}
public void setLstLastOrderDate(Date lstLastOrderDate) {
this.lstLastOrderDate = lstLastOrderDate;
}
public void setLstLostDate(Date lstLostDate) {
this.lstLostDate = lstLostDate;
}
public void setLstDelay(String lstDelay) {
this.lstDelay = lstDelay;
}
public void setLstReason(String lstReason) {
this.lstReason = lstReason;
}
public void setLstStatus(String lstStatus) {
this.lstStatus = lstStatus;
}
}
| UTF-8 | Java | 1,833 | java | CstLost.java | Java | [] | null | [] | package org.jb.crm.cus.domain;
import java.util.Date;
import org.jb.common.domain.BaseDomain;
import org.jb.crm.sys.domain.SysUser;
public class CstLost extends BaseDomain{
private CstCustomer lstCustomer ;///////外键
private SysUser lstCustManager;
private String lstCustName;
private String lstCustManagerName;
private Date lstLastOrderDate;
private Date lstLostDate;
private String lstDelay;
private String lstReason;
private String lstStatus;
public CstCustomer getLstCustomer() {
return lstCustomer;
}
public SysUser getLstCustManager() {
return lstCustManager;
}
public String getLstCustName() {
return lstCustName;
}
public String getLstCustManagerName() {
return lstCustManagerName;
}
public Date getLstLastOrderDate() {
return lstLastOrderDate;
}
public Date getLstLostDate() {
return lstLostDate;
}
public String getLstDelay() {
return lstDelay;
}
public String getLstReason() {
return lstReason;
}
public String getLstStatus() {
return lstStatus;
}
public void setLstCustomer(CstCustomer lstCustomer) {
this.lstCustomer = lstCustomer;
}
public void setLstCustManager(SysUser lstCustManager) {
this.lstCustManager = lstCustManager;
}
public void setLstCustName(String lstCustName) {
this.lstCustName = lstCustName;
}
public void setLstCustManagerName(String lstCustManagerName) {
this.lstCustManagerName = lstCustManagerName;
}
public void setLstLastOrderDate(Date lstLastOrderDate) {
this.lstLastOrderDate = lstLastOrderDate;
}
public void setLstLostDate(Date lstLostDate) {
this.lstLostDate = lstLostDate;
}
public void setLstDelay(String lstDelay) {
this.lstDelay = lstDelay;
}
public void setLstReason(String lstReason) {
this.lstReason = lstReason;
}
public void setLstStatus(String lstStatus) {
this.lstStatus = lstStatus;
}
}
| 1,833 | 0.770913 | 0.770913 | 74 | 23.716217 | 17.570337 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.540541 | false | false | 9 |
8552dedae222a120401fb62467cffd0a5946fca1 | 13,134,009,997,390 | c54f96289ea98fc9ee17ad3bf48b78d8e661b7f6 | /src/main/java/ecoservices/warehouseservice/domain/Stock.java | 8c6d1f117135cf5eaed630c4d50319634dd70552 | [] | no_license | z1key/ms-warehouse-service | https://github.com/z1key/ms-warehouse-service | 76d19e906014183549794ce5de864116e11b736e | df8834c6f0be1aadbe836c776039de9e7eb9dcdf | refs/heads/master | 2021-05-11T16:04:53.148000 | 2018-02-05T18:22:45 | 2018-02-05T18:22:45 | 117,751,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ecoservices.warehouseservice.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class Stock {
@Id
@GeneratedValue
private long id;
private long productId;
private float weight;
private float height;
private float width;
private float length;
private int count;
public Stock() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
public float getLength() {
return length;
}
public void setLength(float length) {
this.length = length;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Stock)) return false;
Stock stock = (Stock) o;
return productId == stock.productId;
}
@Override
public int hashCode() {
return Objects.hash(productId);
}
}
| UTF-8 | Java | 1,707 | java | Stock.java | Java | [] | null | [] | package ecoservices.warehouseservice.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class Stock {
@Id
@GeneratedValue
private long id;
private long productId;
private float weight;
private float height;
private float width;
private float length;
private int count;
public Stock() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
public float getLength() {
return length;
}
public void setLength(float length) {
this.length = length;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Stock)) return false;
Stock stock = (Stock) o;
return productId == stock.productId;
}
@Override
public int hashCode() {
return Objects.hash(productId);
}
}
| 1,707 | 0.593439 | 0.593439 | 95 | 16.968422 | 14.772985 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.326316 | false | false | 9 |
63566a3b6b9195ecadcea809dc7080f99f5bf0de | 12,833,362,309,704 | f8356a88b4e9c4f348b8b7044d7ec6231902e31e | /src/main/java/wowjoy/fruits/ms/module/relation/mapper/ProjectTeamRelationMapper.java | f92cbbad286da595d3f4aa668771cbbb8877ccc1 | [] | no_license | WangziwenUnique/ms-fruits | https://github.com/WangziwenUnique/ms-fruits | 4712c5b888e4473feeedffb27db576c0e1bd0c44 | 92dcefdd06c47fa3e5836d66c990b6852fa59452 | refs/heads/master | 2020-02-17T10:22:58.871000 | 2018-08-08T06:50:05 | 2018-08-08T06:50:05 | 125,295,378 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wowjoy.fruits.ms.module.relation.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import wowjoy.fruits.ms.module.relation.entity.ProjectTeamRelation;
import wowjoy.fruits.ms.module.relation.example.ProjectTeamRelationExample;
import java.util.List;
@Mapper
public interface ProjectTeamRelationMapper{
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
long countByExample(ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int deleteByExample(ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int insert(ProjectTeamRelation record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int insertSelective(ProjectTeamRelation record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
List<ProjectTeamRelation> selectByExample(ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int updateByExampleSelective(@Param("record") ProjectTeamRelation record, @Param("example") ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int updateByExample(@Param("record") ProjectTeamRelation record, @Param("example") ProjectTeamRelationExample example);
} | UTF-8 | Java | 2,354 | java | ProjectTeamRelationMapper.java | Java | [] | null | [] | package wowjoy.fruits.ms.module.relation.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import wowjoy.fruits.ms.module.relation.entity.ProjectTeamRelation;
import wowjoy.fruits.ms.module.relation.example.ProjectTeamRelationExample;
import java.util.List;
@Mapper
public interface ProjectTeamRelationMapper{
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
long countByExample(ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int deleteByExample(ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int insert(ProjectTeamRelation record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int insertSelective(ProjectTeamRelation record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
List<ProjectTeamRelation> selectByExample(ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int updateByExampleSelective(@Param("record") ProjectTeamRelation record, @Param("example") ProjectTeamRelationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table project_team_relation
*
* @mbg.generated Tue Sep 12 13:20:42 CST 2017
*/
int updateByExample(@Param("record") ProjectTeamRelation record, @Param("example") ProjectTeamRelationExample example);
} | 2,354 | 0.713679 | 0.677995 | 67 | 34.149254 | 32.013176 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.223881 | false | false | 9 |
64cbd63728548d19cdcd8ee83b7c75da757ed303 | 1,340,029,807,712 | db3084c75571f1f744efc083cf277b35631c0a9d | /945. Minimum Increment to Make Array Unique.java | c5228586750a50b1019d9f7f09e90c2faeab48ac | [] | no_license | HuizeHuang/LeetCode | https://github.com/HuizeHuang/LeetCode | e4517d7cf92f0e432a041595e5c349777f48c62e | 977f0986965a9a45622879b4824fbff90fa45796 | refs/heads/master | 2020-07-14T18:39:10.390000 | 2020-04-11T17:13:46 | 2020-04-11T17:13:46 | 205,375,622 | 0 | 0 | null | false | 2020-01-19T15:19:28 | 2019-08-30T12:13:39 | 2020-01-18T18:33:04 | 2020-01-19T15:19:28 | 209 | 0 | 0 | 0 | Java | false | false | class Solution {
// Approach 1 - Array
// 0 <= A.length <= 40000
// Approach 2 - Math
// use a variable that represents the value that is supposed to be if all values are unique
public int minIncrementForUnique(int[] A) {
if (A.length == 0) return 0;
Arrays.sort(A);
int supposed = A[0], res = 0;
for (int num : A) {
// if supposed < num, means there does not exist repeated number
// if supposed > num, we need to add (s - num) to current value
res += Math.max(0, supposed - num);
supposed = Math.max(num + 1, supposed + 1);
}
return res;
}
}
| UTF-8 | Java | 678 | java | 945. Minimum Increment to Make Array Unique.java | Java | [] | null | [] | class Solution {
// Approach 1 - Array
// 0 <= A.length <= 40000
// Approach 2 - Math
// use a variable that represents the value that is supposed to be if all values are unique
public int minIncrementForUnique(int[] A) {
if (A.length == 0) return 0;
Arrays.sort(A);
int supposed = A[0], res = 0;
for (int num : A) {
// if supposed < num, means there does not exist repeated number
// if supposed > num, we need to add (s - num) to current value
res += Math.max(0, supposed - num);
supposed = Math.max(num + 1, supposed + 1);
}
return res;
}
}
| 678 | 0.536873 | 0.514749 | 20 | 32.900002 | 25.485094 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 9 |
3bef0b2692280b7b9670319d296b790eef298550 | 22,720,377,053,660 | a32e3bd822390f85ee14d522c8f25912847631ae | /src/com/Servlet/Register.java | ce41d10cac932ebc5a28117702b8a48d32c3cb46 | [
"Apache-2.0"
] | permissive | nullptrjzz/DaigoServlet | https://github.com/nullptrjzz/DaigoServlet | cdf221f7832e4a244f2a2ed3997350bf781811b3 | d2ebfc82f7b600d95c3927bb7bf42386b8873755 | refs/heads/master | 2021-04-09T13:12:25.800000 | 2018-03-11T06:49:44 | 2018-03-11T06:49:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.DBTool.DBUtil;
/**
* Servlet implementation class Register
*/
@WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String phoneNum = request.getParameter("phonenum");
String password = request.getParameter("password");
String headIcon = request.getParameter("headicon");
boolean type=false;//用于判断账号和密码是否与数据库中查询结果一致
String uId = "";
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
try
{
Connection con=DBUtil.getConnection();
Statement stmt=con.createStatement();
ResultSet checkExist = stmt.executeQuery("select * from daigo.user where phonenum=\'" + phoneNum + "\'");
//若未被注册
if (!checkExist.next()) {
type = true;
PreparedStatement pstate = con.prepareStatement("INSERT INTO user (discode, phonenum, password, verify,"
+ "campuscode, headicon) VALUES(?,?,?,?,?,?)");
pstate.setString(1, "86");
pstate.setString(2, phoneNum);
pstate.setString(3, password);
pstate.setInt(4, 0);
pstate.setInt(5, 0);
pstate.setString(6, headIcon);
int code = pstate.executeUpdate();
pstate.close();
if (code > 0) {
String sql="select * from daigo.user where phonenum="+phoneNum;
ResultSet rs=stmt.executeQuery(sql);
rs.first();
uId = rs.getString("userid");
PreparedStatement pstate1 = con.prepareStatement("CREATE TABLE `user_" + uId + "`("
+ "`index` int NOT NULL AUTO_INCREMENT,"
+ "`orderid` text,"
+ "`type` int(1) NULL DEFAULT 0,"
+ "`addressed` int(1) NULL DEFAULT 0,"
+ "PRIMARY KEY (`index`)"
+ ")");
pstate1.executeUpdate();
pstate1 = con.prepareStatement("update daigo.user set nickname=? where userid=?");
pstate1.setString(1, "uid" + uId);
pstate1.setString(2, uId);
pstate1.executeUpdate();
pstate1.close();
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
DBUtil.Close();
if (type == true) {
out.print(uId);
} else {
out.print(type);
}
out.flush();
out.close();
}
}
}
| UTF-8 | Java | 4,181 | java | Register.java | Java | [] | null | [] | package com.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.DBTool.DBUtil;
/**
* Servlet implementation class Register
*/
@WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String phoneNum = request.getParameter("phonenum");
String password = request.getParameter("password");
String headIcon = request.getParameter("headicon");
boolean type=false;//用于判断账号和密码是否与数据库中查询结果一致
String uId = "";
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
try
{
Connection con=DBUtil.getConnection();
Statement stmt=con.createStatement();
ResultSet checkExist = stmt.executeQuery("select * from daigo.user where phonenum=\'" + phoneNum + "\'");
//若未被注册
if (!checkExist.next()) {
type = true;
PreparedStatement pstate = con.prepareStatement("INSERT INTO user (discode, phonenum, password, verify,"
+ "campuscode, headicon) VALUES(?,?,?,?,?,?)");
pstate.setString(1, "86");
pstate.setString(2, phoneNum);
pstate.setString(3, password);
pstate.setInt(4, 0);
pstate.setInt(5, 0);
pstate.setString(6, headIcon);
int code = pstate.executeUpdate();
pstate.close();
if (code > 0) {
String sql="select * from daigo.user where phonenum="+phoneNum;
ResultSet rs=stmt.executeQuery(sql);
rs.first();
uId = rs.getString("userid");
PreparedStatement pstate1 = con.prepareStatement("CREATE TABLE `user_" + uId + "`("
+ "`index` int NOT NULL AUTO_INCREMENT,"
+ "`orderid` text,"
+ "`type` int(1) NULL DEFAULT 0,"
+ "`addressed` int(1) NULL DEFAULT 0,"
+ "PRIMARY KEY (`index`)"
+ ")");
pstate1.executeUpdate();
pstate1 = con.prepareStatement("update daigo.user set nickname=? where userid=?");
pstate1.setString(1, "uid" + uId);
pstate1.setString(2, uId);
pstate1.executeUpdate();
pstate1.close();
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
DBUtil.Close();
if (type == true) {
out.print(uId);
} else {
out.print(type);
}
out.flush();
out.close();
}
}
}
| 4,181 | 0.550036 | 0.543252 | 121 | 32.107437 | 26.063433 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.46281 | false | false | 9 |
bff98711a04bbebdac017b4979d3da9cde5c2616 | 8,392,366,148,622 | 9fb5bd6eb694c1498a51c20d09b0dbf7944b7cb5 | /TestScheduling/src/hr/unizg/fer/hmo/ts/demo/VisualizationDemo.java | 90f4618118171c670d7380de9dd93d10b25dc8b2 | [] | no_license | mbukal/testsched | https://github.com/mbukal/testsched | 26f83ab2eeec30c4669adc8c943a080667dcf82c | 2946c13f51492eff23e98a01733de172b2a635d5 | refs/heads/master | 2021-09-04T05:30:19.759000 | 2018-01-16T09:55:39 | 2018-01-16T09:55:39 | 114,860,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hr.unizg.fer.hmo.ts.demo;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.IntStream;
import hr.unizg.fer.hmo.ts.optimization.ga.mutation.MutationOperator;
import hr.unizg.fer.hmo.ts.scheduler.model.problem.Problem;
import hr.unizg.fer.hmo.ts.scheduler.model.problem.VerboseProblem;
import hr.unizg.fer.hmo.ts.scheduler.model.solution.Solution;
import hr.unizg.fer.hmo.ts.scheduler.model.solution.decoding.SecretSolutionDecoder;
import hr.unizg.fer.hmo.ts.scheduler.model.solution.encoding.PartialSolution;
import hr.unizg.fer.hmo.ts.scheduler.solver.evolutionary.operators.Mutations;
import hr.unizg.fer.hmo.ts.scheduler.solver.random.RandomSamplingScheduler;
import hr.unizg.fer.hmo.ts.util.FileUtils;
import hr.unizg.fer.hmo.ts.util.Visualization;
public class VisualizationDemo {
public static void main(String[] args) throws IOException {
String problemInstanceDirPath = FileUtils.findInAncestor(new File(".").getAbsolutePath(),
"data/problem-instances");
String visualizationDirPath = FileUtils.findInAncestor(new File(".").getAbsolutePath(),
"data/visualization");
DirectoryStream<Path> dirStream = Files
.newDirectoryStream(Paths.get(problemInstanceDirPath));
for (Path problemFilePath : dirStream) {
System.out.println(problemFilePath);
String problemDefinitionString = new String(Files.readAllBytes(problemFilePath));
VerboseProblem verboseProblem = new VerboseProblem(problemDefinitionString);
// System.out.println(verboseProblem);
Problem problem = new Problem(verboseProblem);
RandomSamplingScheduler scheduler = new RandomSamplingScheduler(1);
Solution solution = scheduler.optimize(problem);
// VerboseSolution verboseSolution = new VerboseSolution(verboseProblem,
// solution);
Visualization.pyDisplayHistogram(IntStream.range(0, 4000)
.map(i -> scheduler.optimize(problem).getDuration()).toArray());
String htmlVis = Visualization.convertSolutionToHTML(solution, problem);
String visualizationFilePath = visualizationDirPath + "/viz1.html";
System.out.println(visualizationFilePath);
Files.write(Paths.get(visualizationFilePath), htmlVis.getBytes());
SecretSolutionDecoder ssd = new SecretSolutionDecoder(problem);
MutationOperator<PartialSolution> mut = Mutations.multiSwap(1);
mut.mutate(scheduler._bestPsol);
htmlVis = Visualization.convertSolutionToHTML(ssd.decode(scheduler._bestPsol), problem);
visualizationFilePath = visualizationDirPath + "/viz2.html";
System.out.println(visualizationFilePath);
Files.write(Paths.get(visualizationFilePath), htmlVis.getBytes());
// System.out.println(verboseSolution);
System.out.println(solution.getDuration());
System.out.println(verboseProblem.tests.stream().mapToInt(t -> t.duration).sum());
}
}
}
| UTF-8 | Java | 2,922 | java | VisualizationDemo.java | Java | [] | null | [] | package hr.unizg.fer.hmo.ts.demo;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.IntStream;
import hr.unizg.fer.hmo.ts.optimization.ga.mutation.MutationOperator;
import hr.unizg.fer.hmo.ts.scheduler.model.problem.Problem;
import hr.unizg.fer.hmo.ts.scheduler.model.problem.VerboseProblem;
import hr.unizg.fer.hmo.ts.scheduler.model.solution.Solution;
import hr.unizg.fer.hmo.ts.scheduler.model.solution.decoding.SecretSolutionDecoder;
import hr.unizg.fer.hmo.ts.scheduler.model.solution.encoding.PartialSolution;
import hr.unizg.fer.hmo.ts.scheduler.solver.evolutionary.operators.Mutations;
import hr.unizg.fer.hmo.ts.scheduler.solver.random.RandomSamplingScheduler;
import hr.unizg.fer.hmo.ts.util.FileUtils;
import hr.unizg.fer.hmo.ts.util.Visualization;
public class VisualizationDemo {
public static void main(String[] args) throws IOException {
String problemInstanceDirPath = FileUtils.findInAncestor(new File(".").getAbsolutePath(),
"data/problem-instances");
String visualizationDirPath = FileUtils.findInAncestor(new File(".").getAbsolutePath(),
"data/visualization");
DirectoryStream<Path> dirStream = Files
.newDirectoryStream(Paths.get(problemInstanceDirPath));
for (Path problemFilePath : dirStream) {
System.out.println(problemFilePath);
String problemDefinitionString = new String(Files.readAllBytes(problemFilePath));
VerboseProblem verboseProblem = new VerboseProblem(problemDefinitionString);
// System.out.println(verboseProblem);
Problem problem = new Problem(verboseProblem);
RandomSamplingScheduler scheduler = new RandomSamplingScheduler(1);
Solution solution = scheduler.optimize(problem);
// VerboseSolution verboseSolution = new VerboseSolution(verboseProblem,
// solution);
Visualization.pyDisplayHistogram(IntStream.range(0, 4000)
.map(i -> scheduler.optimize(problem).getDuration()).toArray());
String htmlVis = Visualization.convertSolutionToHTML(solution, problem);
String visualizationFilePath = visualizationDirPath + "/viz1.html";
System.out.println(visualizationFilePath);
Files.write(Paths.get(visualizationFilePath), htmlVis.getBytes());
SecretSolutionDecoder ssd = new SecretSolutionDecoder(problem);
MutationOperator<PartialSolution> mut = Mutations.multiSwap(1);
mut.mutate(scheduler._bestPsol);
htmlVis = Visualization.convertSolutionToHTML(ssd.decode(scheduler._bestPsol), problem);
visualizationFilePath = visualizationDirPath + "/viz2.html";
System.out.println(visualizationFilePath);
Files.write(Paths.get(visualizationFilePath), htmlVis.getBytes());
// System.out.println(verboseSolution);
System.out.println(solution.getDuration());
System.out.println(verboseProblem.tests.stream().mapToInt(t -> t.duration).sum());
}
}
}
| 2,922 | 0.787474 | 0.784394 | 60 | 47.700001 | 26.55328 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.55 | false | false | 9 |
5f92f9e650d7646e12143ec482016f9d4ecb0ebd | 15,848,429,367,525 | 44c4750629391a1dc8adcaad3e3811a181d59059 | /src/main/java/com/scotthensen/portfolio/model/DeleteSymbolRequest.java | e74053206c3acb2ea962319773e967c03d124ae0 | [] | no_license | ScottHensen/portfolio-web | https://github.com/ScottHensen/portfolio-web | d0c8e332a923bec65a437c166d62a8fd5d7e4cb6 | 3d7083da8937990e8018ac3b1f78fc1cc8353e60 | refs/heads/master | 2020-03-21T17:22:49.896000 | 2018-08-30T04:00:43 | 2018-08-30T04:00:43 | 138,828,482 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scotthensen.portfolio.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DeleteSymbolRequest
{
private Integer clientId;
private Integer portfolioId;
private String symbol;
}
| UTF-8 | Java | 327 | java | DeleteSymbolRequest.java | Java | [] | null | [] | package com.scotthensen.portfolio.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DeleteSymbolRequest
{
private Integer clientId;
private Integer portfolioId;
private String symbol;
}
| 327 | 0.828746 | 0.828746 | 17 | 18.235294 | 12.977489 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 9 |
b63cc2e0acbf906acf29b975942b03cfba501fad | 12,232,066,913,259 | 42a6a68321c688ab73ec71562c2733bbcdb83d6e | /src/hwMaze/StudentMTMazeSolver1.java | 73a344331e5e75a34103242d6a9777e972640670 | [] | no_license | anubhav1011/multi-maze | https://github.com/anubhav1011/multi-maze | 0fc2bb15afec431718d3f083e0b2783f8ec0fa9f | ff113a2af55c9765590241fac46b3ea0435b3abe | refs/heads/master | 2020-05-01T01:43:46.463000 | 2019-03-27T02:19:44 | 2019-03-27T02:19:44 | 177,201,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hwMaze;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* This file needs to hold your solver to be tested.
* You can alter the class to extend any class that extends MazeSolver.
* It must have a constructor that takes in a Maze.
* It must have the solve() method that returns the datatype List<Direction>
* which will either be a reference to a list of steps to take or will
* be null if the maze cannot be solved.
*/
public class StudentMTMazeSolver1 extends SkippingMazeSolver {
private final ExecutorService exec;
private final ConcurrentMap<Position, Boolean> seen;
private final Semaphore sem;
final ValueLatch<Move> solution = new ValueLatch<>();
public StudentMTMazeSolver1(Maze maze) {
super(maze);
this.exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
this.seen = new ConcurrentHashMap<>();
this.sem = new Semaphore(Runtime.getRuntime().availableProcessors());
}
public List<Direction> solve() {
// TODO: Implement your code here
Position p = this.maze.getStart();
for (Direction direction : this.maze.getMoves(p)) {
exec.execute(newTask(p.move(direction), direction, null, maze));
}
Move endMove;
try {
endMove = solution.getValue();
LinkedList<Direction> sol = endMove == null ? null : constructSolution(endMove);
return sol;
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected Runnable newTask(Position p, Direction direction, Move prev, Maze maze) {
return new Puzzletask(p, direction, prev, maze);
}
private LinkedList<Direction> constructSolution(Move endMove) {
LinkedList<Direction> sol = new LinkedList<>();
Move current = endMove;
while (current != null && current.to != null) {
sol.addFirst(current.to);
current = current.previous;
}
return sol;
}
class Puzzletask extends Move implements Runnable {
private final Maze maze;
Puzzletask(Position pos, Direction move, Move prev, Maze maze) {
super(pos, move, prev);
this.maze = maze;
}
public void run() {
if (solution.isSet() || seen.containsKey(this.from)) {
return;
}
seen.put(this.from, true);
if (this.maze.getEnd().equals(this.from)) {
//System.out.println("Solution found + " + this.from.toString());
solution.setValue(this);
//sem.release();
return;
}
for (Direction direction : this.maze.getMoves(this.from)) {
//if (sem.tryAcquire()) {
exec.execute(newTask(this.from.move(direction), direction, this, maze));
// if (sem.tryAcquire()) {
// try {
// sem.acquire();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// exec.execute(newTask(this.from.move(direction), direction, this, maze));
//
// } else {
// Puzzletask puzzletask = new Puzzletask(this.from.move(direction), direction, this, maze);
// puzzletask.solveSequentially();
// }
}
//sem.release();
}
public void solveSequentially() {
if (solution.isSet() || seen.containsKey(this.from)) {
return;
}
seen.put(this.from, true);
if (this.maze.getEnd().equals(this.from)) {
//System.out.println("Solution found + " + this.from.toString());
solution.setValue(this);
return;
}
for (Direction direction : this.maze.getMoves(this.from)) {
Puzzletask puzzletask = new Puzzletask(this.from.move(direction), direction, this, maze);
puzzletask.solveSequentially();
}
}
}
}
| UTF-8 | Java | 4,223 | java | StudentMTMazeSolver1.java | Java | [] | null | [] | package hwMaze;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* This file needs to hold your solver to be tested.
* You can alter the class to extend any class that extends MazeSolver.
* It must have a constructor that takes in a Maze.
* It must have the solve() method that returns the datatype List<Direction>
* which will either be a reference to a list of steps to take or will
* be null if the maze cannot be solved.
*/
public class StudentMTMazeSolver1 extends SkippingMazeSolver {
private final ExecutorService exec;
private final ConcurrentMap<Position, Boolean> seen;
private final Semaphore sem;
final ValueLatch<Move> solution = new ValueLatch<>();
public StudentMTMazeSolver1(Maze maze) {
super(maze);
this.exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
this.seen = new ConcurrentHashMap<>();
this.sem = new Semaphore(Runtime.getRuntime().availableProcessors());
}
public List<Direction> solve() {
// TODO: Implement your code here
Position p = this.maze.getStart();
for (Direction direction : this.maze.getMoves(p)) {
exec.execute(newTask(p.move(direction), direction, null, maze));
}
Move endMove;
try {
endMove = solution.getValue();
LinkedList<Direction> sol = endMove == null ? null : constructSolution(endMove);
return sol;
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected Runnable newTask(Position p, Direction direction, Move prev, Maze maze) {
return new Puzzletask(p, direction, prev, maze);
}
private LinkedList<Direction> constructSolution(Move endMove) {
LinkedList<Direction> sol = new LinkedList<>();
Move current = endMove;
while (current != null && current.to != null) {
sol.addFirst(current.to);
current = current.previous;
}
return sol;
}
class Puzzletask extends Move implements Runnable {
private final Maze maze;
Puzzletask(Position pos, Direction move, Move prev, Maze maze) {
super(pos, move, prev);
this.maze = maze;
}
public void run() {
if (solution.isSet() || seen.containsKey(this.from)) {
return;
}
seen.put(this.from, true);
if (this.maze.getEnd().equals(this.from)) {
//System.out.println("Solution found + " + this.from.toString());
solution.setValue(this);
//sem.release();
return;
}
for (Direction direction : this.maze.getMoves(this.from)) {
//if (sem.tryAcquire()) {
exec.execute(newTask(this.from.move(direction), direction, this, maze));
// if (sem.tryAcquire()) {
// try {
// sem.acquire();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// exec.execute(newTask(this.from.move(direction), direction, this, maze));
//
// } else {
// Puzzletask puzzletask = new Puzzletask(this.from.move(direction), direction, this, maze);
// puzzletask.solveSequentially();
// }
}
//sem.release();
}
public void solveSequentially() {
if (solution.isSet() || seen.containsKey(this.from)) {
return;
}
seen.put(this.from, true);
if (this.maze.getEnd().equals(this.from)) {
//System.out.println("Solution found + " + this.from.toString());
solution.setValue(this);
return;
}
for (Direction direction : this.maze.getMoves(this.from)) {
Puzzletask puzzletask = new Puzzletask(this.from.move(direction), direction, this, maze);
puzzletask.solveSequentially();
}
}
}
}
| 4,223 | 0.561923 | 0.561449 | 129 | 31.736435 | 28.076176 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.635659 | false | false | 9 |
02d0270391c9005970f747c8076dbc7215eb5abe | 21,079,699,517,561 | 9eb90397e2752ba700b8b3e5c921e01b1612f019 | /src/br/com/alura/loja/actions/SaveOrderInDatabase.java | 670d4e97a7ac98f6d6900c6e41680b0012fe3c92 | [] | no_license | Gilmardealcantara/java-design-patterns | https://github.com/Gilmardealcantara/java-design-patterns | f17ea64149acf58169d41e72781aefe7da51e3e2 | 3c352d1ca225f4ea32ec5ef20e00cb6f8a4c18cd | refs/heads/main | 2023-02-19T07:43:25.356000 | 2021-01-17T01:33:52 | 2021-01-17T01:34:22 | 326,443,013 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.alura.loja.actions;
import br.com.alura.loja.order.Order;
import br.com.alura.loja.order.action.ActionsAfterOrderGenerate;
public class SaveOrderInDatabase implements ActionsAfterOrderGenerate {
@Override
public void executeAction(Order order){
System.out.println("Salvando pedido no banco de dados !");
}
}
| UTF-8 | Java | 345 | java | SaveOrderInDatabase.java | Java | [] | null | [] | package br.com.alura.loja.actions;
import br.com.alura.loja.order.Order;
import br.com.alura.loja.order.action.ActionsAfterOrderGenerate;
public class SaveOrderInDatabase implements ActionsAfterOrderGenerate {
@Override
public void executeAction(Order order){
System.out.println("Salvando pedido no banco de dados !");
}
}
| 345 | 0.765217 | 0.765217 | 11 | 30.363636 | 26.83374 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 9 |
d3ebff647a7fa44399d22e6cd78bcf03a30afaf7 | 21,079,699,521,326 | 008ba46e540aaa3964f73130b8e7df4d96843f18 | /library/src/org/webpki/crypto/KeyEncryptionAlgorithms.java | cbf3d023ef74e52e41fb4157acfdf01d60782bb8 | [
"Apache-2.0"
] | permissive | cyberphone/openkeystore | https://github.com/cyberphone/openkeystore | 47a749c9705fa45be214cc77e068c71baf7b9191 | 98534d25afcc0b019a0138a4dd9e17b6351b1985 | refs/heads/master | 2023-08-28T07:40:57.185000 | 2023-08-23T19:50:23 | 2023-08-23T19:50:23 | 176,313,656 | 10 | 5 | NOASSERTION | false | 2022-11-30T04:11:02 | 2019-03-18T15:19:06 | 2022-03-10T16:35:45 | 2022-11-30T04:11:01 | 19,739 | 7 | 1 | 0 | Java | false | false | /*
* Copyright 2006-2021 WebPKI.org (http://webpki.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.webpki.crypto;
/**
* JWE and COSE key encryption algorithms.
*
* Note that JOSE and COSE use different KDFs.
*/
public enum KeyEncryptionAlgorithms {
// ECDH
ECDH_ES ("ECDH-ES", -25, false, false, -1),
ECDH_ES_A128KW ("ECDH-ES+A128KW", -29, false, true, 16),
ECDH_ES_A192KW ("ECDH-ES+A192KW", -30, false, true, 24),
ECDH_ES_A256KW ("ECDH-ES+A256KW", -31, false, true, 32),
// RSA
RSA_OAEP ("RSA-OAEP", -40, true, true, -1),
RSA_OAEP_256 ("RSA-OAEP-256", -41, true, true, -1);
String joseId;
int coseId;
boolean rsa;
boolean keyWrap;
int keyEncryptionKeyLength;
KeyEncryptionAlgorithms(String joseId,
int coseId,
boolean rsa,
boolean keyWrap,
int keyEncryptionKeyLength) {
this.joseId = joseId;
this.coseId = coseId;
this.rsa = rsa;
this.keyWrap = keyWrap;
this.keyEncryptionKeyLength = keyEncryptionKeyLength;
}
public boolean isRsa() {
return rsa;
}
public boolean isKeyWrap() {
return keyWrap;
}
public String getJoseAlgorithmId() {
return joseId;
}
public int getCoseAlgorithmId() {
return coseId;
}
public static KeyEncryptionAlgorithms getAlgorithmFromId(String joseAlgorithmId) {
for (KeyEncryptionAlgorithms algorithm : KeyEncryptionAlgorithms.values()) {
if (joseAlgorithmId.equals(algorithm.joseId)) {
return algorithm;
}
}
throw new IllegalArgumentException("Unexpected algorithm: " + joseAlgorithmId);
}
public static KeyEncryptionAlgorithms getAlgorithmFromId(int coseAlgorithmId) {
for (KeyEncryptionAlgorithms algorithm : KeyEncryptionAlgorithms.values()) {
if (coseAlgorithmId == algorithm.coseId) {
return algorithm;
}
}
throw new IllegalArgumentException("Unexpected algorithm: " + coseAlgorithmId);
}
}
| UTF-8 | Java | 2,750 | java | KeyEncryptionAlgorithms.java | Java | [] | null | [] | /*
* Copyright 2006-2021 WebPKI.org (http://webpki.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.webpki.crypto;
/**
* JWE and COSE key encryption algorithms.
*
* Note that JOSE and COSE use different KDFs.
*/
public enum KeyEncryptionAlgorithms {
// ECDH
ECDH_ES ("ECDH-ES", -25, false, false, -1),
ECDH_ES_A128KW ("ECDH-ES+A128KW", -29, false, true, 16),
ECDH_ES_A192KW ("ECDH-ES+A192KW", -30, false, true, 24),
ECDH_ES_A256KW ("ECDH-ES+A256KW", -31, false, true, 32),
// RSA
RSA_OAEP ("RSA-OAEP", -40, true, true, -1),
RSA_OAEP_256 ("RSA-OAEP-256", -41, true, true, -1);
String joseId;
int coseId;
boolean rsa;
boolean keyWrap;
int keyEncryptionKeyLength;
KeyEncryptionAlgorithms(String joseId,
int coseId,
boolean rsa,
boolean keyWrap,
int keyEncryptionKeyLength) {
this.joseId = joseId;
this.coseId = coseId;
this.rsa = rsa;
this.keyWrap = keyWrap;
this.keyEncryptionKeyLength = keyEncryptionKeyLength;
}
public boolean isRsa() {
return rsa;
}
public boolean isKeyWrap() {
return keyWrap;
}
public String getJoseAlgorithmId() {
return joseId;
}
public int getCoseAlgorithmId() {
return coseId;
}
public static KeyEncryptionAlgorithms getAlgorithmFromId(String joseAlgorithmId) {
for (KeyEncryptionAlgorithms algorithm : KeyEncryptionAlgorithms.values()) {
if (joseAlgorithmId.equals(algorithm.joseId)) {
return algorithm;
}
}
throw new IllegalArgumentException("Unexpected algorithm: " + joseAlgorithmId);
}
public static KeyEncryptionAlgorithms getAlgorithmFromId(int coseAlgorithmId) {
for (KeyEncryptionAlgorithms algorithm : KeyEncryptionAlgorithms.values()) {
if (coseAlgorithmId == algorithm.coseId) {
return algorithm;
}
}
throw new IllegalArgumentException("Unexpected algorithm: " + coseAlgorithmId);
}
}
| 2,750 | 0.617091 | 0.596364 | 87 | 30.609196 | 27.150223 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
234989e4be5030638f90b9a04db189ac0a64beca | 21,380,347,200,483 | 4392a71def3cfbe805dba94d81df0ffba6d52357 | /jinterviewback/src/main/java/io/cjf/jinterviewback/constant/ClientExceptionConstant.java | 0231315a62b6180bf4ba1a29acf78c76f4294a34 | [] | no_license | nlpxdc/jinterview1702c | https://github.com/nlpxdc/jinterview1702c | 64b8fc61dccfaf59ade14a74cf4592b987347068 | f22b7f02aa34db4bc065f5f1ea31aaab6e89651b | refs/heads/develop | 2022-07-14T14:46:20.183000 | 2020-01-02T07:40:43 | 2020-01-02T07:40:43 | 224,953,724 | 0 | 0 | null | false | 2022-06-29T17:50:37 | 2019-11-30T03:25:03 | 2020-01-02T07:40:59 | 2022-06-29T17:50:37 | 1,190 | 0 | 0 | 9 | JavaScript | false | false | package io.cjf.jinterviewback.constant;
public class ClientExceptionConstant {
public static final String OPENID_NOT_EXIST_ERRCODE = "0001";
public static final String OPENID_NOT_EXIST_ERRMSG = "openid doesn't exist";
public static final String STUDENT_NOT_ACTIVATE_ERRCODE = "0002";
public static final String STUDENT_NOT_ACTIVATE_ERRMSG = "student not activate";
public static final String MOBILE_NOT_EXIST_ERRCODE = "0003";
public static final String MOBILE_NOT_EXIST_ERRMSG = "mobile not exist";
public static final String CAPTCHA_INVALID_ERRCODE = "0004";
public static final String CAPTCHA_INVALID_ERRMSG = "captcha invalid";
public static final String TOKEN_INVALID_ERRCODE = "0005";
public static final String TOKEN_INVALID_ERRMSG = "token invalid";
public static final String TOKEN_NOT_EXIST_ERRCODE = "0006";
public static final String TOKEN_NOT_EXIST_ERRMSG = "token not exist";
public static final String AUTHCODE_INVALID_ERRCODE = "0007";
public static final String AUTHCODE_INVALID_ERRMSG = "auth code invalid";
public static final String EMail_NOT_EXIST_ERRCODE = "0008";
public static final String EMail_NOT_EXIST_ERRMSG = "email not exist";
public static final String NOT_SUPPORT_STATIC_RESOURCE_ERRCODE = "0009";
public static final String NOT_SUPPORT_STATIC_RESOURCE_ERRMSG = "not support static resource";
public static final String INTERVIEW_NOT_EXIST_ERRCODE = "0010";
public static final String INTERVIEW_NOT_EXIST_ERRMSG = "interview not exist";
public static final String NOT_YOURSELF_INTERVIEW_ERRCODE = "0011";
public static final String NOT_YOURSELF_INTERVIEW_ERRMSG = "not yourself interview";
public static final String NOT_JPEG_FORMAT_ERRCODE = "0012";
public static final String NOT_JPEG_FORMAT_ERRMSG = "not jpeg format";
public static final String PHOTO_EMPTY_ERRCODE = "0013";
public static final String PHOTO_EMPTY_ERRMSG = "photo empty";
public static final String IDCARD_TOO_LARGE_ERRCODE = "0014";
public static final String IDCARD_TOO_LARGE_ERRMSG = "idcard too large, less than 100KB";
public static final String PHOTO_TOO_LARGE_ERRCODE = "0015";
public static final String PHOTO_TOO_LARGE_ERRMSG = "photo too large, less than 1MB";
}
| UTF-8 | Java | 2,299 | java | ClientExceptionConstant.java | Java | [] | null | [] | package io.cjf.jinterviewback.constant;
public class ClientExceptionConstant {
public static final String OPENID_NOT_EXIST_ERRCODE = "0001";
public static final String OPENID_NOT_EXIST_ERRMSG = "openid doesn't exist";
public static final String STUDENT_NOT_ACTIVATE_ERRCODE = "0002";
public static final String STUDENT_NOT_ACTIVATE_ERRMSG = "student not activate";
public static final String MOBILE_NOT_EXIST_ERRCODE = "0003";
public static final String MOBILE_NOT_EXIST_ERRMSG = "mobile not exist";
public static final String CAPTCHA_INVALID_ERRCODE = "0004";
public static final String CAPTCHA_INVALID_ERRMSG = "captcha invalid";
public static final String TOKEN_INVALID_ERRCODE = "0005";
public static final String TOKEN_INVALID_ERRMSG = "token invalid";
public static final String TOKEN_NOT_EXIST_ERRCODE = "0006";
public static final String TOKEN_NOT_EXIST_ERRMSG = "token not exist";
public static final String AUTHCODE_INVALID_ERRCODE = "0007";
public static final String AUTHCODE_INVALID_ERRMSG = "auth code invalid";
public static final String EMail_NOT_EXIST_ERRCODE = "0008";
public static final String EMail_NOT_EXIST_ERRMSG = "email not exist";
public static final String NOT_SUPPORT_STATIC_RESOURCE_ERRCODE = "0009";
public static final String NOT_SUPPORT_STATIC_RESOURCE_ERRMSG = "not support static resource";
public static final String INTERVIEW_NOT_EXIST_ERRCODE = "0010";
public static final String INTERVIEW_NOT_EXIST_ERRMSG = "interview not exist";
public static final String NOT_YOURSELF_INTERVIEW_ERRCODE = "0011";
public static final String NOT_YOURSELF_INTERVIEW_ERRMSG = "not yourself interview";
public static final String NOT_JPEG_FORMAT_ERRCODE = "0012";
public static final String NOT_JPEG_FORMAT_ERRMSG = "not jpeg format";
public static final String PHOTO_EMPTY_ERRCODE = "0013";
public static final String PHOTO_EMPTY_ERRMSG = "photo empty";
public static final String IDCARD_TOO_LARGE_ERRCODE = "0014";
public static final String IDCARD_TOO_LARGE_ERRMSG = "idcard too large, less than 100KB";
public static final String PHOTO_TOO_LARGE_ERRCODE = "0015";
public static final String PHOTO_TOO_LARGE_ERRMSG = "photo too large, less than 1MB";
}
| 2,299 | 0.744672 | 0.716833 | 36 | 62.861111 | 25.111034 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.916667 | false | false | 9 |
f1764986a3953da7e9f3a6975ca3d23129869145 | 17,197,049,070,902 | cf0aaa6f3e8b697e38d866ae0fffd9ff97ea9b20 | /src/main/java/org/synyx/urlaubsverwaltung/mail/MailConfiguration.java | 6178ef75f8022f1d88ccbcec677bb541bf33f2e7 | [
"Apache-2.0"
] | permissive | grafjo/urlaubsverwaltung | https://github.com/grafjo/urlaubsverwaltung | a6b91dff2187a04a8d0798b0a0c4a6ccd1314cc5 | 0c843beefe43a128baba69d41536f454aa338b81 | refs/heads/main | 2023-08-31T05:21:37.631000 | 2023-07-19T10:50:16 | 2023-07-19T18:45:19 | 171,047,044 | 0 | 0 | Apache-2.0 | true | 2023-09-04T21:42:56 | 2019-02-16T20:12:36 | 2022-09-03T14:05:25 | 2023-09-04T21:42:56 | 43,359 | 0 | 0 | 11 | Java | false | false | package org.synyx.urlaubsverwaltung.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import static org.thymeleaf.templatemode.TemplateMode.TEXT;
@Configuration
class MailConfiguration {
private static final String UTF_8 = "UTF-8";
private final ApplicationContext applicationContext;
@Autowired
MailConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
ITemplateEngine emailTemplateEngine() {
final SpringTemplateEngine emailTemplateEngine = new SpringTemplateEngine();
emailTemplateEngine.addTemplateResolver(textTemplateResolver());
emailTemplateEngine.addDialect(new Java8TimeDialect());
emailTemplateEngine.setTemplateEngineMessageSource(emailMessageSource());
return emailTemplateEngine;
}
@Bean
ResourceBundleMessageSource emailMessageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setDefaultEncoding(UTF_8);
messageSource.setBasename("MailMessages");
return messageSource;
}
private SpringResourceTemplateResolver textTemplateResolver() {
final SpringResourceTemplateResolver textEmailTemplateResolver = new SpringResourceTemplateResolver();
textEmailTemplateResolver.setApplicationContext(applicationContext);
textEmailTemplateResolver.setOrder(1);
textEmailTemplateResolver.setPrefix("classpath:/mail/");
textEmailTemplateResolver.setSuffix(".txt");
textEmailTemplateResolver.setTemplateMode(TEXT);
textEmailTemplateResolver.setCharacterEncoding(UTF_8);
textEmailTemplateResolver.setCacheable(false);
return textEmailTemplateResolver;
}
}
| UTF-8 | Java | 2,270 | java | MailConfiguration.java | Java | [] | null | [] | package org.synyx.urlaubsverwaltung.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import static org.thymeleaf.templatemode.TemplateMode.TEXT;
@Configuration
class MailConfiguration {
private static final String UTF_8 = "UTF-8";
private final ApplicationContext applicationContext;
@Autowired
MailConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
ITemplateEngine emailTemplateEngine() {
final SpringTemplateEngine emailTemplateEngine = new SpringTemplateEngine();
emailTemplateEngine.addTemplateResolver(textTemplateResolver());
emailTemplateEngine.addDialect(new Java8TimeDialect());
emailTemplateEngine.setTemplateEngineMessageSource(emailMessageSource());
return emailTemplateEngine;
}
@Bean
ResourceBundleMessageSource emailMessageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setDefaultEncoding(UTF_8);
messageSource.setBasename("MailMessages");
return messageSource;
}
private SpringResourceTemplateResolver textTemplateResolver() {
final SpringResourceTemplateResolver textEmailTemplateResolver = new SpringResourceTemplateResolver();
textEmailTemplateResolver.setApplicationContext(applicationContext);
textEmailTemplateResolver.setOrder(1);
textEmailTemplateResolver.setPrefix("classpath:/mail/");
textEmailTemplateResolver.setSuffix(".txt");
textEmailTemplateResolver.setTemplateMode(TEXT);
textEmailTemplateResolver.setCharacterEncoding(UTF_8);
textEmailTemplateResolver.setCacheable(false);
return textEmailTemplateResolver;
}
}
| 2,270 | 0.789868 | 0.785463 | 55 | 40.272728 | 29.178732 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581818 | false | false | 9 |
e47bf7518915b3157831cd7a5d6320ef8482542f | 17,197,049,070,658 | 81e1d7bf7a6ad5b3849dd0d0dc6ffbd1b5046267 | /dflib/src/test/java/com/nhl/dflib/print/TabularPrinterWorkerTest.java | 9f5a2c14bfb2a30f96723d29c57e17c9e3603b01 | [
"Apache-2.0"
] | permissive | stariy95/dflib | https://github.com/stariy95/dflib | 91e507654bf1e1f42e18f8fa7b25168baeb4aa4f | eb728579d4dfe56561f1723f7485447b52542171 | refs/heads/master | 2020-04-16T19:24:21.696000 | 2019-01-13T15:06:52 | 2019-01-13T18:36:02 | 165,858,071 | 0 | 0 | Apache-2.0 | true | 2019-01-15T13:44:02 | 2019-01-15T13:44:02 | 2019-01-13T18:43:27 | 2019-01-13T18:43:25 | 167 | 0 | 0 | 0 | null | false | null | package com.nhl.dflib.print;
import com.nhl.dflib.DataRow;
import com.nhl.dflib.Index;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
public class TabularPrinterWorkerTest {
private Index columns;
private List<Object[]> rows;
@Before
public void initDataFrameParts() {
this.columns = Index.withNames("col1", "column2");
this.rows = asList(
DataRow.row("one", 1),
DataRow.row("two", 2),
DataRow.row("three", 3),
DataRow.row("four", 4));
}
@Test
public void testAppendFixedWidth() {
assertEquals("a ", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("a", 3).toString());
assertEquals("a ", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("a", 2).toString());
assertEquals("a", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("a", 1).toString());
assertEquals("..", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("abc", 2).toString());
}
@Test
public void testPrint_Full() {
TabularPrinterWorker w = new TabularPrinterWorker(new StringBuilder(), 5, 10);
assertEquals("" +
"col1 column2" + System.lineSeparator() +
"----- -------" + System.lineSeparator() +
"one 1 " + System.lineSeparator() +
"two 2 " + System.lineSeparator() +
"three 3 " + System.lineSeparator() +
"four 4 ", w.print(columns, rows.iterator()).toString());
}
@Test
public void testPrint_TruncateRows() {
TabularPrinterWorker w = new TabularPrinterWorker(new StringBuilder(), 2, 10);
assertEquals("" +
"col1 column2" + System.lineSeparator() +
"---- -------" + System.lineSeparator() +
"one 1 " + System.lineSeparator() +
"two 2 " + System.lineSeparator() +
"...", w.print(columns, rows.iterator()).toString());
}
@Test
public void testPrint_TruncateColumns() {
TabularPrinterWorker w = new TabularPrinterWorker(new StringBuilder(), 5, 4);
assertEquals("" +
"col1 c..2" + System.lineSeparator() +
"---- ----" + System.lineSeparator() +
"one 1 " + System.lineSeparator() +
"two 2 " + System.lineSeparator() +
"t..e 3 " + System.lineSeparator() +
"four 4 ", w.print(columns, rows.iterator()).toString());
}
}
| UTF-8 | Java | 2,719 | java | TabularPrinterWorkerTest.java | Java | [] | null | [] | package com.nhl.dflib.print;
import com.nhl.dflib.DataRow;
import com.nhl.dflib.Index;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
public class TabularPrinterWorkerTest {
private Index columns;
private List<Object[]> rows;
@Before
public void initDataFrameParts() {
this.columns = Index.withNames("col1", "column2");
this.rows = asList(
DataRow.row("one", 1),
DataRow.row("two", 2),
DataRow.row("three", 3),
DataRow.row("four", 4));
}
@Test
public void testAppendFixedWidth() {
assertEquals("a ", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("a", 3).toString());
assertEquals("a ", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("a", 2).toString());
assertEquals("a", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("a", 1).toString());
assertEquals("..", new TabularPrinterWorker(new StringBuilder(), 3, 20).appendFixedWidth("abc", 2).toString());
}
@Test
public void testPrint_Full() {
TabularPrinterWorker w = new TabularPrinterWorker(new StringBuilder(), 5, 10);
assertEquals("" +
"col1 column2" + System.lineSeparator() +
"----- -------" + System.lineSeparator() +
"one 1 " + System.lineSeparator() +
"two 2 " + System.lineSeparator() +
"three 3 " + System.lineSeparator() +
"four 4 ", w.print(columns, rows.iterator()).toString());
}
@Test
public void testPrint_TruncateRows() {
TabularPrinterWorker w = new TabularPrinterWorker(new StringBuilder(), 2, 10);
assertEquals("" +
"col1 column2" + System.lineSeparator() +
"---- -------" + System.lineSeparator() +
"one 1 " + System.lineSeparator() +
"two 2 " + System.lineSeparator() +
"...", w.print(columns, rows.iterator()).toString());
}
@Test
public void testPrint_TruncateColumns() {
TabularPrinterWorker w = new TabularPrinterWorker(new StringBuilder(), 5, 4);
assertEquals("" +
"col1 c..2" + System.lineSeparator() +
"---- ----" + System.lineSeparator() +
"one 1 " + System.lineSeparator() +
"two 2 " + System.lineSeparator() +
"t..e 3 " + System.lineSeparator() +
"four 4 ", w.print(columns, rows.iterator()).toString());
}
}
| 2,719 | 0.559029 | 0.542111 | 73 | 36.246574 | 31.54244 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.794521 | false | false | 9 |
e999371a12c2495b247d55de744929ba104e8eb9 | 23,519,240,919,361 | 3ad99168b8e6b06fe0a562db92b055850ac9f161 | /codevs/src/unitDirector/worker/SearchDirector.java | bfb702b3857ecb48cb8380bad17c72c14e2397ab | [] | no_license | kajiwara009/Sources | https://github.com/kajiwara009/Sources | a15a95efd384ae75cb087b41d5cfcae3e2aceb62 | 3ee15ae4f8d5d9b9607b3cfc54f1072b6bd97ecc | refs/heads/master | 2021-01-10T09:37:20.612000 | 2015-10-28T10:51:39 | 2015-10-28T10:51:39 | 45,105,785 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package unitDirector.worker;
import java.util.List;
import java.util.Random;
import unitDirector.UnitDirector;
import codevs.God;
import data.Direction;
import data.Unit;
import data.UnitType;
import data.Vector;
public class SearchDirector extends UnitDirector {
public static final int SEARCH_VALUE_RANGE = 20;
private static final int MIN_SEARCH_VALUE = 50;
public SearchDirector(God god) {
super(god);
// TODO 自動生成されたコンストラクター・スタブ
}
@Override
public void moveUnits() {
for(Unit u: units){
setOptimalSearchDirection(u);
}
}
public int makeWorker(){
Unit producer = getBestWorkerProducer();
if(producer != null){
producer.setProduce(UnitType.WORKER);
return UnitType.WORKER.getCost();
}else return 0;
}
protected int getViewWiden(Vector pos, Direction dir){
int widen = 0;
int round = UnitType.WORKER.getSight() + 1;
boolean[][] see = god.getSee();
Vector top = pos.plus(dir.getVector().multi( round));
if(top.isOnField()){
if(!see[top.getX()][top.getY()]) widen++;
}else{
//壁までの距離が小さすぎるときは無駄にそっちに行かない
return 0;
}
for(int i = 1; i < round; i++){
Vector standard = pos.plus(dir.getVector().multi(i));
Vector addPoint = dir.getClockWise().getVector().multi(round - i);
Vector point1 = standard.plus(addPoint);
Vector point2 = standard.minus(addPoint);
if(point1.isOnField() && !see[point1.getX()][point1.getY()]) widen++;
if(point2.isOnField() && !see[point2.getX()][point2.getY()]) widen++;
}
return widen;
}
protected int getSearchValue(Vector pos, Direction dir){
int value = 0;
boolean[][] see = god.getSee();
int microSVR = SEARCH_VALUE_RANGE / 2;
int nearWorkerRange = SEARCH_VALUE_RANGE * 3 / 8;
Vector middlePoint = pos.plus(dir.getVector().multi(microSVR));
Vector nearJudge = pos.plus(dir.getVector().multi(nearWorkerRange));
/*
* もし探索方向10マスにワーカーが居た場合は,そいつが探索するだろうから探索の価値がないと考える
*/
for(Unit worker: god.getUnits(UnitType.WORKER)){
if(nearJudge.getMhtDist(worker.point()) < nearWorkerRange){
if(!(worker.getUnitDirector() instanceof ResourceCollectDirector)) return 0;
}
}
/*
* そっち方向にワーカーがいなかった場合
*/
int startX = Math.max(middlePoint.getX() - microSVR, 0);
int endX = Math.min(middlePoint.getX() + microSVR, god.MAP_END);
for(int x = startX; x <= endX; x++){
int yRange = microSVR - Math.abs(x - middlePoint.getX());
int startY = Math.max(middlePoint.getY() - yRange, 0);
int endY = Math.min(middlePoint.getY() + yRange, god.MAP_END);
for(int y = startY; y <= endY; y++){
if(see[x][y]){
continue;
}
value += getMicroValue(pos, new Vector(x, y));
}
}
return value;
}
private int getMicroValue(Vector v1, Vector v2){
int dist = v1.getMhtDist(v2);
int microValue = 0;
if(dist <= SEARCH_VALUE_RANGE / 4){
microValue = 4;
}else if(dist <= SEARCH_VALUE_RANGE / 4 * 2){
microValue = 3;
}else if(dist <= SEARCH_VALUE_RANGE / 4 * 3){
microValue = 2;
}else if(dist <= SEARCH_VALUE_RANGE / 4 * 4){
microValue = 1;
}
return microValue;
}
protected Unit getBestWorkerProducer(){
int maxValue = MIN_SEARCH_VALUE;
Unit bestProducer = null;
for(Unit u: god.getUnits(UnitType.getProducableUnitTypes(UnitType.WORKER))){
if(u.isProducing()) continue;
for(Unit searcher: units){
if(u.point().equals(searcher.point())){
continue;
}
}
for(Direction dir: Direction.values()){
int value = getSearchValue(u.point(), dir);
if(maxValue < value){
bestProducer = u;
maxValue = value;
}
}
}
// System.err.println(maxValue);
return bestProducer;
}
protected void setOptimalSearchDirection(Unit u){
Direction dir = null;
//一歩で視野が最も広がる方向
int maxWiden = 0;
for(Direction d: Direction.values()){
int widen = getViewWiden(u.point(), d);
if(widen > maxWiden){
dir = d;
maxWiden = widen;
}
}
//一歩で視野の広がりがなかった場合
if(dir == null){
int maxValue = Integer.MIN_VALUE;
for (Direction d : Direction.values()) {
int value = getSearchValue(u.point(), d);
if (maxValue < value) {
dir = d;
maxValue = value;
}
}
if(maxValue == 0){
Direction[] dirs = {Direction.DOWN, Direction.RIGHT};
dir = dirs[new Random().nextInt(dirs.length)];
}
}
u.setDir(dir);
}
}
| UTF-8 | Java | 4,560 | java | SearchDirector.java | Java | [] | null | [] | package unitDirector.worker;
import java.util.List;
import java.util.Random;
import unitDirector.UnitDirector;
import codevs.God;
import data.Direction;
import data.Unit;
import data.UnitType;
import data.Vector;
public class SearchDirector extends UnitDirector {
public static final int SEARCH_VALUE_RANGE = 20;
private static final int MIN_SEARCH_VALUE = 50;
public SearchDirector(God god) {
super(god);
// TODO 自動生成されたコンストラクター・スタブ
}
@Override
public void moveUnits() {
for(Unit u: units){
setOptimalSearchDirection(u);
}
}
public int makeWorker(){
Unit producer = getBestWorkerProducer();
if(producer != null){
producer.setProduce(UnitType.WORKER);
return UnitType.WORKER.getCost();
}else return 0;
}
protected int getViewWiden(Vector pos, Direction dir){
int widen = 0;
int round = UnitType.WORKER.getSight() + 1;
boolean[][] see = god.getSee();
Vector top = pos.plus(dir.getVector().multi( round));
if(top.isOnField()){
if(!see[top.getX()][top.getY()]) widen++;
}else{
//壁までの距離が小さすぎるときは無駄にそっちに行かない
return 0;
}
for(int i = 1; i < round; i++){
Vector standard = pos.plus(dir.getVector().multi(i));
Vector addPoint = dir.getClockWise().getVector().multi(round - i);
Vector point1 = standard.plus(addPoint);
Vector point2 = standard.minus(addPoint);
if(point1.isOnField() && !see[point1.getX()][point1.getY()]) widen++;
if(point2.isOnField() && !see[point2.getX()][point2.getY()]) widen++;
}
return widen;
}
protected int getSearchValue(Vector pos, Direction dir){
int value = 0;
boolean[][] see = god.getSee();
int microSVR = SEARCH_VALUE_RANGE / 2;
int nearWorkerRange = SEARCH_VALUE_RANGE * 3 / 8;
Vector middlePoint = pos.plus(dir.getVector().multi(microSVR));
Vector nearJudge = pos.plus(dir.getVector().multi(nearWorkerRange));
/*
* もし探索方向10マスにワーカーが居た場合は,そいつが探索するだろうから探索の価値がないと考える
*/
for(Unit worker: god.getUnits(UnitType.WORKER)){
if(nearJudge.getMhtDist(worker.point()) < nearWorkerRange){
if(!(worker.getUnitDirector() instanceof ResourceCollectDirector)) return 0;
}
}
/*
* そっち方向にワーカーがいなかった場合
*/
int startX = Math.max(middlePoint.getX() - microSVR, 0);
int endX = Math.min(middlePoint.getX() + microSVR, god.MAP_END);
for(int x = startX; x <= endX; x++){
int yRange = microSVR - Math.abs(x - middlePoint.getX());
int startY = Math.max(middlePoint.getY() - yRange, 0);
int endY = Math.min(middlePoint.getY() + yRange, god.MAP_END);
for(int y = startY; y <= endY; y++){
if(see[x][y]){
continue;
}
value += getMicroValue(pos, new Vector(x, y));
}
}
return value;
}
private int getMicroValue(Vector v1, Vector v2){
int dist = v1.getMhtDist(v2);
int microValue = 0;
if(dist <= SEARCH_VALUE_RANGE / 4){
microValue = 4;
}else if(dist <= SEARCH_VALUE_RANGE / 4 * 2){
microValue = 3;
}else if(dist <= SEARCH_VALUE_RANGE / 4 * 3){
microValue = 2;
}else if(dist <= SEARCH_VALUE_RANGE / 4 * 4){
microValue = 1;
}
return microValue;
}
protected Unit getBestWorkerProducer(){
int maxValue = MIN_SEARCH_VALUE;
Unit bestProducer = null;
for(Unit u: god.getUnits(UnitType.getProducableUnitTypes(UnitType.WORKER))){
if(u.isProducing()) continue;
for(Unit searcher: units){
if(u.point().equals(searcher.point())){
continue;
}
}
for(Direction dir: Direction.values()){
int value = getSearchValue(u.point(), dir);
if(maxValue < value){
bestProducer = u;
maxValue = value;
}
}
}
// System.err.println(maxValue);
return bestProducer;
}
protected void setOptimalSearchDirection(Unit u){
Direction dir = null;
//一歩で視野が最も広がる方向
int maxWiden = 0;
for(Direction d: Direction.values()){
int widen = getViewWiden(u.point(), d);
if(widen > maxWiden){
dir = d;
maxWiden = widen;
}
}
//一歩で視野の広がりがなかった場合
if(dir == null){
int maxValue = Integer.MIN_VALUE;
for (Direction d : Direction.values()) {
int value = getSearchValue(u.point(), d);
if (maxValue < value) {
dir = d;
maxValue = value;
}
}
if(maxValue == 0){
Direction[] dirs = {Direction.DOWN, Direction.RIGHT};
dir = dirs[new Random().nextInt(dirs.length)];
}
}
u.setDir(dir);
}
}
| 4,560 | 0.654456 | 0.64419 | 164 | 25.134146 | 20.739243 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.713415 | false | false | 9 |
a2ab7d4d877d7a45ecec12cde9b93eea10ddfa2d | 26,938,034,949,244 | dfbc143422bb1aa5a9f34adf849a927e90f70f7b | /Contoh Project/video walp/com/google/android/gms/internal/ads/awo.java | a7b88c2d0e9501a0973051bff648d2e205fda208 | [] | no_license | IrfanRZ44/Set-Wallpaper | https://github.com/IrfanRZ44/Set-Wallpaper | 82a656acbf99bc94010e4f74383a4269e312a6f6 | 046b89cab1de482a9240f760e8bcfce2b24d6622 | refs/heads/master | 2020-05-18T11:18:14.749000 | 2019-05-01T04:17:54 | 2019-05-01T04:17:54 | 184,367,300 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.internal.ads;
import android.content.Context;
import android.os.IBinder;
import android.os.IInterface;
import android.os.RemoteException;
import android.widget.FrameLayout;
import com.google.android.gms.a.a;
import com.google.android.gms.a.b;
import com.google.android.gms.a.c;
import com.google.android.gms.a.c.a;
@cm
public final class awo
extends c<auv>
{
public awo()
{
super("com.google.android.gms.ads.NativeAdViewDelegateCreatorImpl");
}
public final aus a(Context paramContext, FrameLayout paramFrameLayout1, FrameLayout paramFrameLayout2)
{
try
{
a locala1 = b.a(paramContext);
a locala2 = b.a(paramFrameLayout1);
a locala3 = b.a(paramFrameLayout2);
IBinder localIBinder = ((auv)a(paramContext)).a(locala1, locala2, locala3, 12451000);
if (localIBinder == null) {
return null;
}
IInterface localIInterface = localIBinder.queryLocalInterface("com.google.android.gms.ads.internal.formats.client.INativeAdViewDelegate");
if ((localIInterface instanceof aus)) {
return (aus)localIInterface;
}
auu localauu = new auu(localIBinder);
return localauu;
}
catch (RemoteException localRemoteException)
{
mk.c("Could not create remote NativeAdViewDelegate.", localRemoteException);
return null;
}
catch (c.a locala)
{
label89:
break label89;
}
}
}
/* Location: C:\Users\IrfanRZ\Desktop\video walp\classes_dex2jar.jar
* Qualified Name: com.google.android.gms.internal.ads.awo
* JD-Core Version: 0.7.0.1
*/ | UTF-8 | Java | 1,679 | java | awo.java | Java | [
{
"context": " }\r\n }\r\n}\r\n\r\n\r\r\n/* Location: C:\\Users\\IrfanRZ\\Desktop\\video walp\\classes_dex2jar.jar\r\r\n * Quali",
"end": 1536,
"score": 0.9756555557250977,
"start": 1529,
"tag": "USERNAME",
"value": "IrfanRZ"
}
] | null | [] | package com.google.android.gms.internal.ads;
import android.content.Context;
import android.os.IBinder;
import android.os.IInterface;
import android.os.RemoteException;
import android.widget.FrameLayout;
import com.google.android.gms.a.a;
import com.google.android.gms.a.b;
import com.google.android.gms.a.c;
import com.google.android.gms.a.c.a;
@cm
public final class awo
extends c<auv>
{
public awo()
{
super("com.google.android.gms.ads.NativeAdViewDelegateCreatorImpl");
}
public final aus a(Context paramContext, FrameLayout paramFrameLayout1, FrameLayout paramFrameLayout2)
{
try
{
a locala1 = b.a(paramContext);
a locala2 = b.a(paramFrameLayout1);
a locala3 = b.a(paramFrameLayout2);
IBinder localIBinder = ((auv)a(paramContext)).a(locala1, locala2, locala3, 12451000);
if (localIBinder == null) {
return null;
}
IInterface localIInterface = localIBinder.queryLocalInterface("com.google.android.gms.ads.internal.formats.client.INativeAdViewDelegate");
if ((localIInterface instanceof aus)) {
return (aus)localIInterface;
}
auu localauu = new auu(localIBinder);
return localauu;
}
catch (RemoteException localRemoteException)
{
mk.c("Could not create remote NativeAdViewDelegate.", localRemoteException);
return null;
}
catch (c.a locala)
{
label89:
break label89;
}
}
}
/* Location: C:\Users\IrfanRZ\Desktop\video walp\classes_dex2jar.jar
* Qualified Name: com.google.android.gms.internal.ads.awo
* JD-Core Version: 0.7.0.1
*/ | 1,679 | 0.667064 | 0.650983 | 61 | 25.622952 | 28.861549 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47541 | false | false | 9 |
e6a04ad9429dbd2af17b0d6b4969163e123ab749 | 31,018,253,867,458 | 829f6448b926689c133d96e6e7c155d2520d6e21 | /AlgoBio_IntelliJ/src/Week_0/Main.java | 6d253914d7ca6bce2349bb7aa1238d19d09ed804 | [] | no_license | RollerVincent/AlgoBioRepo | https://github.com/RollerVincent/AlgoBioRepo | 410f857fa5091e77e32a54b5faf2cf2808ad41d5 | ee4642b9ff29567c000314b34f9e48bf213b198d | refs/heads/master | 2020-03-12T05:38:18.962000 | 2018-04-21T11:35:53 | 2018-04-21T11:35:53 | 130,467,695 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Week_0;
import org.apache.commons.cli.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
/* Beim packen der Jars können wir hier die Aufgabennummer angeben und dann in der main methode mit
* der Fallunterscheidung die jeweiligen passenden Algorithmen ausführen. */
static int packagingIndex = 1;
public static void main(String[] args) {
ArrayList<Integer> inputSequence = new ArrayList<Integer>(); // enthält die eingelesenen Zahlen
SequenceAlgorithm currentAlgorithm = null; // führt je nach Flag die richtige Implementation aus
String outputPath = null; // Pfad zur output Datei
List<int[]> results = null; // Liste der gefundenen MSS
Options options = new Options();
Option input = new Option("i", true, "input file");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", true, "output file");
output.setRequired(true);
options.addOption(output);
options.addOption("n", false, "naive algorithm");
options.addOption("l", false, "linear algorithm");
options.addOption("d", false, "dynamic algorithm");
options.addOption("dc", false, "divide and conquer algorithm");
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("Main", options);
System.exit(1);
return;
}
if(!(cmd.hasOption("n")|cmd.hasOption("l")|cmd.hasOption("d")|cmd.hasOption("dc"))){
System.out.println("Choose an algorithm flag ([-n|-l|-d|-dc])");
formatter.printHelp("Main", options);
System.exit(1);
return;
}
outputPath = cmd.getOptionValue("o");
try(BufferedReader br = new BufferedReader(new FileReader(cmd.getOptionValue("i")))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if(!line.startsWith("#")) {
for (String s : line.split("\t")) {
inputSequence.add(Integer.parseInt(s));
}
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(cmd.hasOption("n")){
currentAlgorithm = new Naive();
}else if(cmd.hasOption("dc")){
currentAlgorithm = new DivideAndConquer();
}else if(cmd.hasOption("d")){
currentAlgorithm = new Dynamic();
}else if(cmd.hasOption("l")){
currentAlgorithm = new Linear();
}
Integer[] inputArray = inputSequence.toArray(new Integer[inputSequence.size()]);
/** Hier ist die Fallunterscheidung für die jeweiligen Jars */
if (packagingIndex==1){
results = currentAlgorithm.MSS(inputArray,true);
}else if(packagingIndex==2){
results = currentAlgorithm.MSS(inputArray,false);
}
try {
PrintWriter writer = new PrintWriter(outputPath, "UTF-8");
for (int i = 0; i < results.size(); i++) {
writer.println(results.get(i)[0]+"\t"+results.get(i)[1]+"\t"+results.get(i)[2]);
}
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 3,846 | java | Main.java | Java | [] | null | [] | package Week_0;
import org.apache.commons.cli.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
/* Beim packen der Jars können wir hier die Aufgabennummer angeben und dann in der main methode mit
* der Fallunterscheidung die jeweiligen passenden Algorithmen ausführen. */
static int packagingIndex = 1;
public static void main(String[] args) {
ArrayList<Integer> inputSequence = new ArrayList<Integer>(); // enthält die eingelesenen Zahlen
SequenceAlgorithm currentAlgorithm = null; // führt je nach Flag die richtige Implementation aus
String outputPath = null; // Pfad zur output Datei
List<int[]> results = null; // Liste der gefundenen MSS
Options options = new Options();
Option input = new Option("i", true, "input file");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", true, "output file");
output.setRequired(true);
options.addOption(output);
options.addOption("n", false, "naive algorithm");
options.addOption("l", false, "linear algorithm");
options.addOption("d", false, "dynamic algorithm");
options.addOption("dc", false, "divide and conquer algorithm");
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("Main", options);
System.exit(1);
return;
}
if(!(cmd.hasOption("n")|cmd.hasOption("l")|cmd.hasOption("d")|cmd.hasOption("dc"))){
System.out.println("Choose an algorithm flag ([-n|-l|-d|-dc])");
formatter.printHelp("Main", options);
System.exit(1);
return;
}
outputPath = cmd.getOptionValue("o");
try(BufferedReader br = new BufferedReader(new FileReader(cmd.getOptionValue("i")))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if(!line.startsWith("#")) {
for (String s : line.split("\t")) {
inputSequence.add(Integer.parseInt(s));
}
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(cmd.hasOption("n")){
currentAlgorithm = new Naive();
}else if(cmd.hasOption("dc")){
currentAlgorithm = new DivideAndConquer();
}else if(cmd.hasOption("d")){
currentAlgorithm = new Dynamic();
}else if(cmd.hasOption("l")){
currentAlgorithm = new Linear();
}
Integer[] inputArray = inputSequence.toArray(new Integer[inputSequence.size()]);
/** Hier ist die Fallunterscheidung für die jeweiligen Jars */
if (packagingIndex==1){
results = currentAlgorithm.MSS(inputArray,true);
}else if(packagingIndex==2){
results = currentAlgorithm.MSS(inputArray,false);
}
try {
PrintWriter writer = new PrintWriter(outputPath, "UTF-8");
for (int i = 0; i < results.size(); i++) {
writer.println(results.get(i)[0]+"\t"+results.get(i)[1]+"\t"+results.get(i)[2]);
}
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
| 3,846 | 0.568081 | 0.565217 | 125 | 29.728001 | 27.998394 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.624 | false | false | 9 |
a0b83b51cac11bd0221e48a8502c8181de532026 | 31,018,253,866,224 | 6a7250bec210f70c66351fb6ed07860ad990eb92 | /workhistory/workhistory-service/src/main/java/com/karma/workhistory/service/CandidateService.java | e54907628565a7965542c5520070f3eb17986569 | [] | no_license | mathrupradeep/work-history | https://github.com/mathrupradeep/work-history | e4df281954f4f5bfccf10f054406d4c699739704 | 489cc15737d17e44e9868e0ed1bd0a66d8b4309c | refs/heads/master | 2020-04-15T14:29:49.208000 | 2016-08-17T15:11:06 | 2016-08-17T15:11:06 | 52,575,406 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.karma.workhistory.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.karma.workhistory.model.RequestQueue;
import com.karma.workhistory.model.User;
import com.karma.workhistory.service.util.RandomPasswordGenerator;
import com.karma.workhistory.service.util.UserType;
@Service("candidateService")
public class CandidateService{
@Autowired
UserService userService;
@Autowired
RequestQueueService requestQueueService;
public String addCandidate(User candidate) {
candidate.setPassword(RandomPasswordGenerator.getRandomPassword(9));
candidate.setUserType(UserType.valueOf("Candidate").toString());
return userService.addUser(candidate);
}
public String addCandidateDetails(User candidate) {
return userService.updateUserDetails(candidate);
}
public String addCandidateEmploymentDetails(RequestQueue candidateEmpDetails) {
return requestQueueService.addCandidateEmploymentDetails(candidateEmpDetails);
}
}
| UTF-8 | Java | 1,031 | java | CandidateService.java | Java | [] | null | [] | package com.karma.workhistory.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.karma.workhistory.model.RequestQueue;
import com.karma.workhistory.model.User;
import com.karma.workhistory.service.util.RandomPasswordGenerator;
import com.karma.workhistory.service.util.UserType;
@Service("candidateService")
public class CandidateService{
@Autowired
UserService userService;
@Autowired
RequestQueueService requestQueueService;
public String addCandidate(User candidate) {
candidate.setPassword(RandomPasswordGenerator.getRandomPassword(9));
candidate.setUserType(UserType.valueOf("Candidate").toString());
return userService.addUser(candidate);
}
public String addCandidateDetails(User candidate) {
return userService.updateUserDetails(candidate);
}
public String addCandidateEmploymentDetails(RequestQueue candidateEmpDetails) {
return requestQueueService.addCandidateEmploymentDetails(candidateEmpDetails);
}
}
| 1,031 | 0.825412 | 0.824442 | 35 | 28.457144 | 27.027332 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
9326bf429b9db2aff5137d7a3ba05b1983a58823 | 2,156,073,609,454 | bcc3e509fc1fe752f017cb46a4b51d7e26de2955 | /FileServerImpl.java | 783b1169120f96b6d4f0735bf8cdd93b491179b4 | [] | no_license | DrishtiParchani/Distributed-File-System-using-Java-RMI | https://github.com/DrishtiParchani/Distributed-File-System-using-Java-RMI | 44a5bc616aade7148bbfd768b363ff03fc997695 | 582ca6fc8d8b80cb77e4639146e8c404bc85fda9 | refs/heads/main | 2023-03-28T22:11:39.410000 | 2021-04-07T09:14:58 | 2021-04-07T09:14:58 | 355,480,245 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.rmi.*;
import java.rmi.server.*;
import java.io.*;
import java.util.*;
public class FileServerImpl extends UnicastRemoteObject
implements FileServer {
static String folderPathOnTheServer;
public FileServerImpl() throws RemoteException {
super();
}
/**
* Accept input from the user and initialize the path on the server.
*/
public static void initialiazeFolderPathOnTheServer(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the folder path on the server to persist the files");
String pathEnteredBytheUser = scanner.nextLine();
try {
folderPathOnTheServer = Paths.get(pathEnteredBytheUser).toString();
File chekifValidDirectory = new File(folderPathOnTheServer);
boolean isValidDirectory = false;
while (!isValidDirectory){
if(!chekifValidDirectory.isDirectory()) {
System.out.println("Please enter a valid directory Path");
folderPathOnTheServer = scanner.nextLine();
chekifValidDirectory = new File(folderPathOnTheServer);
}else {
isValidDirectory = true;
}
}
System.out.println("Folder Path set successfully let's start performing operations.");
}catch (InvalidPathException | NullPointerException e){
System.out.println("java.nio.file.InvalidPathException or " +
"java.lang.NullPointerException occurred while initiating the directory"+e.getMessage());
System.out.println("Please enter correct location exiting the application.");
System.exit(0);
}
}
public synchronized FileInfo downloadFile(String filename) throws RemoteException {
System.out.println("downloading file");
BufferedInputStream fileInStream = null;
try {
File fileToBeDownloaded = new File(folderPathOnTheServer + File.separatorChar + filename);
if (fileToBeDownloaded != null && fileToBeDownloaded.exists()) {
FileInfo downloadFileInfo = new FileOp();
String fileName = fileToBeDownloaded.getName();
byte[] fileContent = new byte[(int)fileToBeDownloaded.length()];
fileInStream = new BufferedInputStream(new FileInputStream(fileToBeDownloaded));
if(fileInStream != null) {
fileInStream.read(fileContent);
downloadFileInfo.setInfo(fileName,fileContent);
return downloadFileInfo;
}
}
}catch (IOException e){
System.out.println("java.io.IoException occurred while reading" +
" content of the file for download"+ e.getMessage());
e.printStackTrace();
}finally {
if (fileInStream != null){
try {
fileInStream.close();
} catch (IOException e) {
System.out.println("java.io.IoException while closing the stream in downloadfile"+e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
public synchronized boolean uploadFile(FileInfo fileif) throws RemoteException{
System.out.println("putting file");
File newFileTobeUpdatedIntheServer = new File(folderPathOnTheServer+File.separatorChar+fileif.getName());
if (newFileTobeUpdatedIntheServer != null){
try {
newFileTobeUpdatedIntheServer.createNewFile();
if(newFileTobeUpdatedIntheServer.canWrite()){
FileOutputStream fileOutputStream = new FileOutputStream(newFileTobeUpdatedIntheServer);
fileOutputStream.write(fileif.getContent());
fileOutputStream.close();
System.out.println("File created successfull");
return true;
}
} catch (IOException e) {
System.out.println("java.io.IOException while uploading file"+e.getMessage());
e.printStackTrace();
return false;
}
}
return false;
}
public synchronized boolean RenameFile(String previousFileName,String updatedFileName) throws RemoteException{
System.out.println("Renaming file");
//File to be renamed.
File fileToBeRenamed = new File(folderPathOnTheServer+File.separatorChar+previousFileName);
//New file name.
File newfFileName = new File(folderPathOnTheServer+File.separatorChar+updatedFileName);
if(fileToBeRenamed != null){
fileToBeRenamed.renameTo(newfFileName);
}
return false;
}
public synchronized boolean DeleteFile(String fileName) throws RemoteException{
System.out.println("DELETING file");
File fileToBeDeleted = new File(folderPathOnTheServer+File.separatorChar+fileName);
if(fileToBeDeleted.exists()){
return fileToBeDeleted.delete();
}
return false;
}
}
| UTF-8 | Java | 4,386 | java | FileServerImpl.java | Java | [] | null | [] |
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.rmi.*;
import java.rmi.server.*;
import java.io.*;
import java.util.*;
public class FileServerImpl extends UnicastRemoteObject
implements FileServer {
static String folderPathOnTheServer;
public FileServerImpl() throws RemoteException {
super();
}
/**
* Accept input from the user and initialize the path on the server.
*/
public static void initialiazeFolderPathOnTheServer(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the folder path on the server to persist the files");
String pathEnteredBytheUser = scanner.nextLine();
try {
folderPathOnTheServer = Paths.get(pathEnteredBytheUser).toString();
File chekifValidDirectory = new File(folderPathOnTheServer);
boolean isValidDirectory = false;
while (!isValidDirectory){
if(!chekifValidDirectory.isDirectory()) {
System.out.println("Please enter a valid directory Path");
folderPathOnTheServer = scanner.nextLine();
chekifValidDirectory = new File(folderPathOnTheServer);
}else {
isValidDirectory = true;
}
}
System.out.println("Folder Path set successfully let's start performing operations.");
}catch (InvalidPathException | NullPointerException e){
System.out.println("java.nio.file.InvalidPathException or " +
"java.lang.NullPointerException occurred while initiating the directory"+e.getMessage());
System.out.println("Please enter correct location exiting the application.");
System.exit(0);
}
}
public synchronized FileInfo downloadFile(String filename) throws RemoteException {
System.out.println("downloading file");
BufferedInputStream fileInStream = null;
try {
File fileToBeDownloaded = new File(folderPathOnTheServer + File.separatorChar + filename);
if (fileToBeDownloaded != null && fileToBeDownloaded.exists()) {
FileInfo downloadFileInfo = new FileOp();
String fileName = fileToBeDownloaded.getName();
byte[] fileContent = new byte[(int)fileToBeDownloaded.length()];
fileInStream = new BufferedInputStream(new FileInputStream(fileToBeDownloaded));
if(fileInStream != null) {
fileInStream.read(fileContent);
downloadFileInfo.setInfo(fileName,fileContent);
return downloadFileInfo;
}
}
}catch (IOException e){
System.out.println("java.io.IoException occurred while reading" +
" content of the file for download"+ e.getMessage());
e.printStackTrace();
}finally {
if (fileInStream != null){
try {
fileInStream.close();
} catch (IOException e) {
System.out.println("java.io.IoException while closing the stream in downloadfile"+e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
public synchronized boolean uploadFile(FileInfo fileif) throws RemoteException{
System.out.println("putting file");
File newFileTobeUpdatedIntheServer = new File(folderPathOnTheServer+File.separatorChar+fileif.getName());
if (newFileTobeUpdatedIntheServer != null){
try {
newFileTobeUpdatedIntheServer.createNewFile();
if(newFileTobeUpdatedIntheServer.canWrite()){
FileOutputStream fileOutputStream = new FileOutputStream(newFileTobeUpdatedIntheServer);
fileOutputStream.write(fileif.getContent());
fileOutputStream.close();
System.out.println("File created successfull");
return true;
}
} catch (IOException e) {
System.out.println("java.io.IOException while uploading file"+e.getMessage());
e.printStackTrace();
return false;
}
}
return false;
}
public synchronized boolean RenameFile(String previousFileName,String updatedFileName) throws RemoteException{
System.out.println("Renaming file");
//File to be renamed.
File fileToBeRenamed = new File(folderPathOnTheServer+File.separatorChar+previousFileName);
//New file name.
File newfFileName = new File(folderPathOnTheServer+File.separatorChar+updatedFileName);
if(fileToBeRenamed != null){
fileToBeRenamed.renameTo(newfFileName);
}
return false;
}
public synchronized boolean DeleteFile(String fileName) throws RemoteException{
System.out.println("DELETING file");
File fileToBeDeleted = new File(folderPathOnTheServer+File.separatorChar+fileName);
if(fileToBeDeleted.exists()){
return fileToBeDeleted.delete();
}
return false;
}
}
| 4,386 | 0.73803 | 0.737802 | 120 | 35.525002 | 29.806868 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.933333 | false | false | 9 |
08411a7b7042d80ce11a578eaede3617a29c668b | 2,087,354,122,095 | 970e664332e6b2ed9ffa41fbf8eb615f4cca71c2 | /denpasar-core/src/main/java/com/plumeria/denpasar/util/GenOrderCode.java | ddb1062c634449530b20e8333265d40a85611287 | [] | no_license | four0one/denpasar | https://github.com/four0one/denpasar | 420b8760a8e1a1488c787d308c2f76f94fdc87e3 | 3855d1a5cd311a33cbd0ce9966a23851709f2e5c | refs/heads/master | 2021-01-13T14:48:02.343000 | 2017-01-22T10:26:37 | 2017-01-22T10:26:37 | 76,533,079 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.plumeria.denpasar.util;
import java.util.Date;
import java.util.Random;
/**
* 生成唯一ID
*
* @author Administrator
*
*/
public class GenOrderCode {
private static Date date = new Date();
private static StringBuilder buf = new StringBuilder();
public static synchronized String next() {
buf.delete(0, buf.length());
date.setTime(System.currentTimeMillis());
String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, genSixNum());
return str;
}
/**
* 20位订单号
* @Title: nextMill
* @Description:
* @param @return
* @return String 返回类型
* @throws
*/
public static synchronized String nextMill() {
String millTime=String.valueOf(System.currentTimeMillis());
// System.out.println(millTime);
int length=millTime.length()-10;
String millTimeTemp=millTime.substring(length, millTime.length());
// System.out.println(millTimeTemp);
Random random = new Random();
int a=random.nextInt(10);
int b=random.nextInt(10);
int c=random.nextInt(10);
String str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c)+millTimeTemp+String.valueOf(genSixNum());
return str;
}
/**
* 随机生成6位数
*
* @return
*/
private static int genSixNum() {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Random rand = new Random();
for (int i = 9; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = array[index];
array[index] = array[i - 1];
array[i - 1] = tmp;
}
int result = 0;
for (int i = 0; i < 6; i++)
result = result * 10 + array[i];
return result;
}
public static void main(String[] args) {
System.out.println(GenOrderCode.next());
}
}
| UTF-8 | Java | 1,666 | java | GenOrderCode.java | Java | [
{
"context": "ort java.util.Random;\n\n/**\n * 生成唯一ID\n *\n * @author Administrator\n *\n */\npublic class GenOrderCode {\n\n\tprivate stat",
"end": 127,
"score": 0.6334648132324219,
"start": 114,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.plumeria.denpasar.util;
import java.util.Date;
import java.util.Random;
/**
* 生成唯一ID
*
* @author Administrator
*
*/
public class GenOrderCode {
private static Date date = new Date();
private static StringBuilder buf = new StringBuilder();
public static synchronized String next() {
buf.delete(0, buf.length());
date.setTime(System.currentTimeMillis());
String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, genSixNum());
return str;
}
/**
* 20位订单号
* @Title: nextMill
* @Description:
* @param @return
* @return String 返回类型
* @throws
*/
public static synchronized String nextMill() {
String millTime=String.valueOf(System.currentTimeMillis());
// System.out.println(millTime);
int length=millTime.length()-10;
String millTimeTemp=millTime.substring(length, millTime.length());
// System.out.println(millTimeTemp);
Random random = new Random();
int a=random.nextInt(10);
int b=random.nextInt(10);
int c=random.nextInt(10);
String str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c)+millTimeTemp+String.valueOf(genSixNum());
return str;
}
/**
* 随机生成6位数
*
* @return
*/
private static int genSixNum() {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Random rand = new Random();
for (int i = 9; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = array[index];
array[index] = array[i - 1];
array[i - 1] = tmp;
}
int result = 0;
for (int i = 0; i < 6; i++)
result = result * 10 + array[i];
return result;
}
public static void main(String[] args) {
System.out.println(GenOrderCode.next());
}
}
| 1,666 | 0.649693 | 0.625767 | 71 | 21.957747 | 21.392664 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.830986 | false | false | 9 |
306aa150ac96d065e424d9d5f2414bc28c243941 | 5,952,824,673,821 | 3f8dee04fdbdebfdb96648b5241765263539d935 | /ssh_application/src/main/Java/com/zr/dao/LinkManDao.java | c12acef90c9e6100711f9b4140ec7ed8a85b9370 | [] | no_license | ZWYXY/ssh | https://github.com/ZWYXY/ssh | a0b7fcf4b3eedb5900daeaa56fcf8c0aa390a917 | 34839a5150478e8a432dc667f573ca4694edb65f | refs/heads/master | 2022-12-23T16:59:10.254000 | 2018-11-30T15:04:49 | 2018-11-30T15:04:49 | 219,640,570 | 0 | 0 | null | false | 2022-12-10T05:17:23 | 2019-11-05T02:30:47 | 2019-11-05T02:47:05 | 2022-12-10T05:17:22 | 1,772 | 0 | 0 | 7 | CSS | false | false | package com.zr.dao;
import com.zr.entity.LinkMan;
import java.util.List;
public interface LinkManDao extends BaseDao<LinkMan> {
/**
* LinkManDao provide some good ways that connect to DBMS.
*
*
*
* @author zhourui
* @since 1.0.1
*/
List<LinkMan> findMoreCondition(LinkMan linkMan);
List<LinkMan> findPage(int begin, int rows);
int findCount();
/*
void add(LinkMan linkMan);
LinkMan findOne(int lkmId);//按Id查询
List<LinkMan> listLinkMan();//查询所有联系人
void update(LinkMan linkMan);
void delete(LinkMan linkMan);
*/
}
| UTF-8 | Java | 644 | java | LinkManDao.java | Java | [
{
"context": "nnect to DBMS.\r\n *\r\n *\r\n *\r\n * @author zhourui\r\n * @since 1.0.1\r\n */\r\n\r\n List<LinkMan> ",
"end": 251,
"score": 0.9927191734313965,
"start": 244,
"tag": "USERNAME",
"value": "zhourui"
}
] | null | [] | package com.zr.dao;
import com.zr.entity.LinkMan;
import java.util.List;
public interface LinkManDao extends BaseDao<LinkMan> {
/**
* LinkManDao provide some good ways that connect to DBMS.
*
*
*
* @author zhourui
* @since 1.0.1
*/
List<LinkMan> findMoreCondition(LinkMan linkMan);
List<LinkMan> findPage(int begin, int rows);
int findCount();
/*
void add(LinkMan linkMan);
LinkMan findOne(int lkmId);//按Id查询
List<LinkMan> listLinkMan();//查询所有联系人
void update(LinkMan linkMan);
void delete(LinkMan linkMan);
*/
}
| 644 | 0.613782 | 0.608974 | 34 | 16.352942 | 18.708101 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 9 |
7c3bee4d995c22599f68962f92046346c2a20758 | 32,787,780,344,541 | 972574de1c589e917d479db42dec9f49cfe98056 | /src/main/java/com/zytc/web_3d_school/pojo/SecurityUser.java | d206383f0ee2c31a515d09c2f7744c3d176900fa | [] | no_license | changye-chen/web_3d_school | https://github.com/changye-chen/web_3d_school | 78b3c22432cf59c78bbca5f10c126d58ee35c934 | aa8952f7012f781b09da3ec6dcdb452cf05e15f4 | refs/heads/main | 2023-04-06T18:49:05.736000 | 2021-04-18T07:31:53 | 2021-04-18T07:31:53 | 337,343,916 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zytc.web_3d_school.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import java.sql.Timestamp;
import java.util.Collection;
/**
* @program: web_3d_school
* @description: 实现UserDetails接口
* @author: ChangYe-Chen
* @create: 2021-02-24
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {
//主键,用户id
private int user_id;
//登录名
private String login_name;
//登录密码
private String login_pwd;
//用户真实姓名
private String user_name;
//状态:0:正常 1:冻结 2:删除
private byte status;
//最后登录时间
private Timestamp last_login_time;
//最后登录ip
private String last_login_ip;
//创建时间
private Timestamp create_time;
//邮件地址
private String email;
//手机号码
private String tel;
//所属角色id
private int role_id;
//绑定角色(暂用于绑定老师,绑定分校)
private int bindingRole;
//随机字符串
private String uuid;
//审核状态 1:已审核 0:未审核
private int is_examine;
//主任务id
private int main_mission_id;
//子任务id
private int sub_mission_id;
@Override
public String getPassword() {
return login_pwd;
}
@Override
public String getUsername() {
return login_name;
}
@Override
public boolean isEnabled() { return true; }
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("user");
}
}
| UTF-8 | Java | 2,124 | java | SecurityUser.java | Java | [
{
"context": "chool\n * @description: 实现UserDetails接口\n * @author: ChangYe-Chen\n * @create: 2021-02-24\n **/\n@Data\n@AllArgsConstru",
"end": 463,
"score": 0.9997090697288513,
"start": 451,
"tag": "NAME",
"value": "ChangYe-Chen"
},
{
"context": "e\n public String getPassword() {\... | null | [] | package com.zytc.web_3d_school.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import java.sql.Timestamp;
import java.util.Collection;
/**
* @program: web_3d_school
* @description: 实现UserDetails接口
* @author: ChangYe-Chen
* @create: 2021-02-24
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {
//主键,用户id
private int user_id;
//登录名
private String login_name;
//登录密码
private String login_pwd;
//用户真实姓名
private String user_name;
//状态:0:正常 1:冻结 2:删除
private byte status;
//最后登录时间
private Timestamp last_login_time;
//最后登录ip
private String last_login_ip;
//创建时间
private Timestamp create_time;
//邮件地址
private String email;
//手机号码
private String tel;
//所属角色id
private int role_id;
//绑定角色(暂用于绑定老师,绑定分校)
private int bindingRole;
//随机字符串
private String uuid;
//审核状态 1:已审核 0:未审核
private int is_examine;
//主任务id
private int main_mission_id;
//子任务id
private int sub_mission_id;
@Override
public String getPassword() {
return <PASSWORD>;
}
@Override
public String getUsername() {
return login_name;
}
@Override
public boolean isEnabled() { return true; }
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("user");
}
}
| 2,125 | 0.673777 | 0.665973 | 88 | 20.84091 | 16.210186 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 9 |
b9b93bbe49e52d9c9cff0c96ddae76547542b011 | 23,630,910,132,389 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /platform/lang-impl/src/com/intellij/refactoring/actions/IntroduceFunctionalParameterAction.java | 66a6c9a9652bb48c32aef04b3dc81602063f45b4 | [
"Apache-2.0"
] | permissive | JetBrains/intellij-community | https://github.com/JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560000 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.refactoring.actions;
import com.intellij.lang.refactoring.RefactoringSupportProvider;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import org.jetbrains.annotations.NotNull;
public final class IntroduceFunctionalParameterAction extends IntroduceActionBase {
@Override
protected RefactoringActionHandler getRefactoringHandler(@NotNull RefactoringSupportProvider provider) {
return provider.getIntroduceFunctionalParameterHandler();
}
public static @NlsContexts.DialogTitle String getRefactoringName() {
return RefactoringBundle.message("introduce.functional.parameter.title");
}
}
| UTF-8 | Java | 853 | java | IntroduceFunctionalParameterAction.java | Java | [] | null | [] | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.refactoring.actions;
import com.intellij.lang.refactoring.RefactoringSupportProvider;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import org.jetbrains.annotations.NotNull;
public final class IntroduceFunctionalParameterAction extends IntroduceActionBase {
@Override
protected RefactoringActionHandler getRefactoringHandler(@NotNull RefactoringSupportProvider provider) {
return provider.getIntroduceFunctionalParameterHandler();
}
public static @NlsContexts.DialogTitle String getRefactoringName() {
return RefactoringBundle.message("introduce.functional.parameter.title");
}
}
| 853 | 0.833529 | 0.821805 | 20 | 41.650002 | 37.250874 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
814470f353b812a91d1a1041e6b0ad785f3cd6a6 | 22,282,290,370,846 | 64d4952b00334053091f535f8c37aeb561b01db3 | /david_springboot_parent/david_springboot_rabbitmq/src/main/java/com/david/constants/RabbitmqConstant.java | 280df5dcfc2403c5e49319a27015873d6cff6a2c | [] | no_license | GTWONDER/ed-springboot-learning | https://github.com/GTWONDER/ed-springboot-learning | bfc980f5503c490db89b6448e7dd3fae0e4b5c7d | f6c06a3583e85def777dcf6d79e92332778f0cae | refs/heads/master | 2022-10-01T12:49:13.892000 | 2020-06-15T04:45:15 | 2020-06-15T04:45:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.david.constants;
/**
* 存放一些常量类
* @author :David
* @weibo :http://weibo.com/mcxiaobing
* @github: https://github.com/QQ986945193
*/
public class RabbitmqConstant {
public static final String HOST = "localhost";
public static final String QUEUE_NAME = "QUEUE_DAVID";
public static final String TOPIC_NAME = "TOPIC_NAME";
public static final String USERNAME = "admin";
public static final String PASSWORD = "admin";
public static final String SPRING_BOOT_QUEUE_NAME = "SPRING_BOOT_QUEUE_NAME";
}
| UTF-8 | Java | 535 | java | RabbitmqConstant.java | Java | [
{
"context": "e com.david.constants;\n/**\n * 存放一些常量类\n * @author :David\n * @weibo :http://weibo.com/mcxiaobing\n * @github",
"end": 61,
"score": 0.9990789294242859,
"start": 56,
"tag": "NAME",
"value": "David"
},
{
"context": "常量类\n * @author :David\n * @weibo :http://weibo.com/mcx... | null | [] | package com.david.constants;
/**
* 存放一些常量类
* @author :David
* @weibo :http://weibo.com/mcxiaobing
* @github: https://github.com/QQ986945193
*/
public class RabbitmqConstant {
public static final String HOST = "localhost";
public static final String QUEUE_NAME = "QUEUE_DAVID";
public static final String TOPIC_NAME = "TOPIC_NAME";
public static final String USERNAME = "admin";
public static final String PASSWORD = "<PASSWORD>";
public static final String SPRING_BOOT_QUEUE_NAME = "SPRING_BOOT_QUEUE_NAME";
}
| 540 | 0.733075 | 0.715667 | 16 | 31.3125 | 22.810959 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 9 |
54459bf71716ee803fea44509aac8a2907db1e79 | 23,132,693,895,115 | 91de02447229e5d0fa1c4b0cb8330d82aefd0dcf | /ContractedEmployee (4).java | 4e79d50a0b4f89d1cf48291141053305be413de6 | [] | no_license | aswinsadan/java_assignment | https://github.com/aswinsadan/java_assignment | 93e5a620697f41e91ed0c9e4dbd1d3f9036567b6 | 1bcc6ccf3f449f0c248f923dba0582bcd1d3a046 | refs/heads/master | 2020-05-21T14:22:52.510000 | 2017-03-17T06:46:58 | 2017-03-17T06:46:58 | 84,623,538 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package employee;
public class ContractedEmployee extends Employee implements promotionalOffers {
int ContractDuration,fine;
public ContractedEmployee(int id,String name,int ContractDuration){
super(id,name);
this.ContractDuration=ContractDuration;
System.out.println("details of contracted employee\nid:"+id+"\nname:"+name+"\ncontract code:"+ContractDuration);
}
void setSalary(int salary){
super.salary=salary;
}
void setFine(int fine){
this.fine=fine;
}
void calculatesalary(){
salary=salary-fine;
System.out.println("salary:"+salary);
}
@Override
public void SeasonOffer(double amount) {
amount=amount-(0.08*amount);
System.out.println("seasonal offer:"+amount);
}
@Override
public void regularoffer(double amount) {
amount=amount-(0.15*amount);
System.out.println("regular offer:"+amount);
}
public void registerInsurance() {
insuranceNo="INS_"+id+02;
insureAmount=3000;
System.out.println("insure no:"+insuranceNo+"insureamount:"+insureAmount);
}
public void payEMI() {
totalEMI=0.08*insuranceAmount;
System.out.println("emi:"+totalEMI);
}
}
| UTF-8 | Java | 1,282 | java | ContractedEmployee (4).java | Java | [] | null | [] |
package employee;
public class ContractedEmployee extends Employee implements promotionalOffers {
int ContractDuration,fine;
public ContractedEmployee(int id,String name,int ContractDuration){
super(id,name);
this.ContractDuration=ContractDuration;
System.out.println("details of contracted employee\nid:"+id+"\nname:"+name+"\ncontract code:"+ContractDuration);
}
void setSalary(int salary){
super.salary=salary;
}
void setFine(int fine){
this.fine=fine;
}
void calculatesalary(){
salary=salary-fine;
System.out.println("salary:"+salary);
}
@Override
public void SeasonOffer(double amount) {
amount=amount-(0.08*amount);
System.out.println("seasonal offer:"+amount);
}
@Override
public void regularoffer(double amount) {
amount=amount-(0.15*amount);
System.out.println("regular offer:"+amount);
}
public void registerInsurance() {
insuranceNo="INS_"+id+02;
insureAmount=3000;
System.out.println("insure no:"+insuranceNo+"insureamount:"+insureAmount);
}
public void payEMI() {
totalEMI=0.08*insuranceAmount;
System.out.println("emi:"+totalEMI);
}
}
| 1,282 | 0.635725 | 0.624025 | 45 | 27.444445 | 25.696135 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488889 | false | false | 9 |
7c201094ecc57de04e9e1f87779ed2d42e753d67 | 26,680,336,869,507 | ae743d09e38263b8687642ab79b2da238a437b1a | /dlintranet/src/MailQueue/scheduler/MailSenderSchedulerDAO.java | 959e3ebb26b35b798465f272f0ecf1040458da58 | [] | no_license | ChanduJella/Chandu-Github | https://github.com/ChanduJella/Chandu-Github | 63c31a826814b87cb603f46687d668558383bb1f | d9c746f49d1b8efe2b77bfdf06e4a77491db8554 | refs/heads/master | 2020-03-19T04:54:51.809000 | 2018-06-13T07:30:13 | 2018-06-13T07:30:13 | 135,881,458 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*Title : CommonMailer
*
* Copyright (c) 2007 by Datamatics Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of Datamatics Ltd
* ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with Datamatics Ltd.
* @Class Name : MailSchedulerDAO
* @Created on : 18-June-07
* @Author : Ambikesh
* @Extends :
* @Change Log :
*----------------------------------------------------------------------------
* Version Date Author Changes
*----------------------------------------------------------------------------
* 1.0.0 18-June-07 Ambikesh Initial Version
*----------------------------------------------------------------------------
*
*/
package MailQueue.scheduler;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import commonmailapi.MailSender;
import components.DateConvert;
import MailQueue.CreateLog;
import MailQueue.com.main.GetDataByTag;
import MailQueue.com.main.MailerModification;
import MailQueue.com.xmlcommon.ReadProperty;
import MailQueue.xmlinterface.MailerQueue;
import MailQueue.xmlto.XMLReaderTO;
public class MailSenderSchedulerDAO implements Job{
//default job class constructor
public MailSenderSchedulerDAO() {
}
//Inherited execute method
public void execute(JobExecutionContext context)
throws JobExecutionException {
////system.out.println("Normal Mail Scheduler Task Running");
////system.out.println(new Date());
main();
}
public static void main(String args[]){
MailSenderSchedulerDAO da=new MailSenderSchedulerDAO();
da.main();
}
@SuppressWarnings("deprecation")
public void main() {
ArrayList arrList = new ArrayList();
ArrayList dataList = new ArrayList();
String message = null;
String[] ccadd = new String[40];
MailerModification modification = new MailerModification();
MailSender mailSender = new MailSender();
MailerQueue queue = MailerQueue.getInstance();
queue.initiate();
//getting tag names from properties file
arrList = ReadProperty.getHeadTags();
Iterator iter0 =arrList.iterator();
while(iter0.hasNext()){
String tag =(String)iter0.next();
//getting data for tag from xml files
GetDataByTag dataByTag = new GetDataByTag();
dataList = dataByTag.getDataByTag(tag, queue.data);
queue.data = "";
queue.commit(false);
queue.finalisingObject(queue);
CreateLog.saveoutData("WRITING IT THE FIRST TIME ############################################################\n\n");
Iterator iter1 = dataList.iterator();
while(iter1.hasNext()){
try {
XMLReaderTO readerTO = new XMLReaderTO();
readerTO = (XMLReaderTO) iter1.next();
to = readerTO.getTo();
from = readerTO.getFrom();
cc = readerTO.getCc();
subject = readerTO.getSubject();
body = readerTO.getBody();
if(cc.equalsIgnoreCase("no data")){
cc = null;
}
if(!(cc == null || cc.equalsIgnoreCase("null"))){
if(cc.contains("~~")){
ccadd = cc.split("~~");
}
else{
ccadd[0] = cc;
}
}
message = body;
Date date = new Date();
subject +=", Sent on " + DateConvert.formatDMMY(date) + " at " + date.getHours() + ":" + date.getMinutes();
////system.out.println("Hitting Out:--" + to +" "+ subject);
CreateLog.saveoutData(modification.setData(from, to, null, subject, body, false));
//sending mails
if(cc != null){
mailSender.sendMessage(from, to, subject,message, ccadd);
// //system.out.println(from + to + subject + message + ccadd);
}
else
// //system.out.println(from + to + subject + message );
mailSender.sendMessage(from, to, subject, message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
CreateLog.saveoutData("ENDING A NEW LOG ###############################################################\n\n");
// queue.data = "";
//
// queue.commit(false);
// int write = 1;
//
// XMLFileOperation.write("", write);
}
public static String to = null;
public static String from = null;
public static String cc = null;
public static String subject = null;
public static String body = null;
}
| UTF-8 | Java | 4,657 | java | MailSenderSchedulerDAO.java | Java | [
{
"context": "eated on : 18-June-07 \r\n * @Author : Ambikesh\r\n * @Extends : \r\n * @Change Log :\r\n ",
"end": 499,
"score": 0.9997085928916931,
"start": 491,
"tag": "NAME",
"value": "Ambikesh"
},
{
"context": "----------------------\r\n * 1.0.0 18-Ju... | null | [] | /*
*Title : CommonMailer
*
* Copyright (c) 2007 by Datamatics Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of Datamatics Ltd
* ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with Datamatics Ltd.
* @Class Name : MailSchedulerDAO
* @Created on : 18-June-07
* @Author : Ambikesh
* @Extends :
* @Change Log :
*----------------------------------------------------------------------------
* Version Date Author Changes
*----------------------------------------------------------------------------
* 1.0.0 18-June-07 Ambikesh Initial Version
*----------------------------------------------------------------------------
*
*/
package MailQueue.scheduler;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import commonmailapi.MailSender;
import components.DateConvert;
import MailQueue.CreateLog;
import MailQueue.com.main.GetDataByTag;
import MailQueue.com.main.MailerModification;
import MailQueue.com.xmlcommon.ReadProperty;
import MailQueue.xmlinterface.MailerQueue;
import MailQueue.xmlto.XMLReaderTO;
public class MailSenderSchedulerDAO implements Job{
//default job class constructor
public MailSenderSchedulerDAO() {
}
//Inherited execute method
public void execute(JobExecutionContext context)
throws JobExecutionException {
////system.out.println("Normal Mail Scheduler Task Running");
////system.out.println(new Date());
main();
}
public static void main(String args[]){
MailSenderSchedulerDAO da=new MailSenderSchedulerDAO();
da.main();
}
@SuppressWarnings("deprecation")
public void main() {
ArrayList arrList = new ArrayList();
ArrayList dataList = new ArrayList();
String message = null;
String[] ccadd = new String[40];
MailerModification modification = new MailerModification();
MailSender mailSender = new MailSender();
MailerQueue queue = MailerQueue.getInstance();
queue.initiate();
//getting tag names from properties file
arrList = ReadProperty.getHeadTags();
Iterator iter0 =arrList.iterator();
while(iter0.hasNext()){
String tag =(String)iter0.next();
//getting data for tag from xml files
GetDataByTag dataByTag = new GetDataByTag();
dataList = dataByTag.getDataByTag(tag, queue.data);
queue.data = "";
queue.commit(false);
queue.finalisingObject(queue);
CreateLog.saveoutData("WRITING IT THE FIRST TIME ############################################################\n\n");
Iterator iter1 = dataList.iterator();
while(iter1.hasNext()){
try {
XMLReaderTO readerTO = new XMLReaderTO();
readerTO = (XMLReaderTO) iter1.next();
to = readerTO.getTo();
from = readerTO.getFrom();
cc = readerTO.getCc();
subject = readerTO.getSubject();
body = readerTO.getBody();
if(cc.equalsIgnoreCase("no data")){
cc = null;
}
if(!(cc == null || cc.equalsIgnoreCase("null"))){
if(cc.contains("~~")){
ccadd = cc.split("~~");
}
else{
ccadd[0] = cc;
}
}
message = body;
Date date = new Date();
subject +=", Sent on " + DateConvert.formatDMMY(date) + " at " + date.getHours() + ":" + date.getMinutes();
////system.out.println("Hitting Out:--" + to +" "+ subject);
CreateLog.saveoutData(modification.setData(from, to, null, subject, body, false));
//sending mails
if(cc != null){
mailSender.sendMessage(from, to, subject,message, ccadd);
// //system.out.println(from + to + subject + message + ccadd);
}
else
// //system.out.println(from + to + subject + message );
mailSender.sendMessage(from, to, subject, message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
CreateLog.saveoutData("ENDING A NEW LOG ###############################################################\n\n");
// queue.data = "";
//
// queue.commit(false);
// int write = 1;
//
// XMLFileOperation.write("", write);
}
public static String to = null;
public static String from = null;
public static String cc = null;
public static String subject = null;
public static String body = null;
}
| 4,657 | 0.590724 | 0.585355 | 169 | 25.556213 | 25.034616 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.331361 | false | false | 9 |
fb962cf141309cf79593a1fe80a1a13c5abedfc9 | 15,083,925,147,157 | 4cbcf6b524e5b5daeb78abceafcf7c5fdb0327da | /app/src/main/java/com/closetshare/app/PostAdapter.java | 26efcccc3fe95a866581f31e7ae68414e110fb13 | [] | no_license | csulbcecs343/group4 | https://github.com/csulbcecs343/group4 | 9c00811068240d5977cfa35ae6e23386654747cd | 2eee0b7ba4ce5d3a5fa9bfe27f6a830ea8536292 | refs/heads/master | 2021-01-01T19:01:26.017000 | 2014-04-24T03:20:16 | 2014-04-24T03:20:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.closetshare.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
public class PostAdapter extends BaseAdapter {
Context mContext;
ArrayList<PostView> mList = new ArrayList<PostView>();
public PostAdapter(Context context) {
mContext = context;
}
public void addItem(String username, String photoUrl, String description, int rating) {
PostView postView = new PostView(mContext);
postView.setData(username, photoUrl, description, rating);
mList.add(postView);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mList.size();
}
@Override
public PostView getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PostView postView = (PostView) convertView;
if (postView == null) {
postView = new PostView(mContext);
} else {
postView = mList.get(position);
}
return postView;
}
}
| UTF-8 | Java | 1,267 | java | PostAdapter.java | Java | [] | null | [] | package com.closetshare.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
public class PostAdapter extends BaseAdapter {
Context mContext;
ArrayList<PostView> mList = new ArrayList<PostView>();
public PostAdapter(Context context) {
mContext = context;
}
public void addItem(String username, String photoUrl, String description, int rating) {
PostView postView = new PostView(mContext);
postView.setData(username, photoUrl, description, rating);
mList.add(postView);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mList.size();
}
@Override
public PostView getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PostView postView = (PostView) convertView;
if (postView == null) {
postView = new PostView(mContext);
} else {
postView = mList.get(position);
}
return postView;
}
}
| 1,267 | 0.648777 | 0.648777 | 56 | 21.625 | 21.554384 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
45e19bb2e768bf4803568ffad921e94bbd431d60 | 29,609,504,541,039 | 0c9519e58c4404d14193c1bcdc6b9956ecc8c5b8 | /src/main/java/reservation/service/RepresentationUserServiceImpl.java | ca4dc61809e14526d52cfafd249a91b054e3d0e8 | [] | no_license | zouzouclem/reservation | https://github.com/zouzouclem/reservation | 8bb37d1559434dad73a9bfc50cea7e7ee558a671 | 07e6a8f1617cd285bd6a494d6c0c20a01e75706a | refs/heads/master | 2020-03-07T06:21:54.338000 | 2018-06-14T19:23:30 | 2018-06-14T19:23:30 | 127,320,105 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package reservation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reservation.entity.RepresentationUser;
import reservation.entity.Representations;
import reservation.entity.Shows;
import reservation.repository.RepresentationRepository;
import reservation.repository.RepresentationUserRepository;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Transactional
public class RepresentationUserServiceImpl implements RepresentationUserService {
@Autowired
RepresentationUserRepository representationUserRepository;
@Override
public RepresentationUser save(RepresentationUser representationUser) {
return representationUserRepository.save(representationUser);
}
@Override
public void remove(RepresentationUser representationUser) {
representationUserRepository.delete(representationUser);
}
@Override
public List<RepresentationUser> findByRepresentation(Representations representations) {
return representationUserRepository.findByRepresentationsByRepresentationId(representations);
}
}
| UTF-8 | Java | 1,164 | java | RepresentationUserServiceImpl.java | Java | [] | null | [] | package reservation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reservation.entity.RepresentationUser;
import reservation.entity.Representations;
import reservation.entity.Shows;
import reservation.repository.RepresentationRepository;
import reservation.repository.RepresentationUserRepository;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Transactional
public class RepresentationUserServiceImpl implements RepresentationUserService {
@Autowired
RepresentationUserRepository representationUserRepository;
@Override
public RepresentationUser save(RepresentationUser representationUser) {
return representationUserRepository.save(representationUser);
}
@Override
public void remove(RepresentationUser representationUser) {
representationUserRepository.delete(representationUser);
}
@Override
public List<RepresentationUser> findByRepresentation(Representations representations) {
return representationUserRepository.findByRepresentationsByRepresentationId(representations);
}
}
| 1,164 | 0.825601 | 0.825601 | 36 | 31.333334 | 30.38183 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 9 |
e46ae03d2cc374fbcc49d2a0708bb0c7095b07cb | 27,582,279,978,894 | 417972adc5231c740274219b04cce926c5fcb0d4 | /src/main/java/com/store/cosystore/service/WishListService.java | b950a8731ed12c5bb6ff169ee3b465b6fec2250b | [] | no_license | DariaKlochkova/cosystore | https://github.com/DariaKlochkova/cosystore | ca1a09cbdc4a415bfbfcadccf3c845f677c85a38 | 17561ad460fecd35ab2d8e254d13ca4ccd126fb0 | refs/heads/master | 2023-04-06T22:52:05.840000 | 2022-09-06T20:39:05 | 2022-09-06T20:39:05 | 214,583,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.store.cosystore.service;
import com.store.cosystore.domain.ProductVersion;
import com.store.cosystore.domain.User;
import com.store.cosystore.repos.ProductVersionRepo;
import com.store.cosystore.repos.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class WishListService {
@Autowired
private ProductVersionRepo productVersionRepo;
@Autowired
private UserRepo userRepo;
public void addProduct(User user, int productVersionId){
ProductVersion productVersion = productVersionRepo.findById(productVersionId);
if (!user.getWishList().contains(productVersion)){
productVersion.like();
productVersionRepo.save(productVersion);
user.getWishList().add(productVersion);
userRepo.save(user);
}
}
public void deleteProduct(User user, int productVersionId){
ProductVersion productVersion = productVersionRepo.findById(productVersionId);
if(user.getWishList().remove(productVersion)){
productVersion.unlike();
productVersionRepo.save(productVersion);
userRepo.save(user);
}
}
}
| UTF-8 | Java | 1,235 | java | WishListService.java | Java | [] | null | [] | package com.store.cosystore.service;
import com.store.cosystore.domain.ProductVersion;
import com.store.cosystore.domain.User;
import com.store.cosystore.repos.ProductVersionRepo;
import com.store.cosystore.repos.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class WishListService {
@Autowired
private ProductVersionRepo productVersionRepo;
@Autowired
private UserRepo userRepo;
public void addProduct(User user, int productVersionId){
ProductVersion productVersion = productVersionRepo.findById(productVersionId);
if (!user.getWishList().contains(productVersion)){
productVersion.like();
productVersionRepo.save(productVersion);
user.getWishList().add(productVersion);
userRepo.save(user);
}
}
public void deleteProduct(User user, int productVersionId){
ProductVersion productVersion = productVersionRepo.findById(productVersionId);
if(user.getWishList().remove(productVersion)){
productVersion.unlike();
productVersionRepo.save(productVersion);
userRepo.save(user);
}
}
}
| 1,235 | 0.719838 | 0.719838 | 38 | 31.5 | 25.162367 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 9 |
00415e522ea335b3bb962d0a9eed07541e5f440d | 9,637,906,622,288 | eb16350ff7bfa44ca6553a89a023f2b48ac87a0c | /src/main/java/com/web/controller/admin/scooterclass/AddScooterModelController.java | d5fe8cc92a8e0dcd002890a9195c93d85cee2733 | [] | no_license | MarcinMikolajczyk/projetk_bazodanowy | https://github.com/MarcinMikolajczyk/projetk_bazodanowy | 3c742e718fd8d22c0bd113b4c812b52e036b954c | e45fe4f7f1dfb75dde19b87bf34bcff18b8b422d | refs/heads/master | 2022-12-21T01:03:26.632000 | 2019-12-23T08:49:07 | 2019-12-23T08:49:07 | 229,713,776 | 0 | 0 | null | false | 2022-12-10T05:45:25 | 2019-12-23T08:51:57 | 2019-12-23T08:57:05 | 2022-12-10T05:45:24 | 27,319 | 0 | 0 | 4 | HTML | false | false | package com.web.controller.admin.scooterclass;
import com.data.JpaScooter;
import com.entity.Cennik;
import com.entity.Skutery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.persistence.TypedQuery;
import java.util.List;
@Controller
@RequestMapping("/admin/scooter/model/add")
public class AddScooterModelController {
@Autowired
private JpaScooter jpaScooter;
@RequestMapping
public String addScooter(Model model){
TypedQuery<Cennik> query = jpaScooter.getEn()
.createQuery("select c from Cennik c", Cennik.class);
List<Cennik> cenniki = query.getResultList();
Skutery skuter = new Skutery();
Cennik cennik = new Cennik();
model.addAttribute("skuter", skuter);
model.addAttribute("cenniki", cenniki);
model.addAttribute("cennik", cennik);
return "admin/scooters/addModel";
}
@RequestMapping(method = RequestMethod.POST)
public String saveScooter(@ModelAttribute Skutery skuter,
@ModelAttribute Cennik cennik,
BindingResult result){
cennik = jpaScooter.findCennik(cennik.getId());
jpaScooter.addSkutery(skuter, cennik);
return "redirect:/admin/scooter";
}
}
| UTF-8 | Java | 1,625 | java | AddScooterModelController.java | Java | [] | null | [] | package com.web.controller.admin.scooterclass;
import com.data.JpaScooter;
import com.entity.Cennik;
import com.entity.Skutery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.persistence.TypedQuery;
import java.util.List;
@Controller
@RequestMapping("/admin/scooter/model/add")
public class AddScooterModelController {
@Autowired
private JpaScooter jpaScooter;
@RequestMapping
public String addScooter(Model model){
TypedQuery<Cennik> query = jpaScooter.getEn()
.createQuery("select c from Cennik c", Cennik.class);
List<Cennik> cenniki = query.getResultList();
Skutery skuter = new Skutery();
Cennik cennik = new Cennik();
model.addAttribute("skuter", skuter);
model.addAttribute("cenniki", cenniki);
model.addAttribute("cennik", cennik);
return "admin/scooters/addModel";
}
@RequestMapping(method = RequestMethod.POST)
public String saveScooter(@ModelAttribute Skutery skuter,
@ModelAttribute Cennik cennik,
BindingResult result){
cennik = jpaScooter.findCennik(cennik.getId());
jpaScooter.addSkutery(skuter, cennik);
return "redirect:/admin/scooter";
}
}
| 1,625 | 0.712 | 0.712 | 53 | 29.660378 | 23.153257 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603774 | false | false | 9 |
6f5cfc3216e4d3a443040a9bb615dd936ee554f2 | 9,637,906,624,303 | f52c284ef1ec9a2fbc1a76153247e4ee58b48b95 | /src/main/java/com/example/OA/dao/RoleMapper.java | 38dd05ab3dbb10a7805fe35752ff5f01b499e84e | [] | no_license | Zz451117872/OA | https://github.com/Zz451117872/OA | de85c905b166de4430cf7669462b0350e011e6d1 | ba11276d56ae21dd7704e717c91e8e26dac4297f | refs/heads/master | 2021-05-07T19:21:36.388000 | 2018-03-07T00:52:06 | 2018-03-07T00:52:06 | 108,861,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.OA.dao;
import com.example.OA.model.Role;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface RoleMapper {
int deleteByPrimaryKey(Integer id);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
//----------------------------------------------------
Role getByRolename(String roleName);
List<Role> getByRoleIds(@Param("roleIds") List<Integer> roleIds);
List<Role> getAll();
} | UTF-8 | Java | 605 | java | RoleMapper.java | Java | [] | null | [] | package com.example.OA.dao;
import com.example.OA.model.Role;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface RoleMapper {
int deleteByPrimaryKey(Integer id);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
//----------------------------------------------------
Role getByRolename(String roleName);
List<Role> getByRoleIds(@Param("roleIds") List<Integer> roleIds);
List<Role> getAll();
} | 605 | 0.666116 | 0.666116 | 27 | 21.444445 | 21.21553 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 9 |
64ce6ed3875472eae7d84e3f8466ca9f48f59c35 | 22,256,520,547,018 | 5339b1bc17b3d1e4e2c5872c286abe7b68018795 | /src/com/w3resource/basicpart1/EX104.java | e017491b47cc564b1d0b0618aad6690fbacda8ae | [] | no_license | jayhebe/w3resource_exercises_java | https://github.com/jayhebe/w3resource_exercises_java | 28d42101f9b784ea676f6934ff2bbc0a9de9584d | 0731db2c0fefd95b43e1712db75431a9766fdccd | refs/heads/master | 2020-12-23T13:02:34.231000 | 2020-05-25T13:34:46 | 2020-05-25T13:34:46 | 237,161,641 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.w3resource.basicpart1;
/*
Write a Java program to create a new array from a given array of integers,
new array will contain the elements from the given array before the last element value 10.
*/
import java.util.Arrays;
public class EX104 {
public static void main(String[] args) {
int[] array_nums = {11, 11, 13, 10, 31, 45, 10, 20, 33, 10, 53};
int lastIndexOf10 = 0;
for (int i = 0; i < array_nums.length; i++) {
if (array_nums[i] == 10) {
lastIndexOf10 = i;
}
}
int[] new_array = new int[lastIndexOf10];
for (int i = 0; i < lastIndexOf10; i++) {
new_array[i] = array_nums[i];
}
System.out.println(Arrays.toString(new_array));
}
}
| UTF-8 | Java | 776 | java | EX104.java | Java | [] | null | [] | package com.w3resource.basicpart1;
/*
Write a Java program to create a new array from a given array of integers,
new array will contain the elements from the given array before the last element value 10.
*/
import java.util.Arrays;
public class EX104 {
public static void main(String[] args) {
int[] array_nums = {11, 11, 13, 10, 31, 45, 10, 20, 33, 10, 53};
int lastIndexOf10 = 0;
for (int i = 0; i < array_nums.length; i++) {
if (array_nums[i] == 10) {
lastIndexOf10 = i;
}
}
int[] new_array = new int[lastIndexOf10];
for (int i = 0; i < lastIndexOf10; i++) {
new_array[i] = array_nums[i];
}
System.out.println(Arrays.toString(new_array));
}
}
| 776 | 0.570876 | 0.516753 | 27 | 27.74074 | 25.989447 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.851852 | false | false | 9 |
176ae4734c74bb3317fa0dce0abacb1444b3c4ef | 2,834,678,448,007 | 07bb9ecc0d153671d2b738c2f02802f32b2a58de | /src/main/java/org/austinjug/jaxb/model/Polygon.java | 73ba048b0fe38eb4a179794762faca62597f3e40 | [] | no_license | rrr6399/JaxbMavenDemo | https://github.com/rrr6399/JaxbMavenDemo | e8a7c51e9cd3842d999eeac9af6f1d7a0b60979a | ee92fe97bfefa42b9dc8e2852abddf04d5ba4128 | refs/heads/master | 2021-01-10T20:39:09.868000 | 2015-03-18T18:56:31 | 2015-03-18T18:56:31 | 32,477,038 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.austinjug.jaxb.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "Polygon")
@XmlType(name = "Polygon_Type")
public class Polygon extends Shape {
@XmlElementWrapper(name = "Points")
@XmlElement(name="Point")
private List<Point> points;
@Override
public Double getArea() {
return null;
}
public List<Point> getPoints() {
return this.points;
}
public void setPoints(List<Point> points) {
this.points = points;
}
}
| UTF-8 | Java | 667 | java | Polygon.java | Java | [] | null | [] | package org.austinjug.jaxb.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "Polygon")
@XmlType(name = "Polygon_Type")
public class Polygon extends Shape {
@XmlElementWrapper(name = "Points")
@XmlElement(name="Point")
private List<Point> points;
@Override
public Double getArea() {
return null;
}
public List<Point> getPoints() {
return this.points;
}
public void setPoints(List<Point> points) {
this.points = points;
}
}
| 667 | 0.716642 | 0.716642 | 30 | 20.233334 | 17.21953 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false | 9 |
e1ae7e44f02a40d792fa5e1439d5b4021672a411 | 2,920,577,782,482 | 359b09253f89c409ed9e9fb534d3be7597adfa28 | /src/main/java/com/stivigala/wolt/rest/WoltRestController.java | 6c3d8928492fc9bd6fee8f65799c75c14b9d4da8 | [] | no_license | lacus6999/Stivigala | https://github.com/lacus6999/Stivigala | 32dc48bcae06a01060a86c2a9e284fb1e8a4e0ad | c19fa557efcc025536fc578fe0a2ec6f75c83929 | refs/heads/main | 2023-05-06T11:01:17.145000 | 2021-05-19T10:17:00 | 2021-05-19T10:17:00 | 341,905,732 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stivigala.wolt.rest;
import org.springframework.web.bind.annotation.*;
@RestController
public class WoltRestController {
@GetMapping("/admin")
public String adminPage() {
return "<p>This is an ADMIN site.</p><a href='/'>Back to main site</a>";
}
@GetMapping("/customer")
public String customerPage() {
return "<p>This is a CUSTOMER site.</p><a href='/'>Back to main site</a>";
}
@GetMapping("/manager")
public String managerPage() {
return "<p>This is a MANAGER site.</p><a href='/'>Back to main site</a>";
}
}
| UTF-8 | Java | 589 | java | WoltRestController.java | Java | [] | null | [] | package com.stivigala.wolt.rest;
import org.springframework.web.bind.annotation.*;
@RestController
public class WoltRestController {
@GetMapping("/admin")
public String adminPage() {
return "<p>This is an ADMIN site.</p><a href='/'>Back to main site</a>";
}
@GetMapping("/customer")
public String customerPage() {
return "<p>This is a CUSTOMER site.</p><a href='/'>Back to main site</a>";
}
@GetMapping("/manager")
public String managerPage() {
return "<p>This is a MANAGER site.</p><a href='/'>Back to main site</a>";
}
}
| 589 | 0.62309 | 0.62309 | 23 | 24.608696 | 26.305462 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.217391 | false | false | 9 |
8d4b94375eff39421e71bc354efb85308a43a790 | 5,909,875,063,444 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/4/4_3a26e41d86b893420514b569263893fa3a48af20/fLib/4_3a26e41d86b893420514b569263893fa3a48af20_fLib_t.java | f000b00e29245037b30c3a72a08eb16c9e6ee7f1 | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | /**
* Copyright 2001-2005 Iowa State University
* jportfolio@collaborium.org
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Forecast Library full of needed things for the forecast exercise
*
*
* @author Daryl Herzmann 26 July 2001
*/
package org.collaborium.portfolio.forecast;
import org.collaborium.portfolio.*;
import java.sql.*;
public class fLib {
/**
* Method that prints out a simple SELECT box
* for the years available
*/
public static String yearSelect() {
StringBuffer sbuf = new StringBuffer();
sbuf.append(" <SELECT name=\"year\">\n"
//+" <option value=\"2000\">2000\n"
+" <option value=\"2001\">2001\n"
+" <option value=\"2002\">2002\n"
+" <option value=\"2003\">2003\n"
+" <option value=\"2004\">2004\n"
+" <option value=\"2005\">2005\n"
+" <option value=\"2006\">2006\n"
+" <option value=\"2007\">2007\n"
+" <option value=\"2008\">2008\n"
+" <option value=\"2009\">2009\n"
+" <option value=\"2010\">2010\n"
+" <option value=\"2011\">2011\n"
+" <option value=\"2012\">2012\n"
+" <option value=\"2013\">2013\n"
+" <option value=\"2014\">2014\n"
+" <option value=\"2015\" SELECTED>2015\n"
+" </SELECT>\n");
return sbuf.toString();
} // End of yearSelect()
/**
* Method that prints out a simple SELECT box
* for the months available
*/
public static String monthSelect() {
StringBuffer sbuf = new StringBuffer();
sbuf.append(" <SELECT name=\"month\">\n"
+" <option value=\"1\">January\n"
+" <option value=\"2\">Feburary\n"
+" <option value=\"3\">March\n"
+" <option value=\"4\">April\n"
+" <option value=\"5\">May\n"
+" <option value=\"6\">June\n"
+" <option value=\"7\">July\n"
+" <option value=\"8\">August\n"
+" <option value=\"9\">September\n"
+" <option value=\"10\">October\n"
+" <option value=\"11\">November\n"
+" <option value=\"12\">December\n"
+" </SELECT>\n");
return sbuf.toString();
} // End of monthSelect()
/**
* Protoype to whichDay()
*/
public static String whichDay(String portfolio, String callMode,
String thisPageURL) throws SQLException {
return whichDay(portfolio, callMode, thisPageURL, "1970-01-01");
}
/**
* Generic method to get the user to select a date
* @param portfolio which is the Current Portfolio
* @param callMode value to send back to the CGI server
* @param thisPageURL value of the page to reference in the form
* @return HTMLformated string
*/
public static String whichDay(String portfolio, String callMode,
String thisPageURL, String selectedDate) throws SQLException {
StringBuffer sbuf = new StringBuffer();
ResultSet forecastDays = dbInterface.callDB("SELECT * from forecast_days "
+" WHERE portfolio = '"+ portfolio +"' "
+" and day <= CURRENT_TIMESTAMP::date ORDER by day ASC ");
sbuf.append("<FORM METHOD=\"GET\" ACTION=\""+thisPageURL+"\" name=\"f\">\n"
+"<input type=\"hidden\" name=\"mode\" value=\""+callMode+"\">\n"
+"<input type=\"hidden\" name=\"portfolio\" value=\""+portfolio+"\">\n"
+"<table border=0><tr><th>Forecast Date:</th>\n"
+"<td><SELECT NAME=\"sqlDate\">\n");
while ( forecastDays.next() ) {
String thisDate = forecastDays.getString("day");
sbuf.append("<OPTION VALUE=\""+thisDate+"\" ");
if (thisDate.equals(selectedDate)) sbuf.append("SELECTED");
sbuf.append(">"+thisDate+"\n");
}
sbuf.append("</SELECT></td><td>\n"
+"<INPUT TYPE=\"SUBMIT\" VALUE=\"Select Fx Date\">\n"
+"</td></tr></table>"
+"</FORM>\n");
return sbuf.toString();
}
/**
* Method that prints out a simple SELECT box
* for the months available
*/
public static String daySelect() {
StringBuffer sbuf = new StringBuffer();
sbuf.append(" <SELECT name=\"day\">\n");
for (int i = 1; i < 32; i++)
sbuf.append(" <option value="+i+">"+i+"\n");
sbuf.append(" </SELECT>\n");
return sbuf.toString();
} // End of daySelect()
/**
* Method that prints out the results for the last forecast
* @param portfolio value of the current portfolio
* @param sqlDate which is the value of the date wanted
* @param sortCol self-explainatory
* @param thisPageURL value of the current pageURL
*/
public static String forecastResults(String portfolio, String sqlDate,
String sortCol, String thisPageURL)
throws myException, SQLException {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<H3>Previous Forecast Results:</H3>\n");
/** If no date is specified, lets then see if the last answers works**/
if (sqlDate == null) {
ResultSet availDates = dbInterface.callDB("SELECT day "
+"from forecast_answers WHERE portfolio = '"+ portfolio +"' "
+" ORDER by day DESC LIMIT 1");
if ( availDates.next() ) {
sqlDate = availDates.getString("day");
} else {
throw new myException("No days available to view results for!");
}
}
sbuf.append( whichDay( portfolio, "l", thisPageURL, sqlDate ) );
/** We need to get results from the database **/
forecastDay thisDay = new forecastDay(portfolio, sqlDate);
thisDay.getValidation();
thisDay.getClimo();
if (sortCol == null) {
sortCol = "total_err";
}
sbuf.append( thisDay.catAnswers() );
sbuf.append("<BR><LI>Table Sorted by: "+ sortCol+"</LI>");
/** Now we have a date, lets get how the kids forecasted **/
ResultSet forecasts = dbInterface.callDB("SELECT "
+" getUserName(userid) as realname, * from forecast_grades "
+" WHERE portfolio = '"+ portfolio +"' "
+" and day = '"+ sqlDate +"' order by "+sortCol+" ");
sbuf.append("<P><TABLE>\n"
+"<TR>\n"
+" <TH rowspan=\"2\">Forecaster:</TH>\n"
+" <TH colspan=\"5\">Local Site:</TH>\n"
+" <TD rowspan=\"2\"></TD>\n"
+" <TH colspan=\"5\">Floater Site:</TH>\n"
+" <TH colspan=\"2\" rowspan=\"2\">\n"
+" <a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=total_err\">Total:</a></TH>\n"
+"</TR>\n"
+"<TR>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_err\">Tot:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_err\">Tot:</a></TH>\n"
+"</TR>\n");
int i = 0;
while ( forecasts.next() ) {
if (i % 2 == 0 )
sbuf.append("<TR bgcolor=\"#EEEEEE\">\n");
else
sbuf.append("<TR>\n");
sbuf.append("<TD>"+ forecasts.getString("realname") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("float_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("total_err") +"</TD>\n");
sbuf.append("</TR>\n");
i = i +1;
} // End of while()
sbuf.append("</TABLE>\n");
return sbuf.toString();
} // End of lastForecastResults()
/**
* Method that prints out the results for the last forecast
* @param portfolio value of the current portfolio
* @param sqlDate which is the value of the date wanted
* @param sortCol self-explainatory
* @param thisPageURL value of the current pageURL
*/
public static String cumulativeResults(String portfolio, String sortCol, String thisPageURL)
throws myException, SQLException {
StringBuffer sbuf = new StringBuffer();
if ( sortCol == null )
sortCol = "final_tot";
/** Now we have a date, lets get how the kids forecasted **/
ResultSet forecasts = dbInterface.callDB("SELECT getUserName(userid) as realname, *, "
+" (p0_total+ p1_total + p2_total + p3_total) AS final_tot from forecast_totals "
+" WHERE portfolio = '"+portfolio+"' "
+" order by "+sortCol+" ");
sbuf.append("<TABLE>\n"
+"<TR>\n"
+" <TH rowspan=\"2\">Forecaster:</TH>\n"
+" <TH colspan=\"5\">Local Site:</TH>\n"
+" <TD rowspan=\"2\"></TD>\n"
+" <TH colspan=\"5\">Floater Site:</TH>\n"
+" <TD rowspan=\"2\"></TD>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p0_total\">p0</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p1_total\">p1</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p2_total\">p2</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p3_total\">p3</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sortfinal_total\">Cum Total</a></TH>\n"
+"</TR>\n"
+"<TR>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_err\">Tot:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_err\">Tot:</a></TH>\n"
+"</TR>\n");
int i = 0;
while ( forecasts.next() ) {
if (i % 2 == 0 )
sbuf.append("<TR bgcolor=\"#EEEEEE\">\n");
else
sbuf.append("<TR>\n");
sbuf.append("<TD>"+ forecasts.getString("realname") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("float_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("p0_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("p1_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("p2_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("p3_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("final_tot") +"</TD>\n");
sbuf.append("</TR>\n");
i = i + 1;
} // End of while()
sbuf.append("</TABLE>\n");
return sbuf.toString();
} // End of cumulativeResults()
public static String adminRainSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='9' ");
if ( selected.equalsIgnoreCase("9") ) sbuf.append("SELECTED");
sbuf.append(">CAT 9 | Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 0.05\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 0.06 - 0.25\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 0.26 - 0.50\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 0.51 - 1.00\n");
sbuf.append("<option value='5' ");
if ( selected.equalsIgnoreCase("5") ) sbuf.append("SELECTED");
sbuf.append(">CAT 5 | 1.01 +\n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of rainSelect()
public static String rainSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 0.05\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 0.06 - 0.25\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 0.26 - 0.50\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 0.51 - 1.00\n");
sbuf.append("<option value='5' ");
if ( selected.equalsIgnoreCase("5") ) sbuf.append("SELECTED");
sbuf.append(">CAT 5 | 1.01 +\n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of rainSelect()
public static String adminSnowSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='9' ");
if ( selected.equalsIgnoreCase("9") ) sbuf.append("SELECTED");
sbuf.append(">CAT 9 | Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 2\"\n");
sbuf.append("<option value='8' ");
if ( selected.equalsIgnoreCase("8") ) sbuf.append("SELECTED");
sbuf.append(">CAT 8 | 2\"\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 2\" - 4\"\n");
sbuf.append("<option value='7' ");
if ( selected.equalsIgnoreCase("7") ) sbuf.append("SELECTED");
sbuf.append(">CAT 7 | 4\"\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 4\"- 8\"\n");
sbuf.append("<option value='6' ");
if ( selected.equalsIgnoreCase("6") ) sbuf.append("SELECTED");
sbuf.append(">CAT 6 | 8\"\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 8\" + \n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of snowSelect()
public static String snowSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 2\"\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 2\" - 4\"\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 4\"- 8\"\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 8\" + \n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of snowSelect()
public static String totalForecastErrors( String portfolio )
throws SQLException {
StringBuffer sbuf = new StringBuffer();
dbInterface.updateDB("DELETE from forecast_totals WHERE portfolio = '"+ portfolio +"' ");
/** Total all forecasts first */
dbInterface.updateDB("INSERT into forecast_totals ( SELECT userid, portfolio, sum(local_high), "
+" sum(local_low), sum(local_prec), sum(local_snow), sum(local_err), sum(float_high), "
+" sum(float_low), sum(float_prec), sum(float_snow), sum(float_err) from "
+" forecast_grades WHERE portfolio = '"+ portfolio +"' "
+" GROUP by userid, portfolio ) ");
ResultSet students = dbInterface.callDB("SELECT getUserName( username) as realname, "
+" username from students "
+" WHERE portfolio = '"+ portfolio +"' and nofx = 'n' ");
while ( students.next() ) {
String thisUserID = students.getString("username");
dbInterface.updateDB("UPDATE forecast_totals SET "
+" p0_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 0) , "
+" p1_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 1) , "
+" p2_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 2), "
+" p3_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 3) "
+" WHERE userid = '"+ thisUserID +"' and portfolio = '"+ portfolio +"' ");
}
/** Now we need to update Null values, hack! */
dbInterface.updateDB("update forecast_totals SET p1_total = 0 WHERE portfolio = '"+ portfolio +"' and p1_total IS NULL");
dbInterface.updateDB("update forecast_totals SET p2_total = 0 WHERE portfolio = '"+ portfolio +"' and p2_total IS NULL");
dbInterface.updateDB("update forecast_totals SET p3_total = 0 WHERE portfolio = '"+ portfolio +"' and p3_total IS NULL");
sbuf.append("Done Totalling Forecasts!");
return sbuf.toString();
}
/**
* gradeForecasts() does the automated grading of the entered forecasts
* @param portfolio which is the current Portfolio
* @param sqlDate which is the forecast Date we will be verifying
* @return String data
*/
public static String gradeForecasts( String portfolio, String sqlDate )
throws SQLException {
StringBuffer sbuf = new StringBuffer();
dbInterface.updateDB("DELETE from forecast_grades WHERE "
+" day = '"+ sqlDate +"' and portfolio = '"+ portfolio +"' ");
ResultSet students = dbInterface.callDB("SELECT "
+" getUserName( username) as realname, username from students "
+" WHERE portfolio = '"+ portfolio +"' and nofx = 'n' ");
forecastDay thisDay = new forecastDay(portfolio, sqlDate);
if (thisDay.getValidation()) {
thisDay.getClimo();
String caseGroup = thisDay.getCaseGroup();
String local_high = thisDay.getVLocalHighTemp();
String local_low = thisDay.getVLocalLowTemp();
String local_prec = thisDay.getVLocalPrecCat();
String local_snow = thisDay.getVLocalSnowCat();
String float_high = thisDay.getVFloaterHighTemp();
String float_low = thisDay.getVFloaterLowTemp();
String float_prec = thisDay.getVFloaterPrecCat();
String float_snow = thisDay.getVFloaterSnowCat();
String cl_local_high = thisDay.getCLocalHighTemp();
String cl_local_low = thisDay.getCLocalLowTemp();
String cl_local_prec = thisDay.getCLocalPrecCat();
String cl_local_snow = thisDay.getCLocalSnowCat();
String cl_float_high = thisDay.getCFloaterHighTemp();
String cl_float_low = thisDay.getCFloaterLowTemp();
String cl_float_prec = thisDay.getCFloaterPrecCat();
String cl_float_snow = thisDay.getCFloaterSnowCat();
String u_local_high = null;
String u_local_low = null;
String u_local_prec = null;
String u_local_snow = null;
String u_float_high = null;
String u_float_low = null;
String u_float_prec = null;
String u_float_snow = null;
while ( students.next() ) {
String thisUserID = students.getString("username");
String thisUserName = students.getString("realname");
ResultSet userForecast = dbInterface.callDB("SELECT * from forecasts WHERE "
+" day = '"+sqlDate+"' and portfolio = '"+ portfolio +"' and "
+" userid = '"+ thisUserID +"' ");
if ( userForecast.next() ) {
u_local_high = userForecast.getString("local_high");
u_local_low = userForecast.getString("local_low");
u_local_prec = userForecast.getString("local_prec");
u_local_snow = userForecast.getString("local_snow");
u_float_high = userForecast.getString("float_high");
u_float_low = userForecast.getString("float_low");
u_float_prec = userForecast.getString("float_prec");
u_float_snow = userForecast.getString("float_snow");
} else {
dbInterface.updateDB("INSERT into forecasts (userid, portfolio, day, local_high, "
+" local_low, local_prec, local_snow, float_high, float_low, float_prec, "
+" float_snow, type) VALUES ('"+ thisUserID +"', '"+ portfolio +"', "
+" '"+ sqlDate +"', '"+ cl_local_high +"', '"+ cl_local_low +"', "
+" '"+ cl_local_prec +"', '"+ cl_local_snow +"', '"+ cl_float_high +"' , "
+" '"+ cl_float_low +"', '"+ cl_float_prec +"', '"+ cl_float_snow +"', 'c' ) ");
u_local_high = cl_local_high;
u_local_low = cl_local_low;
u_local_prec = cl_local_prec;
u_local_snow = cl_local_snow;
u_float_high = cl_float_high;
u_float_low = cl_float_low;
u_float_prec = cl_float_prec;
u_float_snow = cl_float_snow;
}
Integer local_high_err = new Integer( gradeTemp( local_high, u_local_high ) );
Integer local_low_err = new Integer( gradeTemp( local_low, u_local_low ) );
Integer local_prec_err = new Integer( gradePrec( local_prec, u_local_prec ) );
Integer local_snow_err = new Integer( gradePrec( local_snow, u_local_snow ) );
Integer float_high_err = new Integer( gradeTemp( float_high, u_float_high ) );
Integer float_low_err = new Integer( gradeTemp( float_low, u_float_low ) );
Integer float_prec_err = new Integer( gradePrec( float_prec, u_float_prec ) );
Integer float_snow_err = new Integer( gradePrec( float_snow, u_float_snow ) );
Integer local_err = new Integer( local_high_err.intValue() + local_low_err.intValue()
+ local_prec_err.intValue() + local_snow_err.intValue() );
Integer float_err = new Integer( float_high_err.intValue() + float_low_err.intValue()
+ float_prec_err.intValue() + float_snow_err.intValue() );
Integer total_err = new Integer( local_err.intValue() + float_err.intValue() );
dbInterface.updateDB("DELETE from forecast_grades WHERE "
+" portfolio = '"+ portfolio +"' and day = '"+ sqlDate +"' "
+" and userid = '"+ thisUserID +"' ");
dbInterface.updateDB("INSERT into forecast_grades ( userid, portfolio, day, local_high, "
+" local_low, local_prec, local_snow, local_err, float_high, float_low, float_prec, "
+" float_snow, float_err, total_err, case_group) VALUES ('"+ thisUserID +"', '"+ portfolio +"', "
+" '"+ sqlDate +"', '"+ local_high_err.toString() +"', '"+ local_low_err.toString() +"', "
+" '"+ local_prec_err.toString() +"', '"+ local_snow_err.toString() +"', "
+" "+ local_err.toString() +", '"+ float_high_err.toString() +"' , "
+" "+ float_low_err.toString() +", '"+ float_prec_err.toString() +"', "
+" "+ float_snow_err.toString() +", "+ float_err.toString() +", "
+" "+ total_err.toString() +", "+ caseGroup +" ) ");
sbuf.append("<BR>Done grading user: "+ thisUserName +"\n");
}
} else {
sbuf.append("<P>Verification not done, since none has been entered.");
}
return sbuf.toString();
} // End of gradeForecasts()
public static String gradePrec( String answer, String guess) {
if ( answer.equals("9") && ( guess.equals("0") || guess.equals("1") ) )
return "0";
if ( answer.equals("8") && ( guess.equals("1") || guess.equals("2") ) )
return "0";
if ( answer.equals("7") && ( guess.equals("2") || guess.equals("3") ) )
return "0";
if ( answer.equals("6") && ( guess.equals("3") || guess.equals("4") ) )
return "0";
if ( answer.equals( guess ) )
return "0";
if ( answer.equals("7") && ( guess.equals("0") || guess.equals("1") ) )
answer = "2";
else if ( answer.equals("6") && ( guess.equals("5") ) )
answer = "4";
else if ( answer.equals("6") && ( guess.equals("0") || guess.equals("1") || guess.equals("2")) )
answer = "3";
else if ( answer.equals("7") && ( guess.equals("4") || guess.equals("5") ) )
answer = "3";
else if ( answer.equals("8") && ( guess.equals("0") ) )
answer = "1";
else if ( answer.equals("8") && ( guess.equals("3") || guess.equals("4") || guess.equals("5") ) )
answer = "2";
else if ( answer.equals("9") )
answer = "1";
Integer answerInt = new java.lang.Integer( answer );
Integer guessInt = new java.lang.Integer( guess );
return new java.lang.Integer( 4 * java.lang.Math.abs( answerInt.intValue() - guessInt.intValue() ) ).toString();
} // End of gradePrec()
public static String gradeTemp( String answer, String guess) {
Integer answerInt = new java.lang.Integer( answer );
Integer guessInt = new java.lang.Integer( guess );
return new java.lang.Integer( java.lang.Math.abs( answerInt.intValue() - guessInt.intValue() ) ).toString();
}
} // End of fLib
| UTF-8 | Java | 28,071 | java | 4_3a26e41d86b893420514b569263893fa3a48af20_fLib_t.java | Java | [
{
"context": "\n * Copyright 2001-2005 Iowa State University\n * jportfolio@collaborium.org\n *\n * This library is free software; you can re",
"end": 81,
"score": 0.9999173283576965,
"start": 55,
"tag": "EMAIL",
"value": "jportfolio@collaborium.org"
},
{
"context": "ngs for the ... | null | [] | /**
* Copyright 2001-2005 Iowa State University
* <EMAIL>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Forecast Library full of needed things for the forecast exercise
*
*
* @author <NAME> 26 July 2001
*/
package org.collaborium.portfolio.forecast;
import org.collaborium.portfolio.*;
import java.sql.*;
public class fLib {
/**
* Method that prints out a simple SELECT box
* for the years available
*/
public static String yearSelect() {
StringBuffer sbuf = new StringBuffer();
sbuf.append(" <SELECT name=\"year\">\n"
//+" <option value=\"2000\">2000\n"
+" <option value=\"2001\">2001\n"
+" <option value=\"2002\">2002\n"
+" <option value=\"2003\">2003\n"
+" <option value=\"2004\">2004\n"
+" <option value=\"2005\">2005\n"
+" <option value=\"2006\">2006\n"
+" <option value=\"2007\">2007\n"
+" <option value=\"2008\">2008\n"
+" <option value=\"2009\">2009\n"
+" <option value=\"2010\">2010\n"
+" <option value=\"2011\">2011\n"
+" <option value=\"2012\">2012\n"
+" <option value=\"2013\">2013\n"
+" <option value=\"2014\">2014\n"
+" <option value=\"2015\" SELECTED>2015\n"
+" </SELECT>\n");
return sbuf.toString();
} // End of yearSelect()
/**
* Method that prints out a simple SELECT box
* for the months available
*/
public static String monthSelect() {
StringBuffer sbuf = new StringBuffer();
sbuf.append(" <SELECT name=\"month\">\n"
+" <option value=\"1\">January\n"
+" <option value=\"2\">Feburary\n"
+" <option value=\"3\">March\n"
+" <option value=\"4\">April\n"
+" <option value=\"5\">May\n"
+" <option value=\"6\">June\n"
+" <option value=\"7\">July\n"
+" <option value=\"8\">August\n"
+" <option value=\"9\">September\n"
+" <option value=\"10\">October\n"
+" <option value=\"11\">November\n"
+" <option value=\"12\">December\n"
+" </SELECT>\n");
return sbuf.toString();
} // End of monthSelect()
/**
* Protoype to whichDay()
*/
public static String whichDay(String portfolio, String callMode,
String thisPageURL) throws SQLException {
return whichDay(portfolio, callMode, thisPageURL, "1970-01-01");
}
/**
* Generic method to get the user to select a date
* @param portfolio which is the Current Portfolio
* @param callMode value to send back to the CGI server
* @param thisPageURL value of the page to reference in the form
* @return HTMLformated string
*/
public static String whichDay(String portfolio, String callMode,
String thisPageURL, String selectedDate) throws SQLException {
StringBuffer sbuf = new StringBuffer();
ResultSet forecastDays = dbInterface.callDB("SELECT * from forecast_days "
+" WHERE portfolio = '"+ portfolio +"' "
+" and day <= CURRENT_TIMESTAMP::date ORDER by day ASC ");
sbuf.append("<FORM METHOD=\"GET\" ACTION=\""+thisPageURL+"\" name=\"f\">\n"
+"<input type=\"hidden\" name=\"mode\" value=\""+callMode+"\">\n"
+"<input type=\"hidden\" name=\"portfolio\" value=\""+portfolio+"\">\n"
+"<table border=0><tr><th>Forecast Date:</th>\n"
+"<td><SELECT NAME=\"sqlDate\">\n");
while ( forecastDays.next() ) {
String thisDate = forecastDays.getString("day");
sbuf.append("<OPTION VALUE=\""+thisDate+"\" ");
if (thisDate.equals(selectedDate)) sbuf.append("SELECTED");
sbuf.append(">"+thisDate+"\n");
}
sbuf.append("</SELECT></td><td>\n"
+"<INPUT TYPE=\"SUBMIT\" VALUE=\"Select Fx Date\">\n"
+"</td></tr></table>"
+"</FORM>\n");
return sbuf.toString();
}
/**
* Method that prints out a simple SELECT box
* for the months available
*/
public static String daySelect() {
StringBuffer sbuf = new StringBuffer();
sbuf.append(" <SELECT name=\"day\">\n");
for (int i = 1; i < 32; i++)
sbuf.append(" <option value="+i+">"+i+"\n");
sbuf.append(" </SELECT>\n");
return sbuf.toString();
} // End of daySelect()
/**
* Method that prints out the results for the last forecast
* @param portfolio value of the current portfolio
* @param sqlDate which is the value of the date wanted
* @param sortCol self-explainatory
* @param thisPageURL value of the current pageURL
*/
public static String forecastResults(String portfolio, String sqlDate,
String sortCol, String thisPageURL)
throws myException, SQLException {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<H3>Previous Forecast Results:</H3>\n");
/** If no date is specified, lets then see if the last answers works**/
if (sqlDate == null) {
ResultSet availDates = dbInterface.callDB("SELECT day "
+"from forecast_answers WHERE portfolio = '"+ portfolio +"' "
+" ORDER by day DESC LIMIT 1");
if ( availDates.next() ) {
sqlDate = availDates.getString("day");
} else {
throw new myException("No days available to view results for!");
}
}
sbuf.append( whichDay( portfolio, "l", thisPageURL, sqlDate ) );
/** We need to get results from the database **/
forecastDay thisDay = new forecastDay(portfolio, sqlDate);
thisDay.getValidation();
thisDay.getClimo();
if (sortCol == null) {
sortCol = "total_err";
}
sbuf.append( thisDay.catAnswers() );
sbuf.append("<BR><LI>Table Sorted by: "+ sortCol+"</LI>");
/** Now we have a date, lets get how the kids forecasted **/
ResultSet forecasts = dbInterface.callDB("SELECT "
+" getUserName(userid) as realname, * from forecast_grades "
+" WHERE portfolio = '"+ portfolio +"' "
+" and day = '"+ sqlDate +"' order by "+sortCol+" ");
sbuf.append("<P><TABLE>\n"
+"<TR>\n"
+" <TH rowspan=\"2\">Forecaster:</TH>\n"
+" <TH colspan=\"5\">Local Site:</TH>\n"
+" <TD rowspan=\"2\"></TD>\n"
+" <TH colspan=\"5\">Floater Site:</TH>\n"
+" <TH colspan=\"2\" rowspan=\"2\">\n"
+" <a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=total_err\">Total:</a></TH>\n"
+"</TR>\n"
+"<TR>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=local_err\">Tot:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=l&sqlDate="+sqlDate+"&sort=float_err\">Tot:</a></TH>\n"
+"</TR>\n");
int i = 0;
while ( forecasts.next() ) {
if (i % 2 == 0 )
sbuf.append("<TR bgcolor=\"#EEEEEE\">\n");
else
sbuf.append("<TR>\n");
sbuf.append("<TD>"+ forecasts.getString("realname") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("float_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("total_err") +"</TD>\n");
sbuf.append("</TR>\n");
i = i +1;
} // End of while()
sbuf.append("</TABLE>\n");
return sbuf.toString();
} // End of lastForecastResults()
/**
* Method that prints out the results for the last forecast
* @param portfolio value of the current portfolio
* @param sqlDate which is the value of the date wanted
* @param sortCol self-explainatory
* @param thisPageURL value of the current pageURL
*/
public static String cumulativeResults(String portfolio, String sortCol, String thisPageURL)
throws myException, SQLException {
StringBuffer sbuf = new StringBuffer();
if ( sortCol == null )
sortCol = "final_tot";
/** Now we have a date, lets get how the kids forecasted **/
ResultSet forecasts = dbInterface.callDB("SELECT getUserName(userid) as realname, *, "
+" (p0_total+ p1_total + p2_total + p3_total) AS final_tot from forecast_totals "
+" WHERE portfolio = '"+portfolio+"' "
+" order by "+sortCol+" ");
sbuf.append("<TABLE>\n"
+"<TR>\n"
+" <TH rowspan=\"2\">Forecaster:</TH>\n"
+" <TH colspan=\"5\">Local Site:</TH>\n"
+" <TD rowspan=\"2\"></TD>\n"
+" <TH colspan=\"5\">Floater Site:</TH>\n"
+" <TD rowspan=\"2\"></TD>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p0_total\">p0</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p1_total\">p1</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p2_total\">p2</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=p3_total\">p3</a></TH>\n"
+" <TH rowspan=\"2\"><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sortfinal_total\">Cum Total</a></TH>\n"
+"</TR>\n"
+"<TR>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=local_err\">Tot:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_high\">High:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_low\">Low:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_prec\">Prec:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_snow\">Snow:</a></TH>\n"
+"<TH><a href=\""+thisPageURL+"?portfolio="+portfolio+"&mode=c&sort=float_err\">Tot:</a></TH>\n"
+"</TR>\n");
int i = 0;
while ( forecasts.next() ) {
if (i % 2 == 0 )
sbuf.append("<TR bgcolor=\"#EEEEEE\">\n");
else
sbuf.append("<TR>\n");
sbuf.append("<TD>"+ forecasts.getString("realname") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("local_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("float_high") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_low") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_prec") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_snow") +"</TD>\n"
+"<TD>"+ forecasts.getString("float_err") +"</TD>\n"
+"<TD></TD>\n"
+"<TD>"+ forecasts.getString("p0_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("p1_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("p2_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("p3_total") +"</TD>\n"
+"<TD>"+ forecasts.getString("final_tot") +"</TD>\n");
sbuf.append("</TR>\n");
i = i + 1;
} // End of while()
sbuf.append("</TABLE>\n");
return sbuf.toString();
} // End of cumulativeResults()
public static String adminRainSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='9' ");
if ( selected.equalsIgnoreCase("9") ) sbuf.append("SELECTED");
sbuf.append(">CAT 9 | Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 0.05\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 0.06 - 0.25\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 0.26 - 0.50\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 0.51 - 1.00\n");
sbuf.append("<option value='5' ");
if ( selected.equalsIgnoreCase("5") ) sbuf.append("SELECTED");
sbuf.append(">CAT 5 | 1.01 +\n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of rainSelect()
public static String rainSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 0.05\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 0.06 - 0.25\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 0.26 - 0.50\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 0.51 - 1.00\n");
sbuf.append("<option value='5' ");
if ( selected.equalsIgnoreCase("5") ) sbuf.append("SELECTED");
sbuf.append(">CAT 5 | 1.01 +\n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of rainSelect()
public static String adminSnowSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='9' ");
if ( selected.equalsIgnoreCase("9") ) sbuf.append("SELECTED");
sbuf.append(">CAT 9 | Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 2\"\n");
sbuf.append("<option value='8' ");
if ( selected.equalsIgnoreCase("8") ) sbuf.append("SELECTED");
sbuf.append(">CAT 8 | 2\"\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 2\" - 4\"\n");
sbuf.append("<option value='7' ");
if ( selected.equalsIgnoreCase("7") ) sbuf.append("SELECTED");
sbuf.append(">CAT 7 | 4\"\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 4\"- 8\"\n");
sbuf.append("<option value='6' ");
if ( selected.equalsIgnoreCase("6") ) sbuf.append("SELECTED");
sbuf.append(">CAT 6 | 8\"\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 8\" + \n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of snowSelect()
public static String snowSelect(String selectName, String selected) {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<SELECT name='"+selectName+"'>\n");
sbuf.append("<option value='0' ");
if ( selected.equalsIgnoreCase("0") ) sbuf.append("SELECTED");
sbuf.append(">CAT 0 | 0 - Trace\n");
sbuf.append("<option value='1' ");
if ( selected.equalsIgnoreCase("1") ) sbuf.append("SELECTED");
sbuf.append(">CAT 1 | Trace - 2\"\n");
sbuf.append("<option value='2' ");
if ( selected.equalsIgnoreCase("2") ) sbuf.append("SELECTED");
sbuf.append(">CAT 2 | 2\" - 4\"\n");
sbuf.append("<option value='3' ");
if ( selected.equalsIgnoreCase("3") ) sbuf.append("SELECTED");
sbuf.append(">CAT 3 | 4\"- 8\"\n");
sbuf.append("<option value='4' ");
if ( selected.equalsIgnoreCase("4") ) sbuf.append("SELECTED");
sbuf.append(">CAT 4 | 8\" + \n");
sbuf.append("</SELECT>\n");
return sbuf.toString();
} // End of snowSelect()
public static String totalForecastErrors( String portfolio )
throws SQLException {
StringBuffer sbuf = new StringBuffer();
dbInterface.updateDB("DELETE from forecast_totals WHERE portfolio = '"+ portfolio +"' ");
/** Total all forecasts first */
dbInterface.updateDB("INSERT into forecast_totals ( SELECT userid, portfolio, sum(local_high), "
+" sum(local_low), sum(local_prec), sum(local_snow), sum(local_err), sum(float_high), "
+" sum(float_low), sum(float_prec), sum(float_snow), sum(float_err) from "
+" forecast_grades WHERE portfolio = '"+ portfolio +"' "
+" GROUP by userid, portfolio ) ");
ResultSet students = dbInterface.callDB("SELECT getUserName( username) as realname, "
+" username from students "
+" WHERE portfolio = '"+ portfolio +"' and nofx = 'n' ");
while ( students.next() ) {
String thisUserID = students.getString("username");
dbInterface.updateDB("UPDATE forecast_totals SET "
+" p0_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 0) , "
+" p1_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 1) , "
+" p2_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 2), "
+" p3_total = totalErrorByCase('"+ thisUserID+"', '"+ portfolio +"', 3) "
+" WHERE userid = '"+ thisUserID +"' and portfolio = '"+ portfolio +"' ");
}
/** Now we need to update Null values, hack! */
dbInterface.updateDB("update forecast_totals SET p1_total = 0 WHERE portfolio = '"+ portfolio +"' and p1_total IS NULL");
dbInterface.updateDB("update forecast_totals SET p2_total = 0 WHERE portfolio = '"+ portfolio +"' and p2_total IS NULL");
dbInterface.updateDB("update forecast_totals SET p3_total = 0 WHERE portfolio = '"+ portfolio +"' and p3_total IS NULL");
sbuf.append("Done Totalling Forecasts!");
return sbuf.toString();
}
/**
* gradeForecasts() does the automated grading of the entered forecasts
* @param portfolio which is the current Portfolio
* @param sqlDate which is the forecast Date we will be verifying
* @return String data
*/
public static String gradeForecasts( String portfolio, String sqlDate )
throws SQLException {
StringBuffer sbuf = new StringBuffer();
dbInterface.updateDB("DELETE from forecast_grades WHERE "
+" day = '"+ sqlDate +"' and portfolio = '"+ portfolio +"' ");
ResultSet students = dbInterface.callDB("SELECT "
+" getUserName( username) as realname, username from students "
+" WHERE portfolio = '"+ portfolio +"' and nofx = 'n' ");
forecastDay thisDay = new forecastDay(portfolio, sqlDate);
if (thisDay.getValidation()) {
thisDay.getClimo();
String caseGroup = thisDay.getCaseGroup();
String local_high = thisDay.getVLocalHighTemp();
String local_low = thisDay.getVLocalLowTemp();
String local_prec = thisDay.getVLocalPrecCat();
String local_snow = thisDay.getVLocalSnowCat();
String float_high = thisDay.getVFloaterHighTemp();
String float_low = thisDay.getVFloaterLowTemp();
String float_prec = thisDay.getVFloaterPrecCat();
String float_snow = thisDay.getVFloaterSnowCat();
String cl_local_high = thisDay.getCLocalHighTemp();
String cl_local_low = thisDay.getCLocalLowTemp();
String cl_local_prec = thisDay.getCLocalPrecCat();
String cl_local_snow = thisDay.getCLocalSnowCat();
String cl_float_high = thisDay.getCFloaterHighTemp();
String cl_float_low = thisDay.getCFloaterLowTemp();
String cl_float_prec = thisDay.getCFloaterPrecCat();
String cl_float_snow = thisDay.getCFloaterSnowCat();
String u_local_high = null;
String u_local_low = null;
String u_local_prec = null;
String u_local_snow = null;
String u_float_high = null;
String u_float_low = null;
String u_float_prec = null;
String u_float_snow = null;
while ( students.next() ) {
String thisUserID = students.getString("username");
String thisUserName = students.getString("realname");
ResultSet userForecast = dbInterface.callDB("SELECT * from forecasts WHERE "
+" day = '"+sqlDate+"' and portfolio = '"+ portfolio +"' and "
+" userid = '"+ thisUserID +"' ");
if ( userForecast.next() ) {
u_local_high = userForecast.getString("local_high");
u_local_low = userForecast.getString("local_low");
u_local_prec = userForecast.getString("local_prec");
u_local_snow = userForecast.getString("local_snow");
u_float_high = userForecast.getString("float_high");
u_float_low = userForecast.getString("float_low");
u_float_prec = userForecast.getString("float_prec");
u_float_snow = userForecast.getString("float_snow");
} else {
dbInterface.updateDB("INSERT into forecasts (userid, portfolio, day, local_high, "
+" local_low, local_prec, local_snow, float_high, float_low, float_prec, "
+" float_snow, type) VALUES ('"+ thisUserID +"', '"+ portfolio +"', "
+" '"+ sqlDate +"', '"+ cl_local_high +"', '"+ cl_local_low +"', "
+" '"+ cl_local_prec +"', '"+ cl_local_snow +"', '"+ cl_float_high +"' , "
+" '"+ cl_float_low +"', '"+ cl_float_prec +"', '"+ cl_float_snow +"', 'c' ) ");
u_local_high = cl_local_high;
u_local_low = cl_local_low;
u_local_prec = cl_local_prec;
u_local_snow = cl_local_snow;
u_float_high = cl_float_high;
u_float_low = cl_float_low;
u_float_prec = cl_float_prec;
u_float_snow = cl_float_snow;
}
Integer local_high_err = new Integer( gradeTemp( local_high, u_local_high ) );
Integer local_low_err = new Integer( gradeTemp( local_low, u_local_low ) );
Integer local_prec_err = new Integer( gradePrec( local_prec, u_local_prec ) );
Integer local_snow_err = new Integer( gradePrec( local_snow, u_local_snow ) );
Integer float_high_err = new Integer( gradeTemp( float_high, u_float_high ) );
Integer float_low_err = new Integer( gradeTemp( float_low, u_float_low ) );
Integer float_prec_err = new Integer( gradePrec( float_prec, u_float_prec ) );
Integer float_snow_err = new Integer( gradePrec( float_snow, u_float_snow ) );
Integer local_err = new Integer( local_high_err.intValue() + local_low_err.intValue()
+ local_prec_err.intValue() + local_snow_err.intValue() );
Integer float_err = new Integer( float_high_err.intValue() + float_low_err.intValue()
+ float_prec_err.intValue() + float_snow_err.intValue() );
Integer total_err = new Integer( local_err.intValue() + float_err.intValue() );
dbInterface.updateDB("DELETE from forecast_grades WHERE "
+" portfolio = '"+ portfolio +"' and day = '"+ sqlDate +"' "
+" and userid = '"+ thisUserID +"' ");
dbInterface.updateDB("INSERT into forecast_grades ( userid, portfolio, day, local_high, "
+" local_low, local_prec, local_snow, local_err, float_high, float_low, float_prec, "
+" float_snow, float_err, total_err, case_group) VALUES ('"+ thisUserID +"', '"+ portfolio +"', "
+" '"+ sqlDate +"', '"+ local_high_err.toString() +"', '"+ local_low_err.toString() +"', "
+" '"+ local_prec_err.toString() +"', '"+ local_snow_err.toString() +"', "
+" "+ local_err.toString() +", '"+ float_high_err.toString() +"' , "
+" "+ float_low_err.toString() +", '"+ float_prec_err.toString() +"', "
+" "+ float_snow_err.toString() +", "+ float_err.toString() +", "
+" "+ total_err.toString() +", "+ caseGroup +" ) ");
sbuf.append("<BR>Done grading user: "+ thisUserName +"\n");
}
} else {
sbuf.append("<P>Verification not done, since none has been entered.");
}
return sbuf.toString();
} // End of gradeForecasts()
public static String gradePrec( String answer, String guess) {
if ( answer.equals("9") && ( guess.equals("0") || guess.equals("1") ) )
return "0";
if ( answer.equals("8") && ( guess.equals("1") || guess.equals("2") ) )
return "0";
if ( answer.equals("7") && ( guess.equals("2") || guess.equals("3") ) )
return "0";
if ( answer.equals("6") && ( guess.equals("3") || guess.equals("4") ) )
return "0";
if ( answer.equals( guess ) )
return "0";
if ( answer.equals("7") && ( guess.equals("0") || guess.equals("1") ) )
answer = "2";
else if ( answer.equals("6") && ( guess.equals("5") ) )
answer = "4";
else if ( answer.equals("6") && ( guess.equals("0") || guess.equals("1") || guess.equals("2")) )
answer = "3";
else if ( answer.equals("7") && ( guess.equals("4") || guess.equals("5") ) )
answer = "3";
else if ( answer.equals("8") && ( guess.equals("0") ) )
answer = "1";
else if ( answer.equals("8") && ( guess.equals("3") || guess.equals("4") || guess.equals("5") ) )
answer = "2";
else if ( answer.equals("9") )
answer = "1";
Integer answerInt = new java.lang.Integer( answer );
Integer guessInt = new java.lang.Integer( guess );
return new java.lang.Integer( 4 * java.lang.Math.abs( answerInt.intValue() - guessInt.intValue() ) ).toString();
} // End of gradePrec()
public static String gradeTemp( String answer, String guess) {
Integer answerInt = new java.lang.Integer( answer );
Integer guessInt = new java.lang.Integer( guess );
return new java.lang.Integer( java.lang.Math.abs( answerInt.intValue() - guessInt.intValue() ) ).toString();
}
} // End of fLib
| 28,044 | 0.60607 | 0.590503 | 690 | 39.68116 | 30.03915 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.815942 | false | false | 9 |
db017c20e0ae6316d9f647fcc022f855cf900140 | 5,437,428,649,151 | b66324d16c6d30877ae7cdec435fb9c7d2a1bf98 | /aplicaciones/misPruebas/ejerciciosABC.java | f40e223ed0c6089c5c7d4958babb7e7420cad9c3 | [] | no_license | ecoresjr/eda | https://github.com/ecoresjr/eda | c472d31c8311c33ca8f7e5fa54520228bb60e41b | 22a3d43ca5d3b3de2437763d35bb60452466b5ba | refs/heads/master | 2018-09-30T12:32:55.922000 | 2018-06-07T18:43:53 | 2018-06-07T18:43:53 | 136,049,091 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aplicaciones.misPruebas;
import librerias.estructurasDeDatos.jerarquicos.*;
/**
* Write a description of class ejerciciosABC here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ejerciciosABC
{
public static void main (String args[]){
ABCDinamic<Integer> arbre=new ABCDinamic<Integer>();
for(int i=0;i<1000;i++){
arbre.inserir(i);
}
arbre.cercar(363);
}
}
| UTF-8 | Java | 458 | java | ejerciciosABC.java | Java | [] | null | [] | package aplicaciones.misPruebas;
import librerias.estructurasDeDatos.jerarquicos.*;
/**
* Write a description of class ejerciciosABC here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ejerciciosABC
{
public static void main (String args[]){
ABCDinamic<Integer> arbre=new ABCDinamic<Integer>();
for(int i=0;i<1000;i++){
arbre.inserir(i);
}
arbre.cercar(363);
}
}
| 458 | 0.639738 | 0.622271 | 20 | 21.9 | 19.429102 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 9 |
8c0ab818ca2474850f86560ea6d49fff34f535bf | 14,181,982,075,091 | e1811965b16dc6eabe864d293ee36f8e05a690e9 | /src/main/java/com/pxxy/mapper/CostMapper.java | 5920ddad4d47bb0c35a8cf5b6d786396c0d55521 | [] | no_license | ZhongChenBiao/netctoss | https://github.com/ZhongChenBiao/netctoss | 137f83600ee8dd0d9b200e047787feb3b8565933 | 46d04fcb0759cb0b3510982a1afbfb11a40b41cd | refs/heads/main | 2023-04-08T16:55:10.288000 | 2021-03-30T06:48:26 | 2021-03-30T06:48:26 | 352,893,538 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pxxy.mapper;
import org.springframework.stereotype.Repository;
/**
* @Descricption:资费的持久层接口
* @Author:江灿
* @Date:Create in 11:21 2019/5/29
*/
@Repository()
public interface CostMapper {
}
| UTF-8 | Java | 226 | java | CostMapper.java | Java | [
{
"context": "sitory;\n\n/**\n * @Descricption:资费的持久层接口\n * @Author:江灿\n * @Date:Create in 11:21 2019/5/29\n */\n@Repositor",
"end": 120,
"score": 0.8706650137901306,
"start": 118,
"tag": "NAME",
"value": "江灿"
}
] | null | [] | package com.pxxy.mapper;
import org.springframework.stereotype.Repository;
/**
* @Descricption:资费的持久层接口
* @Author:江灿
* @Date:Create in 11:21 2019/5/29
*/
@Repository()
public interface CostMapper {
}
| 226 | 0.728155 | 0.674757 | 12 | 16.166666 | 15.328804 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 9 |
d66a1c49022f75c9015f443b24363bd3a2f4acf1 | 30,863,634,995,507 | 7319ea376b1bd95b0aded7c4dcd832203aa1b820 | /test/integration/src/test/java/com/liferay/faces/bridge/test/integration/demo/PrimePushCDICounterPortletTester.java | 9d65412f63a5e4abc212170bb3c4d7b3e41c8992 | [
"Apache-2.0"
] | permissive | juangon/liferay-faces-bridge-impl | https://github.com/juangon/liferay-faces-bridge-impl | b89ea747753c2947fafb53367cf5e1785463bf0d | 2a71bfbe081dcab7027d71c5e278aecbdc64255f | refs/heads/master | 2021-01-21T16:09:33.551000 | 2018-04-03T13:51:15 | 2018-04-05T16:12:25 | 43,823,439 | 0 | 0 | null | true | 2015-10-07T14:58:50 | 2015-10-07T14:58:49 | 2015-09-09T13:19:15 | 2015-10-05T14:59:56 | 1,599 | 0 | 0 | 0 | null | null | null | /**
* Copyright (c) 2000-2017 Liferay, Inc. 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liferay.faces.bridge.test.integration.demo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import com.liferay.faces.bridge.test.integration.BridgeTestUtil;
import com.liferay.faces.test.selenium.browser.BrowserDriver;
import com.liferay.faces.test.selenium.browser.BrowserDriverFactory;
import com.liferay.faces.test.selenium.browser.BrowserDriverManagingTesterBase;
import com.liferay.faces.test.selenium.browser.TestUtil;
import com.liferay.faces.test.selenium.browser.WaitingAsserter;
import com.liferay.faces.test.selenium.browser.WaitingAsserterFactory;
/**
* @author Kyle Stiemann
*/
public class PrimePushCDICounterPortletTester extends BrowserDriverManagingTesterBase {
// Private Data Members
private BrowserDriver browserDriver2;
@Test
public void runPrimePushCDICounterPortletTest() {
BrowserDriver browserDriver1 = getBrowserDriver();
String primePushCDICounterURL = BridgeTestUtil.getDemoPageURL("primepush-cdi-counter");
browserDriver1.navigateWindowTo(primePushCDICounterURL);
browserDriver2.navigateWindowTo(primePushCDICounterURL);
// Test that the initial count value is the same in both browsers.
String countDisplayXpath = "//span[contains(@id,':countDisplay')]";
WebElement countDisplayElement = browserDriver1.findElementByXpath(countDisplayXpath);
String countString = countDisplayElement.getText().trim();
WaitingAsserter waitingAsserter2 = WaitingAsserterFactory.getWaitingAsserter(browserDriver2);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
int count = Integer.parseInt(countString);
// Click the increment button in the first browser and test that the count has been incremented in both
// browsers.
String incrementCounterButtonXpath = "//button[contains(@id,':incrementCounter')]";
browserDriver1.clickElement(incrementCounterButtonXpath);
count++;
WaitingAsserter waitingAsserter1 = getWaitingAsserter();
countString = Integer.toString(count);
waitingAsserter1.assertTextPresentInElement(countString, countDisplayXpath);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
// Click the increment button in the second browser and test that the count has been incremented in both
// browsers.
browserDriver2.clickElement(incrementCounterButtonXpath);
count++;
countString = Integer.toString(count);
waitingAsserter1.assertTextPresentInElement(countString, countDisplayXpath);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
// Click the increment button 10 times in the first browser and test that the count is accurate in both
// browsers.
for (int i = 0; i < 10; i++) {
browserDriver1.clickElement(incrementCounterButtonXpath);
count++;
}
countString = Integer.toString(count);
waitingAsserter1.assertTextPresentInElement(countString, countDisplayXpath);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
}
@Before
public void setUpBrowserDriver2() {
browserDriver2 = BrowserDriverFactory.getBrowserDriver();
TestUtil.signIn(browserDriver2);
}
@After
public void tearDownBrowserDriver2() {
if (browserDriver2 != null) {
browserDriver2.quit();
browserDriver2 = null;
}
}
}
| UTF-8 | Java | 3,943 | java | PrimePushCDICounterPortletTester.java | Java | [
{
"context": ".browser.WaitingAsserterFactory;\n\n\n/**\n * @author Kyle Stiemann\n */\npublic class PrimePushCDICounterPortletTester",
"end": 1296,
"score": 0.9996979832649231,
"start": 1283,
"tag": "NAME",
"value": "Kyle Stiemann"
}
] | null | [] | /**
* Copyright (c) 2000-2017 Liferay, Inc. 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liferay.faces.bridge.test.integration.demo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import com.liferay.faces.bridge.test.integration.BridgeTestUtil;
import com.liferay.faces.test.selenium.browser.BrowserDriver;
import com.liferay.faces.test.selenium.browser.BrowserDriverFactory;
import com.liferay.faces.test.selenium.browser.BrowserDriverManagingTesterBase;
import com.liferay.faces.test.selenium.browser.TestUtil;
import com.liferay.faces.test.selenium.browser.WaitingAsserter;
import com.liferay.faces.test.selenium.browser.WaitingAsserterFactory;
/**
* @author <NAME>
*/
public class PrimePushCDICounterPortletTester extends BrowserDriverManagingTesterBase {
// Private Data Members
private BrowserDriver browserDriver2;
@Test
public void runPrimePushCDICounterPortletTest() {
BrowserDriver browserDriver1 = getBrowserDriver();
String primePushCDICounterURL = BridgeTestUtil.getDemoPageURL("primepush-cdi-counter");
browserDriver1.navigateWindowTo(primePushCDICounterURL);
browserDriver2.navigateWindowTo(primePushCDICounterURL);
// Test that the initial count value is the same in both browsers.
String countDisplayXpath = "//span[contains(@id,':countDisplay')]";
WebElement countDisplayElement = browserDriver1.findElementByXpath(countDisplayXpath);
String countString = countDisplayElement.getText().trim();
WaitingAsserter waitingAsserter2 = WaitingAsserterFactory.getWaitingAsserter(browserDriver2);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
int count = Integer.parseInt(countString);
// Click the increment button in the first browser and test that the count has been incremented in both
// browsers.
String incrementCounterButtonXpath = "//button[contains(@id,':incrementCounter')]";
browserDriver1.clickElement(incrementCounterButtonXpath);
count++;
WaitingAsserter waitingAsserter1 = getWaitingAsserter();
countString = Integer.toString(count);
waitingAsserter1.assertTextPresentInElement(countString, countDisplayXpath);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
// Click the increment button in the second browser and test that the count has been incremented in both
// browsers.
browserDriver2.clickElement(incrementCounterButtonXpath);
count++;
countString = Integer.toString(count);
waitingAsserter1.assertTextPresentInElement(countString, countDisplayXpath);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
// Click the increment button 10 times in the first browser and test that the count is accurate in both
// browsers.
for (int i = 0; i < 10; i++) {
browserDriver1.clickElement(incrementCounterButtonXpath);
count++;
}
countString = Integer.toString(count);
waitingAsserter1.assertTextPresentInElement(countString, countDisplayXpath);
waitingAsserter2.assertTextPresentInElement(countString, countDisplayXpath);
}
@Before
public void setUpBrowserDriver2() {
browserDriver2 = BrowserDriverFactory.getBrowserDriver();
TestUtil.signIn(browserDriver2);
}
@After
public void tearDownBrowserDriver2() {
if (browserDriver2 != null) {
browserDriver2.quit();
browserDriver2 = null;
}
}
}
| 3,936 | 0.793558 | 0.782906 | 106 | 36.198112 | 32.364788 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.509434 | false | false | 9 |
a77801efaee078f2bb7ec59c0ef0405c32d78776 | 28,338,194,237,655 | ce661dbe14b2e0e521121934a99751806508b080 | /library-hzGgrapher/src/main/java/com/handstudio/android/hzgrapherlib/graphview/NYCurveGraphView.java | e5e4e8fa6e71925add46523878cc4371eb137140 | [] | no_license | SageLu/Test | https://github.com/SageLu/Test | 8a21183d6db2cd621f66e828c42bdb6681b9d129 | 5118c68a9a26f937c893f30997e05a27345c7388 | refs/heads/master | 2021-07-06T14:28:39.934000 | 2017-09-28T09:45:54 | 2017-09-28T09:45:54 | 104,848,123 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.handstudio.android.hzgrapherlib.graphview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.canvas.GraphCanvasWrapper;
import com.handstudio.android.hzgrapherlib.error.ErrorCode;
import com.handstudio.android.hzgrapherlib.error.ErrorDetector;
import com.handstudio.android.hzgrapherlib.path.GraphPath;
import com.handstudio.android.hzgrapherlib.util.Spline;
import com.handstudio.android.hzgrapherlib.vo.curvegraph.CurveGraphVO;
/**
* Created by loo on 16-8-4.
* 继承普通view的曲线图
*/
public class NYCurveGraphView extends View {
public static final String TAG = "CurveGraphView";
private SurfaceHolder mHolder;
public DrawThread mDrawThread;
private CurveGraphVO mCurveGraphVO = null;
private Spline spline = null;
private Bitmap content;
//Constructor
public NYCurveGraphView(Context context, CurveGraphVO vo) {
super(context);
mCurveGraphVO = vo;
initView(context, vo);
}
private void initView(Context context, CurveGraphVO vo) {
ErrorCode ec = ErrorDetector.checkGraphObject(vo);
ec.printError();
setBackgroundColor(Color.WHITE);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mDrawThread == null) {
mDrawThread = new DrawThread(mHolder, getContext());
mDrawThread.start();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mDrawThread == null) {
mDrawThread = new DrawThread(mHolder, getContext());
mDrawThread.start();
}
}
private static final Object touchLock = new Object(); // touch synchronize
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (mDrawThread == null) {
return false;
}
if (action == MotionEvent.ACTION_DOWN) {
synchronized (touchLock) {
mDrawThread.isDirty = true;
}
return true;
} else if (action == MotionEvent.ACTION_MOVE) {
synchronized (touchLock) {
mDrawThread.isDirty = true;
}
return true;
} else if (action == MotionEvent.ACTION_UP) {
synchronized (touchLock) {
mDrawThread.isDirty = true;
}
return true;
}
return super.onTouchEvent(event);
}
@Override
public void draw(Canvas canvas) {
if (content != null) {
super.draw(canvas);
canvas.drawBitmap(content, 0, 0, null);
} else
super.draw(canvas);
}
class DrawThread extends Thread {
//final SurfaceHolder mHolder;
Context mCtx;
boolean finishDraw;
boolean isRun = true;
boolean isDirty = true;
int height = getHeight();
int width = getWidth();
//graph length
int xLength = width - (mCurveGraphVO.getPaddingLeft() + mCurveGraphVO.getPaddingRight() + mCurveGraphVO.getMarginRight());
int yLength = height - (mCurveGraphVO.getPaddingBottom() + mCurveGraphVO.getPaddingTop() + mCurveGraphVO.getMarginTop());
//chart length
int chartXLength = width - (mCurveGraphVO.getPaddingLeft() + mCurveGraphVO.getPaddingRight());
Paint p = new Paint();
Paint pCircle = new Paint();
Paint pCurve = new Paint();
Paint pBaseLine = new Paint();
Paint pBaseLineX = new Paint();
TextPaint pMarkText = new TextPaint();
//animation
float anim = 0.0f;
boolean isAnimation = false;
boolean isDrawRegion = false;
long animStartTime = -1;
int animationType = 0;
Bitmap bg = null;
public DrawThread(SurfaceHolder holder, Context context) {
mHolder = holder;
mCtx = context;
content = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
}
public void setRunFlag(boolean bool) {
isRun = bool;
}
@Override
public void run() {
Canvas canvas = null;
GraphCanvasWrapper graphCanvasWrapper = null;
Log.e(TAG, "height = " + height);
Log.e(TAG, "width = " + width);
setPaint();
isAnimation();
isDrawRegion();
finishDraw = false;
canvas = new Canvas(content);
canvas.setBitmap(content);
animStartTime = System.currentTimeMillis();
canvas.drawColor(Color.WHITE);
while (isRun) {
//draw only on dirty mode
if (!isDirty) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
continue;
}
graphCanvasWrapper = new GraphCanvasWrapper(canvas, width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
calcTimePass();
synchronized (touchLock) {
try {
//bg color
finishDraw = true;
// x coord dot Line
drawBaseLine(graphCanvasWrapper);
// x coord
graphCanvasWrapper.drawLine(-50, 0, chartXLength, 0, pCircle);
drawAL((int) graphCanvasWrapper.mMt.calcX(0), (int) graphCanvasWrapper.mMt.calcY(0)
, (int) graphCanvasWrapper.mMt.calcX(chartXLength), (int) graphCanvasWrapper.mMt.calcY(0), canvas);
// x, y coord mark
//drawXMark(graphCanvasWrapper);
// x, y coord text
drawXText(graphCanvasWrapper);
// Draw Graph
drawGraphRegion(graphCanvasWrapper);
drawGraph(graphCanvasWrapper);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (graphCanvasWrapper.getCanvas() != null) {
postInvalidate();
}
}
}
}
}
/**
* 画箭头
*
* @param sx
* @param sy
* @param ex
* @param ey
*/
public void drawAL(int sx, int sy, int ex, int ey, Canvas canvas) {
double H = 8; // 箭头高度
double L = 3.5; // 底边的一半
int x3 = 0;
int y3 = 0;
int x4 = 0;
int y4 = 0;
double awrad = Math.atan(L / H); // 箭头角度
double arraow_len = Math.sqrt(L * L + H * H); // 箭头的长度
double[] arrXY_1 = rotateVec(ex - sx, ey - sy, awrad, true, arraow_len);
double[] arrXY_2 = rotateVec(ex - sx, ey - sy, -awrad, true, arraow_len);
double x_3 = ex - arrXY_1[0]; // (x3,y3)是第一端点
double y_3 = ey - arrXY_1[1];
double x_4 = ex - arrXY_2[0]; // (x4,y4)是第二端点
double y_4 = ey - arrXY_2[1];
Double X3 = new Double(x_3);
x3 = X3.intValue();
Double Y3 = new Double(y_3);
y3 = Y3.intValue();
Double X4 = new Double(x_4);
x4 = X4.intValue();
Double Y4 = new Double(y_4);
y4 = Y4.intValue();
Path triangle = new Path();
triangle.moveTo(ex, ey);
triangle.lineTo(x3, y3);
triangle.lineTo(x4, y4);
triangle.close();
canvas.drawPath(triangle, pCircle);
}
// 计算
public double[] rotateVec(int px, int py, double ang, boolean isChLen, double newLen) {
double mathstr[] = new double[2];
// 矢量旋转函数,参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度
double vx = px * Math.cos(ang) - py * Math.sin(ang);
double vy = px * Math.sin(ang) + py * Math.cos(ang);
if (isChLen) {
double d = Math.sqrt(vx * vx + vy * vy);
vx = vx / d * newLen;
vy = vy / d * newLen;
mathstr[0] = vx;
mathstr[1] = vy;
}
return mathstr;
}
/**
* time calculate
*/
private void calcTimePass() {
if (isAnimation) {
long curTime = System.currentTimeMillis();
long gapTime = curTime - animStartTime;
long animDuration = mCurveGraphVO.getAnimation().getDuration();
if (gapTime >= animDuration)
gapTime = animDuration;
anim = (float) gapTime / (float) animDuration;
} else {
isDirty = false;
}
}
/**
* check graph Curve animation
*/
private void isAnimation() {
if (mCurveGraphVO.getAnimation() != null) {
isAnimation = true;
} else {
isAnimation = false;
}
animationType = mCurveGraphVO.getAnimation().getAnimation();
}
/**
* check graph Curve region animation
*/
private void isDrawRegion() {
if (mCurveGraphVO.isDrawRegion()) {
isDrawRegion = true;
} else {
isDrawRegion = false;
}
}
/**
* draw Base Line
*/
private void drawBaseLine(GraphCanvasWrapper graphCanvas) {
for (int i = 1; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {
float y = yLength * mCurveGraphVO.getIncrement() * i / mCurveGraphVO.getMaxValue();
graphCanvas.drawLine(-50, y, chartXLength, y, pBaseLineX);
}
}
/**
* set graph Curve color
*/
private void setPaint() {
p = new Paint();
p.setFlags(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true); //text anti alias
p.setFilterBitmap(true); // bitmap anti alias
p.setColor(Color.BLUE);
p.setStrokeWidth(3);
p.setStyle(Paint.Style.STROKE);
pCircle = new Paint();
pCircle.setFlags(Paint.ANTI_ALIAS_FLAG);
pCircle.setAntiAlias(true); //text anti alias
pCircle.setFilterBitmap(true); // bitmap anti alias
pCircle.setColor(0xfffb5f5b);
pCircle.setStrokeWidth(3);
pCircle.setStyle(Paint.Style.FILL_AND_STROKE);
pCurve = new Paint();
pCurve.setFlags(Paint.ANTI_ALIAS_FLAG);
pCurve.setAntiAlias(true); //text anti alias
pCurve.setFilterBitmap(true); // bitmap anti alias
pCurve.setShader(new LinearGradient(0, 300f, 0, 0f, Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));
pBaseLine = new Paint();
pBaseLine.setFlags(Paint.ANTI_ALIAS_FLAG);
pBaseLine.setAntiAlias(true); //text anti alias
pBaseLine.setFilterBitmap(true); // bitmap anti alias
pBaseLine.setColor(0xfff0f0f0);
pBaseLine.setStrokeWidth(3);
pBaseLineX = new Paint();
pBaseLineX.setFlags(Paint.ANTI_ALIAS_FLAG);
pBaseLineX.setAntiAlias(true); //text anti alias
pBaseLineX.setFilterBitmap(true); // bitmap anti alias
pBaseLineX.setColor(0xfff0f0f0);
pBaseLineX.setStyle(Paint.Style.FILL);
pMarkText = new TextPaint();
pMarkText.setFlags(Paint.ANTI_ALIAS_FLAG);
pMarkText.setAntiAlias(true); //text anti alias
pMarkText.setColor(0xff646464);
}
/**
* draw Graph Region
*/
private void drawGraphRegion(GraphCanvasWrapper graphCanvas) {
if (isDrawRegion) {
if (isAnimation) {
drawGraphRegionWithAnimation(graphCanvas);
} else {
drawGraphRegionWithoutAnimation(graphCanvas);
}
}
}
/**
* draw Graph
*/
private void drawGraph(GraphCanvasWrapper graphCanvas) {
if (isAnimation) {
drawGraphWithAnimation(graphCanvas);
} else {
drawGraphWithoutAnimation(graphCanvas);
}
}
/**
* draw graph without animation
*/
private void drawGraphRegionWithoutAnimation(GraphCanvasWrapper graphCanvas) {
boolean isDrawRegion = mCurveGraphVO.isDrawRegion();
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath regionPath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
float xGap = xLength / (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
spline = Spline.createMonotoneCubicSpline(x, y);
// draw Region
for (float j = x[0]; j < x[x.length - 1]; j++) {
if (!firstSet) {
regionPath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else
regionPath.lineTo((j + 1), spline.interpolate((j + 1)));
}
if (isDrawRegion) {
regionPath.lineTo(x[x.length - 1], 0);
regionPath.lineTo(0, 0);
Paint pBg = new Paint();
pBg.setFlags(Paint.ANTI_ALIAS_FLAG);
pBg.setAntiAlias(true); //text anti alias
pBg.setFilterBitmap(true); // bitmap anti alias
pBg.setStyle(Paint.Style.FILL);
pBg.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
graphCanvas.getCanvas().drawPath(regionPath, pBg);
}
}
}
/**
* draw graph with animation
*/
private void drawGraphRegionWithAnimation(GraphCanvasWrapper graphCanvas) {
//for draw animation
boolean isDrawRegion = mCurveGraphVO.isDrawRegion();
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath regionPath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
int xl = (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
if (xl == 0)
xl = 1;
float xGap = xLength / xl;
float moveX = 0;
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
if (x == null || y == null || x.length != y.length || x.length < 2)
continue;
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
// draw line
for (float j = x[0]; j <= x[x.length - 1]; j++) {
if (!firstSet) {
regionPath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else {
moveX = j * anim;
regionPath.lineTo(moveX, spline.interpolate(moveX));
}
}
if (isDrawRegion) {
if (animationType == GraphAnimation.CURVE_REGION_ANIMATION_1) {
moveX += xGap * anim;
if (moveX >= xLength) {
moveX = xLength;
}
}
regionPath.lineTo(moveX, 0);
regionPath.lineTo(0, 0);
Paint pBg = new Paint();
pBg.setFlags(Paint.ANTI_ALIAS_FLAG);
pBg.setAntiAlias(true); //text anti alias
pBg.setFilterBitmap(true); // bitmap anti alias
pBg.setStyle(Paint.Style.FILL);
pBg.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
graphCanvas.getCanvas().drawPath(regionPath, pBg);
}
if (anim == 1)
isDirty = false;
}
}
/**
* draw graph without animation
*/
private void drawGraphWithoutAnimation(GraphCanvasWrapper graphCanvas) {
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath curvePath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
float xGap = xLength / (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
// draw line
for (float j = x[0]; j < x[x.length - 1]; j++) {
if (!firstSet) {
curvePath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else
curvePath.lineTo((j + 1), spline.interpolate((j + 1)));
}
// draw point
TextPaint tP = new TextPaint(pMarkText);
tP.setColor(pCircle.getColor());
for (int j = 0; j < mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length; j++) {
float pointX = xGap * j;
float pointY = yLength * mCurveGraphVO.getArrGraph().get(i).getCoordinateArr()[j] / mCurveGraphVO.getMaxValue();
graphCanvas.drawCircle(pointX, pointY, 4, pCircle);
String txt = mCurveGraphVO.getArrGraph().get(i).getCoordinateTitleArr()[j];
int tW = (int) pMarkText.measureText(txt);
tW = tW >> 1;
int tH = getFontHeight(pMarkText.getTextSize());
graphCanvas.drawText(txt, x[j] - tW, y[j] + tH, tP);
}
}
}
/**
* draw graph with animation
*/
private void drawGraphWithAnimation(GraphCanvasWrapper graphCanvas) {
//for draw animation
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath curvePath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
int xl = (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
if (xl == 0)
xl = 1;
float xGap = xLength / xl;
float pointNum = (mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length * anim) / 1;
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
if (x == null || y == null || x.length != y.length || x.length < 2)
continue;
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
// draw line
for (float j = x[0]; j <= x[x.length - 1]; j++) {
if (!firstSet) {
curvePath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else {
curvePath.lineTo(((j) * anim), spline.interpolate(((j) * anim)));
}
}
graphCanvas.getCanvas().drawPath(curvePath, p);
// draw point
TextPaint tP = new TextPaint(pMarkText);
tP.setColor(pCircle.getColor());
for (int j = 0; j < pointNum + 1; j++) {
if (j < mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length) {
String txt = mCurveGraphVO.getArrGraph().get(i).getCoordinateTitleArr()[j];
int tW = (int) pMarkText.measureText(txt);
tW = tW >> 1;
int tH = getFontHeight(pMarkText.getTextSize());
float tY = y[j] + tH;
if (graphCanvas.mMt.calcY(tY)<=0)
tY = y[j] - tH;
graphCanvas.drawText(txt, x[j] - tW, tY, tP);
graphCanvas.drawCircle(x[j], y[j], 4, pCircle);
}
}
if (anim == 1)
isDirty = false;
}
}
public int getFontHeight(float fontSize) {
Paint paint = new Paint();
paint.setTextSize(fontSize);
Paint.FontMetrics fm = paint.getFontMetrics();
return (int) Math.ceil(fm.descent - fm.ascent);
}
/**
* draw X Mark
*/
private void drawXMark(GraphCanvasWrapper graphCanvas) {
float x = 0;
float xGap = 0;
x = (mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length - 1);
if (x != 0)
xGap = xLength / x;
else
xGap = xLength;
for (int i = 0; i < mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length; i++) {
x = xGap * i;
graphCanvas.drawLine(x, 0, x, -10, pBaseLine);
}
}
/**
* draw Y Mark
*/
private void drawYMark(GraphCanvasWrapper canvas) {
for (int i = 0; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {
float y = yLength * mCurveGraphVO.getIncrement() * i / mCurveGraphVO.getMaxValue();
canvas.drawLine(0, y, -10, y, pBaseLine);
}
}
/**
* draw X Text
*/
private void drawXText(GraphCanvasWrapper graphCanvas) {
float x = 0;
float xGap = 0;
x = (mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length - 1);
if (x != 0)
xGap = xLength / x;
else
xGap = xLength;
pMarkText.setColor(0xff646464);
for (int i = 0; i < mCurveGraphVO.getLegendArr().length; i++) {
x = xGap * i;
String text = mCurveGraphVO.getLegendArr()[i];
pMarkText.measureText(text);
pMarkText.setTextSize(20);
Rect rect = new Rect();
pMarkText.getTextBounds(text, 0, text.length(), rect);
StaticLayout layout = new StaticLayout(text, pMarkText, text.trim().length() > 9 ? rect.width() - 15 : rect.width() + 15,
Layout.Alignment.ALIGN_CENTER, 1.0F, 0.0F, true);
graphCanvas.getCanvas().save();
graphCanvas.getCanvas().translate(graphCanvas.mMt.calcX(x - (rect.width() / 2)), graphCanvas.mMt.calcY(-(20 + rect.height())));
layout.draw(graphCanvas.getCanvas());
graphCanvas.getCanvas().restore();
}
}
/**
* draw Y Text
*/
private void drawYText(GraphCanvasWrapper graphCanvas) {
for (int i = 0; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {
String mark = Float.toString(mCurveGraphVO.getIncrement() * i);
float y = yLength * mCurveGraphVO.getIncrement() * i / mCurveGraphVO.getMaxValue();
pMarkText.measureText(mark);
pMarkText.setTextSize(20);
Rect rect = new Rect();
pMarkText.getTextBounds(mark, 0, mark.length(), rect);
// Log.e(TAG, "rect = height()" + rect.height());
// Log.e(TAG, "rect = width()" + rect.width());
graphCanvas.drawText(mark, -(rect.width() + 20), y - rect.height() / 2, pMarkText);
}
}
/**
* set point X Coordinate
*/
private float[] setAxisX(float xGap, int graphNum) {
float[] axisX = new float[mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length];
for (int i = 0; i < mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length; i++) {
axisX[i] = xGap * i;
}
return axisX;
}
/**
* set point Y Coordinate
*/
private float[] setAxisY(int graphNum) {
float[] axisY = new float[mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length];
for (int i = 0; i < mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length; i++) {
axisY[i] = yLength * mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr()[i] / mCurveGraphVO.getMaxValue();
}
return axisY;
}
}
}
| UTF-8 | Java | 27,293 | java | NYCurveGraphView.java | Java | [
{
"context": "lib.vo.curvegraph.CurveGraphVO;\n\n/**\n * Created by loo on 16-8-4.\n * 继承普通view的曲线图\n */\npublic class NYCur",
"end": 1030,
"score": 0.9831476211547852,
"start": 1027,
"tag": "USERNAME",
"value": "loo"
}
] | null | [] | package com.handstudio.android.hzgrapherlib.graphview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.canvas.GraphCanvasWrapper;
import com.handstudio.android.hzgrapherlib.error.ErrorCode;
import com.handstudio.android.hzgrapherlib.error.ErrorDetector;
import com.handstudio.android.hzgrapherlib.path.GraphPath;
import com.handstudio.android.hzgrapherlib.util.Spline;
import com.handstudio.android.hzgrapherlib.vo.curvegraph.CurveGraphVO;
/**
* Created by loo on 16-8-4.
* 继承普通view的曲线图
*/
public class NYCurveGraphView extends View {
public static final String TAG = "CurveGraphView";
private SurfaceHolder mHolder;
public DrawThread mDrawThread;
private CurveGraphVO mCurveGraphVO = null;
private Spline spline = null;
private Bitmap content;
//Constructor
public NYCurveGraphView(Context context, CurveGraphVO vo) {
super(context);
mCurveGraphVO = vo;
initView(context, vo);
}
private void initView(Context context, CurveGraphVO vo) {
ErrorCode ec = ErrorDetector.checkGraphObject(vo);
ec.printError();
setBackgroundColor(Color.WHITE);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mDrawThread == null) {
mDrawThread = new DrawThread(mHolder, getContext());
mDrawThread.start();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mDrawThread == null) {
mDrawThread = new DrawThread(mHolder, getContext());
mDrawThread.start();
}
}
private static final Object touchLock = new Object(); // touch synchronize
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (mDrawThread == null) {
return false;
}
if (action == MotionEvent.ACTION_DOWN) {
synchronized (touchLock) {
mDrawThread.isDirty = true;
}
return true;
} else if (action == MotionEvent.ACTION_MOVE) {
synchronized (touchLock) {
mDrawThread.isDirty = true;
}
return true;
} else if (action == MotionEvent.ACTION_UP) {
synchronized (touchLock) {
mDrawThread.isDirty = true;
}
return true;
}
return super.onTouchEvent(event);
}
@Override
public void draw(Canvas canvas) {
if (content != null) {
super.draw(canvas);
canvas.drawBitmap(content, 0, 0, null);
} else
super.draw(canvas);
}
class DrawThread extends Thread {
//final SurfaceHolder mHolder;
Context mCtx;
boolean finishDraw;
boolean isRun = true;
boolean isDirty = true;
int height = getHeight();
int width = getWidth();
//graph length
int xLength = width - (mCurveGraphVO.getPaddingLeft() + mCurveGraphVO.getPaddingRight() + mCurveGraphVO.getMarginRight());
int yLength = height - (mCurveGraphVO.getPaddingBottom() + mCurveGraphVO.getPaddingTop() + mCurveGraphVO.getMarginTop());
//chart length
int chartXLength = width - (mCurveGraphVO.getPaddingLeft() + mCurveGraphVO.getPaddingRight());
Paint p = new Paint();
Paint pCircle = new Paint();
Paint pCurve = new Paint();
Paint pBaseLine = new Paint();
Paint pBaseLineX = new Paint();
TextPaint pMarkText = new TextPaint();
//animation
float anim = 0.0f;
boolean isAnimation = false;
boolean isDrawRegion = false;
long animStartTime = -1;
int animationType = 0;
Bitmap bg = null;
public DrawThread(SurfaceHolder holder, Context context) {
mHolder = holder;
mCtx = context;
content = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
}
public void setRunFlag(boolean bool) {
isRun = bool;
}
@Override
public void run() {
Canvas canvas = null;
GraphCanvasWrapper graphCanvasWrapper = null;
Log.e(TAG, "height = " + height);
Log.e(TAG, "width = " + width);
setPaint();
isAnimation();
isDrawRegion();
finishDraw = false;
canvas = new Canvas(content);
canvas.setBitmap(content);
animStartTime = System.currentTimeMillis();
canvas.drawColor(Color.WHITE);
while (isRun) {
//draw only on dirty mode
if (!isDirty) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
continue;
}
graphCanvasWrapper = new GraphCanvasWrapper(canvas, width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
calcTimePass();
synchronized (touchLock) {
try {
//bg color
finishDraw = true;
// x coord dot Line
drawBaseLine(graphCanvasWrapper);
// x coord
graphCanvasWrapper.drawLine(-50, 0, chartXLength, 0, pCircle);
drawAL((int) graphCanvasWrapper.mMt.calcX(0), (int) graphCanvasWrapper.mMt.calcY(0)
, (int) graphCanvasWrapper.mMt.calcX(chartXLength), (int) graphCanvasWrapper.mMt.calcY(0), canvas);
// x, y coord mark
//drawXMark(graphCanvasWrapper);
// x, y coord text
drawXText(graphCanvasWrapper);
// Draw Graph
drawGraphRegion(graphCanvasWrapper);
drawGraph(graphCanvasWrapper);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (graphCanvasWrapper.getCanvas() != null) {
postInvalidate();
}
}
}
}
}
/**
* 画箭头
*
* @param sx
* @param sy
* @param ex
* @param ey
*/
public void drawAL(int sx, int sy, int ex, int ey, Canvas canvas) {
double H = 8; // 箭头高度
double L = 3.5; // 底边的一半
int x3 = 0;
int y3 = 0;
int x4 = 0;
int y4 = 0;
double awrad = Math.atan(L / H); // 箭头角度
double arraow_len = Math.sqrt(L * L + H * H); // 箭头的长度
double[] arrXY_1 = rotateVec(ex - sx, ey - sy, awrad, true, arraow_len);
double[] arrXY_2 = rotateVec(ex - sx, ey - sy, -awrad, true, arraow_len);
double x_3 = ex - arrXY_1[0]; // (x3,y3)是第一端点
double y_3 = ey - arrXY_1[1];
double x_4 = ex - arrXY_2[0]; // (x4,y4)是第二端点
double y_4 = ey - arrXY_2[1];
Double X3 = new Double(x_3);
x3 = X3.intValue();
Double Y3 = new Double(y_3);
y3 = Y3.intValue();
Double X4 = new Double(x_4);
x4 = X4.intValue();
Double Y4 = new Double(y_4);
y4 = Y4.intValue();
Path triangle = new Path();
triangle.moveTo(ex, ey);
triangle.lineTo(x3, y3);
triangle.lineTo(x4, y4);
triangle.close();
canvas.drawPath(triangle, pCircle);
}
// 计算
public double[] rotateVec(int px, int py, double ang, boolean isChLen, double newLen) {
double mathstr[] = new double[2];
// 矢量旋转函数,参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度
double vx = px * Math.cos(ang) - py * Math.sin(ang);
double vy = px * Math.sin(ang) + py * Math.cos(ang);
if (isChLen) {
double d = Math.sqrt(vx * vx + vy * vy);
vx = vx / d * newLen;
vy = vy / d * newLen;
mathstr[0] = vx;
mathstr[1] = vy;
}
return mathstr;
}
/**
* time calculate
*/
private void calcTimePass() {
if (isAnimation) {
long curTime = System.currentTimeMillis();
long gapTime = curTime - animStartTime;
long animDuration = mCurveGraphVO.getAnimation().getDuration();
if (gapTime >= animDuration)
gapTime = animDuration;
anim = (float) gapTime / (float) animDuration;
} else {
isDirty = false;
}
}
/**
* check graph Curve animation
*/
private void isAnimation() {
if (mCurveGraphVO.getAnimation() != null) {
isAnimation = true;
} else {
isAnimation = false;
}
animationType = mCurveGraphVO.getAnimation().getAnimation();
}
/**
* check graph Curve region animation
*/
private void isDrawRegion() {
if (mCurveGraphVO.isDrawRegion()) {
isDrawRegion = true;
} else {
isDrawRegion = false;
}
}
/**
* draw Base Line
*/
private void drawBaseLine(GraphCanvasWrapper graphCanvas) {
for (int i = 1; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {
float y = yLength * mCurveGraphVO.getIncrement() * i / mCurveGraphVO.getMaxValue();
graphCanvas.drawLine(-50, y, chartXLength, y, pBaseLineX);
}
}
/**
* set graph Curve color
*/
private void setPaint() {
p = new Paint();
p.setFlags(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true); //text anti alias
p.setFilterBitmap(true); // bitmap anti alias
p.setColor(Color.BLUE);
p.setStrokeWidth(3);
p.setStyle(Paint.Style.STROKE);
pCircle = new Paint();
pCircle.setFlags(Paint.ANTI_ALIAS_FLAG);
pCircle.setAntiAlias(true); //text anti alias
pCircle.setFilterBitmap(true); // bitmap anti alias
pCircle.setColor(0xfffb5f5b);
pCircle.setStrokeWidth(3);
pCircle.setStyle(Paint.Style.FILL_AND_STROKE);
pCurve = new Paint();
pCurve.setFlags(Paint.ANTI_ALIAS_FLAG);
pCurve.setAntiAlias(true); //text anti alias
pCurve.setFilterBitmap(true); // bitmap anti alias
pCurve.setShader(new LinearGradient(0, 300f, 0, 0f, Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));
pBaseLine = new Paint();
pBaseLine.setFlags(Paint.ANTI_ALIAS_FLAG);
pBaseLine.setAntiAlias(true); //text anti alias
pBaseLine.setFilterBitmap(true); // bitmap anti alias
pBaseLine.setColor(0xfff0f0f0);
pBaseLine.setStrokeWidth(3);
pBaseLineX = new Paint();
pBaseLineX.setFlags(Paint.ANTI_ALIAS_FLAG);
pBaseLineX.setAntiAlias(true); //text anti alias
pBaseLineX.setFilterBitmap(true); // bitmap anti alias
pBaseLineX.setColor(0xfff0f0f0);
pBaseLineX.setStyle(Paint.Style.FILL);
pMarkText = new TextPaint();
pMarkText.setFlags(Paint.ANTI_ALIAS_FLAG);
pMarkText.setAntiAlias(true); //text anti alias
pMarkText.setColor(0xff646464);
}
/**
* draw Graph Region
*/
private void drawGraphRegion(GraphCanvasWrapper graphCanvas) {
if (isDrawRegion) {
if (isAnimation) {
drawGraphRegionWithAnimation(graphCanvas);
} else {
drawGraphRegionWithoutAnimation(graphCanvas);
}
}
}
/**
* draw Graph
*/
private void drawGraph(GraphCanvasWrapper graphCanvas) {
if (isAnimation) {
drawGraphWithAnimation(graphCanvas);
} else {
drawGraphWithoutAnimation(graphCanvas);
}
}
/**
* draw graph without animation
*/
private void drawGraphRegionWithoutAnimation(GraphCanvasWrapper graphCanvas) {
boolean isDrawRegion = mCurveGraphVO.isDrawRegion();
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath regionPath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
float xGap = xLength / (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
spline = Spline.createMonotoneCubicSpline(x, y);
// draw Region
for (float j = x[0]; j < x[x.length - 1]; j++) {
if (!firstSet) {
regionPath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else
regionPath.lineTo((j + 1), spline.interpolate((j + 1)));
}
if (isDrawRegion) {
regionPath.lineTo(x[x.length - 1], 0);
regionPath.lineTo(0, 0);
Paint pBg = new Paint();
pBg.setFlags(Paint.ANTI_ALIAS_FLAG);
pBg.setAntiAlias(true); //text anti alias
pBg.setFilterBitmap(true); // bitmap anti alias
pBg.setStyle(Paint.Style.FILL);
pBg.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
graphCanvas.getCanvas().drawPath(regionPath, pBg);
}
}
}
/**
* draw graph with animation
*/
private void drawGraphRegionWithAnimation(GraphCanvasWrapper graphCanvas) {
//for draw animation
boolean isDrawRegion = mCurveGraphVO.isDrawRegion();
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath regionPath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
int xl = (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
if (xl == 0)
xl = 1;
float xGap = xLength / xl;
float moveX = 0;
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
if (x == null || y == null || x.length != y.length || x.length < 2)
continue;
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
// draw line
for (float j = x[0]; j <= x[x.length - 1]; j++) {
if (!firstSet) {
regionPath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else {
moveX = j * anim;
regionPath.lineTo(moveX, spline.interpolate(moveX));
}
}
if (isDrawRegion) {
if (animationType == GraphAnimation.CURVE_REGION_ANIMATION_1) {
moveX += xGap * anim;
if (moveX >= xLength) {
moveX = xLength;
}
}
regionPath.lineTo(moveX, 0);
regionPath.lineTo(0, 0);
Paint pBg = new Paint();
pBg.setFlags(Paint.ANTI_ALIAS_FLAG);
pBg.setAntiAlias(true); //text anti alias
pBg.setFilterBitmap(true); // bitmap anti alias
pBg.setStyle(Paint.Style.FILL);
pBg.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
graphCanvas.getCanvas().drawPath(regionPath, pBg);
}
if (anim == 1)
isDirty = false;
}
}
/**
* draw graph without animation
*/
private void drawGraphWithoutAnimation(GraphCanvasWrapper graphCanvas) {
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath curvePath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
float xGap = xLength / (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
// draw line
for (float j = x[0]; j < x[x.length - 1]; j++) {
if (!firstSet) {
curvePath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else
curvePath.lineTo((j + 1), spline.interpolate((j + 1)));
}
// draw point
TextPaint tP = new TextPaint(pMarkText);
tP.setColor(pCircle.getColor());
for (int j = 0; j < mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length; j++) {
float pointX = xGap * j;
float pointY = yLength * mCurveGraphVO.getArrGraph().get(i).getCoordinateArr()[j] / mCurveGraphVO.getMaxValue();
graphCanvas.drawCircle(pointX, pointY, 4, pCircle);
String txt = mCurveGraphVO.getArrGraph().get(i).getCoordinateTitleArr()[j];
int tW = (int) pMarkText.measureText(txt);
tW = tW >> 1;
int tH = getFontHeight(pMarkText.getTextSize());
graphCanvas.drawText(txt, x[j] - tW, y[j] + tH, tP);
}
}
}
/**
* draw graph with animation
*/
private void drawGraphWithAnimation(GraphCanvasWrapper graphCanvas) {
//for draw animation
for (int i = 0; i < mCurveGraphVO.getArrGraph().size(); i++) {
GraphPath curvePath = new GraphPath(width, height, mCurveGraphVO.getPaddingLeft(), mCurveGraphVO.getPaddingBottom());
boolean firstSet = false;
int xl = (mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length - 1);
if (xl == 0)
xl = 1;
float xGap = xLength / xl;
float pointNum = (mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length * anim) / 1;
float[] x = setAxisX(xGap, i);
float[] y = setAxisY(i);
// Creates a monotone cubic spline from a given set of control points.
if (x == null || y == null || x.length != y.length || x.length < 2)
continue;
spline = Spline.createMonotoneCubicSpline(x, y);
p.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
pCircle.setColor(mCurveGraphVO.getArrGraph().get(i).getColor());
// draw line
for (float j = x[0]; j <= x[x.length - 1]; j++) {
if (!firstSet) {
curvePath.moveTo(j, spline.interpolate(j));
firstSet = true;
} else {
curvePath.lineTo(((j) * anim), spline.interpolate(((j) * anim)));
}
}
graphCanvas.getCanvas().drawPath(curvePath, p);
// draw point
TextPaint tP = new TextPaint(pMarkText);
tP.setColor(pCircle.getColor());
for (int j = 0; j < pointNum + 1; j++) {
if (j < mCurveGraphVO.getArrGraph().get(i).getCoordinateArr().length) {
String txt = mCurveGraphVO.getArrGraph().get(i).getCoordinateTitleArr()[j];
int tW = (int) pMarkText.measureText(txt);
tW = tW >> 1;
int tH = getFontHeight(pMarkText.getTextSize());
float tY = y[j] + tH;
if (graphCanvas.mMt.calcY(tY)<=0)
tY = y[j] - tH;
graphCanvas.drawText(txt, x[j] - tW, tY, tP);
graphCanvas.drawCircle(x[j], y[j], 4, pCircle);
}
}
if (anim == 1)
isDirty = false;
}
}
public int getFontHeight(float fontSize) {
Paint paint = new Paint();
paint.setTextSize(fontSize);
Paint.FontMetrics fm = paint.getFontMetrics();
return (int) Math.ceil(fm.descent - fm.ascent);
}
/**
* draw X Mark
*/
private void drawXMark(GraphCanvasWrapper graphCanvas) {
float x = 0;
float xGap = 0;
x = (mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length - 1);
if (x != 0)
xGap = xLength / x;
else
xGap = xLength;
for (int i = 0; i < mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length; i++) {
x = xGap * i;
graphCanvas.drawLine(x, 0, x, -10, pBaseLine);
}
}
/**
* draw Y Mark
*/
private void drawYMark(GraphCanvasWrapper canvas) {
for (int i = 0; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {
float y = yLength * mCurveGraphVO.getIncrement() * i / mCurveGraphVO.getMaxValue();
canvas.drawLine(0, y, -10, y, pBaseLine);
}
}
/**
* draw X Text
*/
private void drawXText(GraphCanvasWrapper graphCanvas) {
float x = 0;
float xGap = 0;
x = (mCurveGraphVO.getArrGraph().get(0).getCoordinateArr().length - 1);
if (x != 0)
xGap = xLength / x;
else
xGap = xLength;
pMarkText.setColor(0xff646464);
for (int i = 0; i < mCurveGraphVO.getLegendArr().length; i++) {
x = xGap * i;
String text = mCurveGraphVO.getLegendArr()[i];
pMarkText.measureText(text);
pMarkText.setTextSize(20);
Rect rect = new Rect();
pMarkText.getTextBounds(text, 0, text.length(), rect);
StaticLayout layout = new StaticLayout(text, pMarkText, text.trim().length() > 9 ? rect.width() - 15 : rect.width() + 15,
Layout.Alignment.ALIGN_CENTER, 1.0F, 0.0F, true);
graphCanvas.getCanvas().save();
graphCanvas.getCanvas().translate(graphCanvas.mMt.calcX(x - (rect.width() / 2)), graphCanvas.mMt.calcY(-(20 + rect.height())));
layout.draw(graphCanvas.getCanvas());
graphCanvas.getCanvas().restore();
}
}
/**
* draw Y Text
*/
private void drawYText(GraphCanvasWrapper graphCanvas) {
for (int i = 0; mCurveGraphVO.getIncrement() * i <= mCurveGraphVO.getMaxValue(); i++) {
String mark = Float.toString(mCurveGraphVO.getIncrement() * i);
float y = yLength * mCurveGraphVO.getIncrement() * i / mCurveGraphVO.getMaxValue();
pMarkText.measureText(mark);
pMarkText.setTextSize(20);
Rect rect = new Rect();
pMarkText.getTextBounds(mark, 0, mark.length(), rect);
// Log.e(TAG, "rect = height()" + rect.height());
// Log.e(TAG, "rect = width()" + rect.width());
graphCanvas.drawText(mark, -(rect.width() + 20), y - rect.height() / 2, pMarkText);
}
}
/**
* set point X Coordinate
*/
private float[] setAxisX(float xGap, int graphNum) {
float[] axisX = new float[mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length];
for (int i = 0; i < mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length; i++) {
axisX[i] = xGap * i;
}
return axisX;
}
/**
* set point Y Coordinate
*/
private float[] setAxisY(int graphNum) {
float[] axisY = new float[mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length];
for (int i = 0; i < mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr().length; i++) {
axisY[i] = yLength * mCurveGraphVO.getArrGraph().get(graphNum).getCoordinateArr()[i] / mCurveGraphVO.getMaxValue();
}
return axisY;
}
}
}
| 27,293 | 0.515054 | 0.5075 | 727 | 36.323246 | 29.116402 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.737276 | false | false | 9 |
b12175c95f8d47832ff2ae356a19d9a72ca5f240 | 6,794,638,303,977 | 2cb499e4be6ce34054bf854793f0c34716180359 | /module4/demo/src/main/java/com/example/demo/dto/QuestionDto.java | cde6e78bbd66a3ba5b12907f7f71b36b35547049 | [] | no_license | nhutam123/C0221G1-le-nhu-tam | https://github.com/nhutam123/C0221G1-le-nhu-tam | 3b1398583e778cec1c232ce72a562daf1778398e | 549304e82500a5094a91e332dc8a23213ffca80b | refs/heads/main | 2023-07-12T01:06:09.316000 | 2021-08-11T10:35:45 | 2021-08-11T10:35:45 | 342,120,462 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.dto;
import com.example.demo.model.entity.QuestionType;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.Date;
public class QuestionDto {
private Integer id;
@Size(min=5,max = 100)
@NotEmpty
private String title;
@Size(min = 10,max = 500)
@NotEmpty
private String content;
@NotEmpty
private String answer;
@NotEmpty
private String dateCreate;
@NotEmpty
private String status;
private int flag;
private QuestionType questionType;
public QuestionDto() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getDateCreate() {
return dateCreate;
}
public void setDateCreate(String dateCreate) {
this.dateCreate = dateCreate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public QuestionType getQuestionType() {
return questionType;
}
public void setQuestionType(QuestionType questionType) {
this.questionType = questionType;
}
}
| UTF-8 | Java | 1,778 | java | QuestionDto.java | Java | [] | null | [] | package com.example.demo.dto;
import com.example.demo.model.entity.QuestionType;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.Date;
public class QuestionDto {
private Integer id;
@Size(min=5,max = 100)
@NotEmpty
private String title;
@Size(min = 10,max = 500)
@NotEmpty
private String content;
@NotEmpty
private String answer;
@NotEmpty
private String dateCreate;
@NotEmpty
private String status;
private int flag;
private QuestionType questionType;
public QuestionDto() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getDateCreate() {
return dateCreate;
}
public void setDateCreate(String dateCreate) {
this.dateCreate = dateCreate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public QuestionType getQuestionType() {
return questionType;
}
public void setQuestionType(QuestionType questionType) {
this.questionType = questionType;
}
}
| 1,778 | 0.619235 | 0.614173 | 93 | 18.11828 | 15.645844 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
9fc475c9f67437942c4bc161c215cb74a086af53 | 12,807,592,541,871 | a7be05451801468055c51deb5be244155d363bd0 | /src/main/java/com/springboot/test/SpringBootTest/designModel/observer/TemperatureObserver2.java | 22565893da30280634c6967bb9f9a335df1360b7 | [] | no_license | wtd741277660/SpringBootTest | https://github.com/wtd741277660/SpringBootTest | 8e0bcc785328de2e9d32eb12f510440474163b8f | bf02df2bd4d6f711fcb168e2ea58d15b7db99fa5 | refs/heads/master | 2022-07-11T19:10:48.385000 | 2021-04-09T03:12:42 | 2021-04-09T03:12:42 | 189,191,235 | 0 | 0 | null | false | 2022-06-21T02:32:44 | 2019-05-29T09:13:00 | 2021-04-09T03:13:49 | 2022-06-21T02:32:43 | 16,861 | 0 | 0 | 4 | Java | false | false | package com.springboot.test.SpringBootTest.designModel.observer;
import java.util.Observable;
import java.util.Observer;
/**
* 温度数据的观察者,温度数据主题发生变化时会通知此观察者
*/
public class TemperatureObserver2 implements Observer {
/**
* 主题通过调用update方法来通知观察者
* @param o
* @param arg
*/
@Override
public void update(Observable o, Object arg) {
System.out.println("观察者2收到数据:" + arg);
}
}
| UTF-8 | Java | 515 | java | TemperatureObserver2.java | Java | [] | null | [] | package com.springboot.test.SpringBootTest.designModel.observer;
import java.util.Observable;
import java.util.Observer;
/**
* 温度数据的观察者,温度数据主题发生变化时会通知此观察者
*/
public class TemperatureObserver2 implements Observer {
/**
* 主题通过调用update方法来通知观察者
* @param o
* @param arg
*/
@Override
public void update(Observable o, Object arg) {
System.out.println("观察者2收到数据:" + arg);
}
}
| 515 | 0.678657 | 0.673861 | 20 | 19.85 | 19.711102 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
eb947ab61a5d0d73f2ce33b517ece8ff612f9713 | 20,452,634,286,199 | b27d5c322e96b9753190686542cbec04243a677b | /app/src/main/java/op27no2/parentscope2/MyPurchaseAdapter.java | 69ad95c1b40c1c106cbd67ac8d92e0164bd890d1 | [] | no_license | op27no2/ParentScope2 | https://github.com/op27no2/ParentScope2 | bb066dbc92e0174e84a6447d1db5faea21bbd31e | 5b0cc8ec7c19faac4064828854739d8ce2c8ea58 | refs/heads/master | 2020-04-04T21:39:58.598000 | 2019-09-08T19:58:02 | 2019-09-08T19:58:02 | 156,294,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package op27no2.parentscope2;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rilixtech.materialfancybutton.MaterialFancyButton;
import java.util.ArrayList;
/**
* Created by CristMac on 11/3/17.
*/
public class MyPurchaseAdapter extends RecyclerView.Adapter<MyPurchaseAdapter.ViewHolder> {
private ArrayList<String> mDataset;
private ArrayList<String> mDataset2;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyPurchaseAdapter(ArrayList<String> myDataset, ArrayList<String> myDataset2) {
mDataset = myDataset;
mDataset2 = myDataset2;
}
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = (View) LayoutInflater.from(parent.getContext())
.inflate(R.layout.rowview_premium, parent, false);
// set the view's size, margins, paddings and layout parameters
final ViewHolder holder = new ViewHolder(v);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String mTitle = mDataset.get(position);
final String mTitle2 = mDataset2.get(position);
System.out.println("position test"+position);
TextView mText = holder.mView.findViewById(R.id.text_view);
TextView mText2 = holder.mView.findViewById(R.id.text2);
mText.setText(mTitle);
mText2.setText(mTitle2);
MaterialFancyButton mButton = holder.mView.findViewById(R.id.purchase_button);
/* if(position==0){
mButton.setText("Info:");
mText2.setVisibility(View.GONE);
}*/
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.size();
}
}
| UTF-8 | Java | 2,795 | java | MyPurchaseAdapter.java | Java | [
{
"context": "n;\n\nimport java.util.ArrayList;\n\n/**\n * Created by CristMac on 11/3/17.\n */\n\npublic class MyPurchaseAdapter e",
"end": 322,
"score": 0.9962234497070312,
"start": 314,
"tag": "USERNAME",
"value": "CristMac"
}
] | null | [] | package op27no2.parentscope2;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rilixtech.materialfancybutton.MaterialFancyButton;
import java.util.ArrayList;
/**
* Created by CristMac on 11/3/17.
*/
public class MyPurchaseAdapter extends RecyclerView.Adapter<MyPurchaseAdapter.ViewHolder> {
private ArrayList<String> mDataset;
private ArrayList<String> mDataset2;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyPurchaseAdapter(ArrayList<String> myDataset, ArrayList<String> myDataset2) {
mDataset = myDataset;
mDataset2 = myDataset2;
}
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = (View) LayoutInflater.from(parent.getContext())
.inflate(R.layout.rowview_premium, parent, false);
// set the view's size, margins, paddings and layout parameters
final ViewHolder holder = new ViewHolder(v);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String mTitle = mDataset.get(position);
final String mTitle2 = mDataset2.get(position);
System.out.println("position test"+position);
TextView mText = holder.mView.findViewById(R.id.text_view);
TextView mText2 = holder.mView.findViewById(R.id.text2);
mText.setText(mTitle);
mText2.setText(mTitle2);
MaterialFancyButton mButton = holder.mView.findViewById(R.id.purchase_button);
/* if(position==0){
mButton.setText("Info:");
mText2.setVisibility(View.GONE);
}*/
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.size();
}
}
| 2,795 | 0.659034 | 0.651163 | 90 | 30.022223 | 27.632902 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.422222 | false | false | 9 |
b3855896f7c4fb282e4cccfe38331c80693a2fdc | 10,823,317,609,821 | ee5d43cc5ec2040015d6993267ea430aa1a07095 | /src/main/java/cs20162/aula03/Exercicio02.java | 22b135a534ec0b5d35043d8308265a95961f5f5e | [] | no_license | andrehaarengl/cs20162-aula03 | https://github.com/andrehaarengl/cs20162-aula03 | ed50f18c0b2ef547bd58291b1439659d8d62dbc5 | 6382cea312f6cfdb808a6fb6afcf492a41ef91aa | refs/heads/master | 2020-06-28T12:03:28.677000 | 2016-10-26T03:33:53 | 2016-10-26T03:33:53 | 67,441,702 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 cs20162.aula03;
/**
*
* @author andre
*/
public class Exercicio02 {
/**
*
* @param n
* @return p
*/
public static double calculoValorPi(int n) {
int i, s, d;
double p = 0;
if (n < 1) {
throw new IllegalArgumentException("NUMERO DIGITADO INVALIDO");
} else {
i = 1;
s = -1;
d = -1;
p = 0;
while (n >= i) {
d = d + 2;
s = -1 * s;
p = p + 4 * (s / d);
i = i + 1;
}
}
return p;
}
}
| UTF-8 | Java | 804 | java | Exercicio02.java | Java | [
{
"context": "or.\n */\npackage cs20162.aula03;\n\n/**\n *\n * @author andre\n */\npublic class Exercicio02 {\n\n /**\n *\n ",
"end": 233,
"score": 0.7826030254364014,
"start": 228,
"tag": "USERNAME",
"value": "andre"
}
] | null | [] | /*
* 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 cs20162.aula03;
/**
*
* @author andre
*/
public class Exercicio02 {
/**
*
* @param n
* @return p
*/
public static double calculoValorPi(int n) {
int i, s, d;
double p = 0;
if (n < 1) {
throw new IllegalArgumentException("NUMERO DIGITADO INVALIDO");
} else {
i = 1;
s = -1;
d = -1;
p = 0;
while (n >= i) {
d = d + 2;
s = -1 * s;
p = p + 4 * (s / d);
i = i + 1;
}
}
return p;
}
}
| 804 | 0.436567 | 0.412935 | 38 | 20.157894 | 18.639977 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 9 |
63efdc1d71ce8e65e122a68b9fdf2287ed7e095d | 25,134,148,637,062 | 7c769a1d778d4c1314d90bc107a43cc2bffd851d | /src/main/java/fr/community143/util/Validator.java | 7cd57ab34ef623bb3e46c0e7daf410ae00bfbf0c | [] | no_license | 143-Community/143-Bot | https://github.com/143-Community/143-Bot | c6472c2ab4cc3178100803b30f3b16acbea01eb0 | 84cde8a7979aa7bbc94ba108d6d9af44369e3a84 | refs/heads/master | 2018-09-09T01:39:23.686000 | 2017-06-25T20:41:25 | 2017-06-25T20:41:25 | 93,642,196 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.community143.util;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by alexis on 16/05/17.
* French author.
*/
public class Validator
{
public static boolean testUrl(String uri)
{
URL url;
try {
url = new URL(uri);
} catch (MalformedURLException e) {
return false;
}
return true;
}
}
| UTF-8 | Java | 679 | java | Validator.java | Java | [
{
"context": "\nimport java.net.URLConnection;\n\n/**\n * Created by alexis on 16/05/17.\n * French author.\n */\n\npublic class ",
"end": 390,
"score": 0.9923369288444519,
"start": 384,
"tag": "USERNAME",
"value": "alexis"
}
] | null | [] | package fr.community143.util;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by alexis on 16/05/17.
* French author.
*/
public class Validator
{
public static boolean testUrl(String uri)
{
URL url;
try {
url = new URL(uri);
} catch (MalformedURLException e) {
return false;
}
return true;
}
}
| 679 | 0.681885 | 0.664212 | 34 | 18.970589 | 15.085024 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.441176 | false | false | 9 |
3375c4317c368ceb8034745aee852bb9d35c10bb | 13,125,420,089,369 | cfe94c26492de71ef59a368844fb2d00ad5161e7 | /alien4cloud-core/src/test/java/alien4cloud/tosca/serializer/ToscaSerializerUtilsTest.java | a4edeeebb5c25230b80a098ff8f1efc26b0ce17e | [
"Apache-2.0"
] | permissive | alien4cloud/alien4cloud | https://github.com/alien4cloud/alien4cloud | 91f7a4ed92b48ad7a521352be16df2d7d5fa7d73 | 27500e04925ed7c52dbb7b2aa81e81deb8668b05 | refs/heads/3.0.x | 2023-03-11T20:46:41.263000 | 2023-01-29T08:18:41 | 2023-01-29T08:18:41 | 24,750,302 | 78 | 86 | Apache-2.0 | false | 2023-02-22T01:46:31 | 2014-10-03T07:34:22 | 2022-09-12T16:43:54 | 2023-02-22T01:46:25 | 28,610 | 74 | 66 | 74 | Java | false | false | package alien4cloud.tosca.serializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alien4cloud.tosca.exceptions.ConstraintValueDoNotMatchPropertyTypeException;
import org.alien4cloud.tosca.exceptions.ConstraintViolationException;
import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
import org.alien4cloud.tosca.model.definitions.DeploymentArtifact;
import org.alien4cloud.tosca.model.definitions.ScalarPropertyValue;
import org.alien4cloud.tosca.model.definitions.constraints.AbstractPropertyConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.EqualConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.GreaterOrEqualConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.GreaterThanConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.InRangeConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.LengthConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.LessOrEqualConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.LessThanConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.MaxLengthConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.MinLengthConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.PatternConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.ValidValuesConstraint;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.templates.Topology;
import org.alien4cloud.tosca.normative.types.IPropertyType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class ToscaSerializerUtilsTest {
private ToscaSerializerUtils utils;
@Before
public void prepare() {
utils = new ToscaSerializerUtils();
}
@Test
public void testCollectionIsNotEmpty() {
Assert.assertFalse(utils.collectionIsNotEmpty(null));
Assert.assertFalse(utils.collectionIsNotEmpty(new ArrayList<String>()));
Assert.assertTrue(utils.collectionIsNotEmpty(Lists.newArrayList("Element")));
}
@Test
public void testMapIsNotEmpty() {
Assert.assertFalse(utils.mapIsNotEmpty(null));
Assert.assertFalse(utils.mapIsNotEmpty(Maps.newHashMap()));
Map<String, Object> map = Maps.newHashMap();
map.put("key1", null);
Assert.assertTrue(utils.mapIsNotEmpty(map));
map = Maps.newHashMap();
map.put("key1", "value1");
Assert.assertTrue(utils.mapIsNotEmpty(map));
}
@Test
public void testPropertyValueFormatText() {
Assert.assertEquals("aaaa", ToscaPropertySerializerUtils.formatTextValue(0, "aaaa"));
Assert.assertEquals("\"[aa]\"", ToscaPropertySerializerUtils.formatTextValue(0, "[aa]"));
Assert.assertEquals("123", ToscaPropertySerializerUtils.formatTextValue(0, "123"));
Assert.assertEquals("\"*\"", ToscaPropertySerializerUtils.formatTextValue(0, "*"));
}
@Test
public void testRenderScalar() {
Assert.assertEquals("a scalar", ToscaPropertySerializerUtils.renderScalar("a scalar"));
// contains a [ so should be quoted
Assert.assertEquals("\"[a scalar\"", ToscaPropertySerializerUtils.renderScalar("[a scalar"));
Assert.assertEquals("\"a ]scalar\"", ToscaPropertySerializerUtils.renderScalar("a ]scalar"));
// contains a { so should be quoted
Assert.assertEquals("\"{a scalar\"", ToscaPropertySerializerUtils.renderScalar("{a scalar"));
Assert.assertEquals("\"a }scalar\"", ToscaPropertySerializerUtils.renderScalar("a }scalar"));
// contains a : so should be quoted
Assert.assertEquals("\":a scalar\"", ToscaPropertySerializerUtils.renderScalar(":a scalar"));
Assert.assertEquals("\"a :scalar\"", ToscaPropertySerializerUtils.renderScalar("a :scalar"));
// contains a - so should be quoted
Assert.assertEquals("\"-a scalar\"", ToscaPropertySerializerUtils.renderScalar("-a scalar"));
Assert.assertEquals("\"a -scalar\"", ToscaPropertySerializerUtils.renderScalar("a -scalar"));
// starts or ends with a ' ' so should be quoted
Assert.assertEquals("\" a scalar\"", ToscaPropertySerializerUtils.renderScalar(" a scalar"));
Assert.assertEquals("\"a scalar \"", ToscaPropertySerializerUtils.renderScalar("a scalar "));
// and then " should be escaped
Assert.assertEquals("\"a \\\"scalar\\\" \"", ToscaPropertySerializerUtils.renderScalar("a \"scalar\" "));
}
@Test
public void testRenderDescription() throws IOException {
Assert.assertEquals("\"a single line description\"", utils.renderDescription("a single line description", " "));
Assert.assertEquals("|\n a multi line \n description", utils.renderDescription("a multi line \ndescription", " "));
}
@Test
public void testMapIsNotEmptyAndContainsNotnullValues() {
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(null));
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(Maps.newHashMap()));
Map<String, Object> map = Maps.newHashMap();
map.put("key1", null);
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(map));
map.put("key2", "something");
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(map));
// inner collection
Map<String, Set<String>> mapOfSet = Maps.newHashMap();
Set<String> set = Sets.newHashSet();
mapOfSet.put("key1", set);
// the set is empty
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfSet));
Set<String> filledSet = Sets.newHashSet("something");
mapOfSet.put("key2", filledSet);
// the second set contains something
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfSet));
// inner map
Map<String, Map<String, Set<String>>> mapOfmap = Maps.newHashMap();
Map<String, Set<String>> innerMap = Maps.newHashMap();
mapOfmap.put("key1", innerMap);
// the inner map is empty
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfmap));
Map<String, Set<String>> innerMap2 = Maps.newHashMap();
Set<String> emptySet = Sets.newHashSet();
innerMap2.put("key21", emptySet);
mapOfmap.put("key2", innerMap2);
// the inner set is empty
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfmap));
filledSet = Sets.newHashSet("something");
innerMap2.put("key22", filledSet);
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfmap));
// ScalarPropertyValue
ScalarPropertyValue spv = new ScalarPropertyValue();
Map<String, AbstractPropertyValue> apvMap = new HashMap<String, AbstractPropertyValue>();
apvMap.put("key1", spv);
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(apvMap));
spv.setValue("value");
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(apvMap));
}
@Test
public void testGetCsvToString() {
Assert.assertEquals("", utils.getCsvToString(null));
Assert.assertEquals("", utils.getCsvToString(Lists.newArrayList()));
Assert.assertEquals("one", utils.getCsvToString(Lists.newArrayList("one")));
Assert.assertEquals("one, two", utils.getCsvToString(Lists.newArrayList("one", "two")));
Assert.assertEquals("1, 2", utils.getCsvToString(Lists.newArrayList(Integer.valueOf(1), Integer.valueOf(2))));
Assert.assertEquals("one, two, \"three,four\"", utils.getCsvToString(Lists.newArrayList("one", "two", "three,four"), true));
}
@Test
public void testHasCapabilitiesContainingNotNullProperties() {
NodeTemplate nt = new NodeTemplate();
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
Map<String, Capability> capabilities = Maps.newHashMap();
nt.setCapabilities(capabilities);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
Capability capability1 = new Capability();
capabilities.put("capa1", capability1);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
Capability capability2 = new Capability();
Map<String, AbstractPropertyValue> properties = new HashMap<String, AbstractPropertyValue>();
capability2.setProperties(properties);
capabilities.put("capa2", capability2);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
properties.put("prop1", null);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
properties.put("prop2", new ScalarPropertyValue("value"));
Assert.assertTrue(utils.hasCapabilitiesContainingNotNullProperties(nt));
}
@Test
public void testRenderConstraint() {
GreaterOrEqualConstraint greaterOrEqualConstraint = new GreaterOrEqualConstraint();
Assert.assertEquals("greater_or_equal: null", utils.renderConstraint(greaterOrEqualConstraint));
greaterOrEqualConstraint.setGreaterOrEqual("1");
Assert.assertEquals("greater_or_equal: 1", utils.renderConstraint(greaterOrEqualConstraint));
GreaterThanConstraint greaterThanConstraint = new GreaterThanConstraint();
Assert.assertEquals("greater_than: null", utils.renderConstraint(greaterThanConstraint));
greaterThanConstraint.setGreaterThan("1");
Assert.assertEquals("greater_than: 1", utils.renderConstraint(greaterThanConstraint));
LessOrEqualConstraint lessOrEqualConstraint = new LessOrEqualConstraint();
Assert.assertEquals("less_or_equal: null", utils.renderConstraint(lessOrEqualConstraint));
lessOrEqualConstraint.setLessOrEqual("1");
Assert.assertEquals("less_or_equal: 1", utils.renderConstraint(lessOrEqualConstraint));
LessThanConstraint lessThanConstraint = new LessThanConstraint();
Assert.assertEquals("less_than: null", utils.renderConstraint(lessThanConstraint));
lessThanConstraint.setLessThan("1");
Assert.assertEquals("less_than: 1", utils.renderConstraint(lessThanConstraint));
LengthConstraint lengthConstraint = new LengthConstraint();
Assert.assertEquals("length: null", utils.renderConstraint(lengthConstraint));
lengthConstraint.setLength(1);
Assert.assertEquals("length: 1", utils.renderConstraint(lengthConstraint));
MaxLengthConstraint maxLengthConstraint = new MaxLengthConstraint();
Assert.assertEquals("max_length: null", utils.renderConstraint(maxLengthConstraint));
maxLengthConstraint.setMaxLength(1);
Assert.assertEquals("max_length: 1", utils.renderConstraint(maxLengthConstraint));
MinLengthConstraint minLengthConstraint = new MinLengthConstraint();
Assert.assertEquals("min_length: null", utils.renderConstraint(minLengthConstraint));
minLengthConstraint.setMinLength(1);
Assert.assertEquals("min_length: 1", utils.renderConstraint(minLengthConstraint));
PatternConstraint patternConstraint = new PatternConstraint();
Assert.assertEquals("pattern: null", utils.renderConstraint(patternConstraint));
patternConstraint.setPattern("a");
Assert.assertEquals("pattern: a", utils.renderConstraint(patternConstraint));
patternConstraint.setPattern("[.*]");
Assert.assertEquals("pattern: \"[.*]\"", utils.renderConstraint(patternConstraint));
EqualConstraint equalConstraint = new EqualConstraint();
Assert.assertEquals("equal: null", utils.renderConstraint(equalConstraint));
equalConstraint.setEqual("value");
Assert.assertEquals("equal: value", utils.renderConstraint(equalConstraint));
equalConstraint.setEqual(" value");
Assert.assertEquals("equal: \" value\"", utils.renderConstraint(equalConstraint));
InRangeConstraint inRangeConstraint = new InRangeConstraint();
Assert.assertEquals("in_range: []", utils.renderConstraint(inRangeConstraint));
List<String> inRange = Lists.newArrayList();
inRangeConstraint.setInRange(inRange);
Assert.assertEquals("in_range: []", utils.renderConstraint(inRangeConstraint));
inRange.add("1");
Assert.assertEquals("in_range: [1]", utils.renderConstraint(inRangeConstraint));
inRange.add("2");
Assert.assertEquals("in_range: [1, 2]", utils.renderConstraint(inRangeConstraint));
ValidValuesConstraint validValuesConstraint = new ValidValuesConstraint();
Assert.assertEquals("valid_values: []", utils.renderConstraint(validValuesConstraint));
List<String> validValues = Lists.newArrayList();
validValuesConstraint.setValidValues(validValues);
Assert.assertEquals("valid_values: []", utils.renderConstraint(validValuesConstraint));
validValues.add("value1");
Assert.assertEquals("valid_values: [value1]", utils.renderConstraint(validValuesConstraint));
validValues.add("value2 ");
Assert.assertEquals("valid_values: [value1, \"value2 \"]", utils.renderConstraint(validValuesConstraint));
validValues.add("value3,value4");
Assert.assertEquals("valid_values: [value1, \"value2 \", \"value3,value4\"]", utils.renderConstraint(validValuesConstraint));
// finally test an unknown constraint
AbstractPropertyConstraint abstractPropertyConstraint = new AbstractPropertyConstraint() {
@Override
public void validate(Object propertyValue) throws ConstraintViolationException {
}
@Override
public void initialize(IPropertyType<?> propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
}
};
Assert.assertEquals("", utils.renderConstraint(abstractPropertyConstraint));
}
private DeploymentArtifact createArtifact() {
DeploymentArtifact deploymentArtifact = new DeploymentArtifact();
deploymentArtifact.setArchiveName("test");
deploymentArtifact.setArchiveVersion("1.0");
return deploymentArtifact;
}
@Test
public void testArtifactsAndRepositoriesExport() {
Topology topology = new Topology();
topology.setNodeTemplates(Maps.newHashMap());
NodeTemplate node = new NodeTemplate();
node.setArtifacts(Maps.newHashMap());
topology.getNodeTemplates().put("Compute", node);
// no repositories
DeploymentArtifact deploymentArtifact = createArtifact();
deploymentArtifact.setArtifactRef("aaa/bbb.zip");
deploymentArtifact.setArtifactType("tosca.artifacts.File");
node.getArtifacts().put("local_war", deploymentArtifact);
Assert.assertFalse(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
String deploymentArtifactExport = ToscaSerializerUtils.formatArtifact(deploymentArtifact, 2);
Assert.assertEquals(" file: aaa/bbb.zip\n type: tosca.artifacts.File", deploymentArtifactExport);
// one repository should success
DeploymentArtifact deploymentArtifact2 = createArtifact();
deploymentArtifact2.setArtifactRef("aaa/bbb.zip");
deploymentArtifact2.setArtifactType("tosca.artifacts.File");
deploymentArtifact2.setRepositoryName("my_company");
deploymentArtifact2.setRepositoryURL("http://my_company.org");
deploymentArtifact2.setArtifactRepository("http");
deploymentArtifact2.setRepositoryCredential(Maps.newHashMap());
deploymentArtifact2.getRepositoryCredential().put("user", "my_user");
deploymentArtifact2.getRepositoryCredential().put("token", "password");
node.getArtifacts().put("http_war", deploymentArtifact2);
Assert.assertTrue(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
String deploymentArtifact2Export = ToscaSerializerUtils.formatArtifact(deploymentArtifact2, 1);
String repositoriesExport = ToscaSerializerUtils.formatRepositories("test", "1.0", topology);
Assert.assertEquals(" file: aaa/bbb.zip\n type: tosca.artifacts.File\n repository: my_company", deploymentArtifact2Export);
Assert.assertEquals(" my_company:\n url: http://my_company.org\n type: http\n credential:\n token: password\n user: my_user",
repositoriesExport);
// two repositories with different name
DeploymentArtifact deploymentArtifact3 = createArtifact();
deploymentArtifact3.setArtifactRef("aaa/ccc.zip");
deploymentArtifact3.setArtifactType("tosca.artifacts.File");
deploymentArtifact3.setRepositoryName("my_companyBis");
deploymentArtifact3.setRepositoryURL("http://my_company.org");
deploymentArtifact3.setArtifactRepository("maven");
node.getArtifacts().put("http_war2", deploymentArtifact3);
Assert.assertTrue(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
repositoriesExport = ToscaSerializerUtils.formatRepositories("test", "1.0", topology);
Assert.assertEquals(
" my_company:\n url: http://my_company.org\n type: http\n credential:\n token: password\n user: my_user\n my_companyBis:\n url: http://my_company.org\n type: maven",
repositoriesExport);
// add a new artifact with an already existing repository, should not duplicate the repository
DeploymentArtifact deploymentArtifact4 = createArtifact();
deploymentArtifact4.setArtifactRef("aaa/ddd.zip");
deploymentArtifact4.setArtifactType("tosca.artifacts.File");
deploymentArtifact4.setRepositoryName("my_company");
deploymentArtifact4.setRepositoryURL("http://my_company.org");
deploymentArtifact4.setArtifactRepository("http");
node.getArtifacts().put("http_war3", deploymentArtifact4);
Assert.assertTrue(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
repositoriesExport = ToscaSerializerUtils.formatRepositories("test", "1.0", topology);
Assert.assertEquals(
" my_company:\n url: http://my_company.org\n type: http\n credential:\n token: password\n user: my_user\n my_companyBis:\n url: http://my_company.org\n type: maven",
repositoriesExport);
}
}
| UTF-8 | Java | 18,832 | java | ToscaSerializerUtilsTest.java | Java | [
{
"context": "tArtifact2.getRepositoryCredential().put(\"user\", \"my_user\");\n deploymentArtifact2.getRepositoryCrede",
"end": 16069,
"score": 0.9995975494384766,
"start": 16062,
"tag": "USERNAME",
"value": "my_user"
},
{
"context": "Artifact2.getRepositoryCredential().put(\... | null | [] | package alien4cloud.tosca.serializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alien4cloud.tosca.exceptions.ConstraintValueDoNotMatchPropertyTypeException;
import org.alien4cloud.tosca.exceptions.ConstraintViolationException;
import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue;
import org.alien4cloud.tosca.model.definitions.DeploymentArtifact;
import org.alien4cloud.tosca.model.definitions.ScalarPropertyValue;
import org.alien4cloud.tosca.model.definitions.constraints.AbstractPropertyConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.EqualConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.GreaterOrEqualConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.GreaterThanConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.InRangeConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.LengthConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.LessOrEqualConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.LessThanConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.MaxLengthConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.MinLengthConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.PatternConstraint;
import org.alien4cloud.tosca.model.definitions.constraints.ValidValuesConstraint;
import org.alien4cloud.tosca.model.templates.Capability;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.templates.Topology;
import org.alien4cloud.tosca.normative.types.IPropertyType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class ToscaSerializerUtilsTest {
private ToscaSerializerUtils utils;
@Before
public void prepare() {
utils = new ToscaSerializerUtils();
}
@Test
public void testCollectionIsNotEmpty() {
Assert.assertFalse(utils.collectionIsNotEmpty(null));
Assert.assertFalse(utils.collectionIsNotEmpty(new ArrayList<String>()));
Assert.assertTrue(utils.collectionIsNotEmpty(Lists.newArrayList("Element")));
}
@Test
public void testMapIsNotEmpty() {
Assert.assertFalse(utils.mapIsNotEmpty(null));
Assert.assertFalse(utils.mapIsNotEmpty(Maps.newHashMap()));
Map<String, Object> map = Maps.newHashMap();
map.put("key1", null);
Assert.assertTrue(utils.mapIsNotEmpty(map));
map = Maps.newHashMap();
map.put("key1", "value1");
Assert.assertTrue(utils.mapIsNotEmpty(map));
}
@Test
public void testPropertyValueFormatText() {
Assert.assertEquals("aaaa", ToscaPropertySerializerUtils.formatTextValue(0, "aaaa"));
Assert.assertEquals("\"[aa]\"", ToscaPropertySerializerUtils.formatTextValue(0, "[aa]"));
Assert.assertEquals("123", ToscaPropertySerializerUtils.formatTextValue(0, "123"));
Assert.assertEquals("\"*\"", ToscaPropertySerializerUtils.formatTextValue(0, "*"));
}
@Test
public void testRenderScalar() {
Assert.assertEquals("a scalar", ToscaPropertySerializerUtils.renderScalar("a scalar"));
// contains a [ so should be quoted
Assert.assertEquals("\"[a scalar\"", ToscaPropertySerializerUtils.renderScalar("[a scalar"));
Assert.assertEquals("\"a ]scalar\"", ToscaPropertySerializerUtils.renderScalar("a ]scalar"));
// contains a { so should be quoted
Assert.assertEquals("\"{a scalar\"", ToscaPropertySerializerUtils.renderScalar("{a scalar"));
Assert.assertEquals("\"a }scalar\"", ToscaPropertySerializerUtils.renderScalar("a }scalar"));
// contains a : so should be quoted
Assert.assertEquals("\":a scalar\"", ToscaPropertySerializerUtils.renderScalar(":a scalar"));
Assert.assertEquals("\"a :scalar\"", ToscaPropertySerializerUtils.renderScalar("a :scalar"));
// contains a - so should be quoted
Assert.assertEquals("\"-a scalar\"", ToscaPropertySerializerUtils.renderScalar("-a scalar"));
Assert.assertEquals("\"a -scalar\"", ToscaPropertySerializerUtils.renderScalar("a -scalar"));
// starts or ends with a ' ' so should be quoted
Assert.assertEquals("\" a scalar\"", ToscaPropertySerializerUtils.renderScalar(" a scalar"));
Assert.assertEquals("\"a scalar \"", ToscaPropertySerializerUtils.renderScalar("a scalar "));
// and then " should be escaped
Assert.assertEquals("\"a \\\"scalar\\\" \"", ToscaPropertySerializerUtils.renderScalar("a \"scalar\" "));
}
@Test
public void testRenderDescription() throws IOException {
Assert.assertEquals("\"a single line description\"", utils.renderDescription("a single line description", " "));
Assert.assertEquals("|\n a multi line \n description", utils.renderDescription("a multi line \ndescription", " "));
}
@Test
public void testMapIsNotEmptyAndContainsNotnullValues() {
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(null));
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(Maps.newHashMap()));
Map<String, Object> map = Maps.newHashMap();
map.put("key1", null);
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(map));
map.put("key2", "something");
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(map));
// inner collection
Map<String, Set<String>> mapOfSet = Maps.newHashMap();
Set<String> set = Sets.newHashSet();
mapOfSet.put("key1", set);
// the set is empty
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfSet));
Set<String> filledSet = Sets.newHashSet("something");
mapOfSet.put("key2", filledSet);
// the second set contains something
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfSet));
// inner map
Map<String, Map<String, Set<String>>> mapOfmap = Maps.newHashMap();
Map<String, Set<String>> innerMap = Maps.newHashMap();
mapOfmap.put("key1", innerMap);
// the inner map is empty
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfmap));
Map<String, Set<String>> innerMap2 = Maps.newHashMap();
Set<String> emptySet = Sets.newHashSet();
innerMap2.put("key21", emptySet);
mapOfmap.put("key2", innerMap2);
// the inner set is empty
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfmap));
filledSet = Sets.newHashSet("something");
innerMap2.put("key22", filledSet);
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(mapOfmap));
// ScalarPropertyValue
ScalarPropertyValue spv = new ScalarPropertyValue();
Map<String, AbstractPropertyValue> apvMap = new HashMap<String, AbstractPropertyValue>();
apvMap.put("key1", spv);
Assert.assertFalse(utils.mapIsNotEmptyAndContainsNotnullValues(apvMap));
spv.setValue("value");
Assert.assertTrue(utils.mapIsNotEmptyAndContainsNotnullValues(apvMap));
}
@Test
public void testGetCsvToString() {
Assert.assertEquals("", utils.getCsvToString(null));
Assert.assertEquals("", utils.getCsvToString(Lists.newArrayList()));
Assert.assertEquals("one", utils.getCsvToString(Lists.newArrayList("one")));
Assert.assertEquals("one, two", utils.getCsvToString(Lists.newArrayList("one", "two")));
Assert.assertEquals("1, 2", utils.getCsvToString(Lists.newArrayList(Integer.valueOf(1), Integer.valueOf(2))));
Assert.assertEquals("one, two, \"three,four\"", utils.getCsvToString(Lists.newArrayList("one", "two", "three,four"), true));
}
@Test
public void testHasCapabilitiesContainingNotNullProperties() {
NodeTemplate nt = new NodeTemplate();
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
Map<String, Capability> capabilities = Maps.newHashMap();
nt.setCapabilities(capabilities);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
Capability capability1 = new Capability();
capabilities.put("capa1", capability1);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
Capability capability2 = new Capability();
Map<String, AbstractPropertyValue> properties = new HashMap<String, AbstractPropertyValue>();
capability2.setProperties(properties);
capabilities.put("capa2", capability2);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
properties.put("prop1", null);
Assert.assertFalse(utils.hasCapabilitiesContainingNotNullProperties(nt));
properties.put("prop2", new ScalarPropertyValue("value"));
Assert.assertTrue(utils.hasCapabilitiesContainingNotNullProperties(nt));
}
@Test
public void testRenderConstraint() {
GreaterOrEqualConstraint greaterOrEqualConstraint = new GreaterOrEqualConstraint();
Assert.assertEquals("greater_or_equal: null", utils.renderConstraint(greaterOrEqualConstraint));
greaterOrEqualConstraint.setGreaterOrEqual("1");
Assert.assertEquals("greater_or_equal: 1", utils.renderConstraint(greaterOrEqualConstraint));
GreaterThanConstraint greaterThanConstraint = new GreaterThanConstraint();
Assert.assertEquals("greater_than: null", utils.renderConstraint(greaterThanConstraint));
greaterThanConstraint.setGreaterThan("1");
Assert.assertEquals("greater_than: 1", utils.renderConstraint(greaterThanConstraint));
LessOrEqualConstraint lessOrEqualConstraint = new LessOrEqualConstraint();
Assert.assertEquals("less_or_equal: null", utils.renderConstraint(lessOrEqualConstraint));
lessOrEqualConstraint.setLessOrEqual("1");
Assert.assertEquals("less_or_equal: 1", utils.renderConstraint(lessOrEqualConstraint));
LessThanConstraint lessThanConstraint = new LessThanConstraint();
Assert.assertEquals("less_than: null", utils.renderConstraint(lessThanConstraint));
lessThanConstraint.setLessThan("1");
Assert.assertEquals("less_than: 1", utils.renderConstraint(lessThanConstraint));
LengthConstraint lengthConstraint = new LengthConstraint();
Assert.assertEquals("length: null", utils.renderConstraint(lengthConstraint));
lengthConstraint.setLength(1);
Assert.assertEquals("length: 1", utils.renderConstraint(lengthConstraint));
MaxLengthConstraint maxLengthConstraint = new MaxLengthConstraint();
Assert.assertEquals("max_length: null", utils.renderConstraint(maxLengthConstraint));
maxLengthConstraint.setMaxLength(1);
Assert.assertEquals("max_length: 1", utils.renderConstraint(maxLengthConstraint));
MinLengthConstraint minLengthConstraint = new MinLengthConstraint();
Assert.assertEquals("min_length: null", utils.renderConstraint(minLengthConstraint));
minLengthConstraint.setMinLength(1);
Assert.assertEquals("min_length: 1", utils.renderConstraint(minLengthConstraint));
PatternConstraint patternConstraint = new PatternConstraint();
Assert.assertEquals("pattern: null", utils.renderConstraint(patternConstraint));
patternConstraint.setPattern("a");
Assert.assertEquals("pattern: a", utils.renderConstraint(patternConstraint));
patternConstraint.setPattern("[.*]");
Assert.assertEquals("pattern: \"[.*]\"", utils.renderConstraint(patternConstraint));
EqualConstraint equalConstraint = new EqualConstraint();
Assert.assertEquals("equal: null", utils.renderConstraint(equalConstraint));
equalConstraint.setEqual("value");
Assert.assertEquals("equal: value", utils.renderConstraint(equalConstraint));
equalConstraint.setEqual(" value");
Assert.assertEquals("equal: \" value\"", utils.renderConstraint(equalConstraint));
InRangeConstraint inRangeConstraint = new InRangeConstraint();
Assert.assertEquals("in_range: []", utils.renderConstraint(inRangeConstraint));
List<String> inRange = Lists.newArrayList();
inRangeConstraint.setInRange(inRange);
Assert.assertEquals("in_range: []", utils.renderConstraint(inRangeConstraint));
inRange.add("1");
Assert.assertEquals("in_range: [1]", utils.renderConstraint(inRangeConstraint));
inRange.add("2");
Assert.assertEquals("in_range: [1, 2]", utils.renderConstraint(inRangeConstraint));
ValidValuesConstraint validValuesConstraint = new ValidValuesConstraint();
Assert.assertEquals("valid_values: []", utils.renderConstraint(validValuesConstraint));
List<String> validValues = Lists.newArrayList();
validValuesConstraint.setValidValues(validValues);
Assert.assertEquals("valid_values: []", utils.renderConstraint(validValuesConstraint));
validValues.add("value1");
Assert.assertEquals("valid_values: [value1]", utils.renderConstraint(validValuesConstraint));
validValues.add("value2 ");
Assert.assertEquals("valid_values: [value1, \"value2 \"]", utils.renderConstraint(validValuesConstraint));
validValues.add("value3,value4");
Assert.assertEquals("valid_values: [value1, \"value2 \", \"value3,value4\"]", utils.renderConstraint(validValuesConstraint));
// finally test an unknown constraint
AbstractPropertyConstraint abstractPropertyConstraint = new AbstractPropertyConstraint() {
@Override
public void validate(Object propertyValue) throws ConstraintViolationException {
}
@Override
public void initialize(IPropertyType<?> propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
}
};
Assert.assertEquals("", utils.renderConstraint(abstractPropertyConstraint));
}
private DeploymentArtifact createArtifact() {
DeploymentArtifact deploymentArtifact = new DeploymentArtifact();
deploymentArtifact.setArchiveName("test");
deploymentArtifact.setArchiveVersion("1.0");
return deploymentArtifact;
}
@Test
public void testArtifactsAndRepositoriesExport() {
Topology topology = new Topology();
topology.setNodeTemplates(Maps.newHashMap());
NodeTemplate node = new NodeTemplate();
node.setArtifacts(Maps.newHashMap());
topology.getNodeTemplates().put("Compute", node);
// no repositories
DeploymentArtifact deploymentArtifact = createArtifact();
deploymentArtifact.setArtifactRef("aaa/bbb.zip");
deploymentArtifact.setArtifactType("tosca.artifacts.File");
node.getArtifacts().put("local_war", deploymentArtifact);
Assert.assertFalse(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
String deploymentArtifactExport = ToscaSerializerUtils.formatArtifact(deploymentArtifact, 2);
Assert.assertEquals(" file: aaa/bbb.zip\n type: tosca.artifacts.File", deploymentArtifactExport);
// one repository should success
DeploymentArtifact deploymentArtifact2 = createArtifact();
deploymentArtifact2.setArtifactRef("aaa/bbb.zip");
deploymentArtifact2.setArtifactType("tosca.artifacts.File");
deploymentArtifact2.setRepositoryName("my_company");
deploymentArtifact2.setRepositoryURL("http://my_company.org");
deploymentArtifact2.setArtifactRepository("http");
deploymentArtifact2.setRepositoryCredential(Maps.newHashMap());
deploymentArtifact2.getRepositoryCredential().put("user", "my_user");
deploymentArtifact2.getRepositoryCredential().put("token", "<PASSWORD>");
node.getArtifacts().put("http_war", deploymentArtifact2);
Assert.assertTrue(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
String deploymentArtifact2Export = ToscaSerializerUtils.formatArtifact(deploymentArtifact2, 1);
String repositoriesExport = ToscaSerializerUtils.formatRepositories("test", "1.0", topology);
Assert.assertEquals(" file: aaa/bbb.zip\n type: tosca.artifacts.File\n repository: my_company", deploymentArtifact2Export);
Assert.assertEquals(" my_company:\n url: http://my_company.org\n type: http\n credential:\n token: <PASSWORD> user: my_user",
repositoriesExport);
// two repositories with different name
DeploymentArtifact deploymentArtifact3 = createArtifact();
deploymentArtifact3.setArtifactRef("aaa/ccc.zip");
deploymentArtifact3.setArtifactType("tosca.artifacts.File");
deploymentArtifact3.setRepositoryName("my_companyBis");
deploymentArtifact3.setRepositoryURL("http://my_company.org");
deploymentArtifact3.setArtifactRepository("maven");
node.getArtifacts().put("http_war2", deploymentArtifact3);
Assert.assertTrue(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
repositoriesExport = ToscaSerializerUtils.formatRepositories("test", "1.0", topology);
Assert.assertEquals(
" my_company:\n url: http://my_company.org\n type: http\n credential:\n token: <PASSWORD> user: my_user\n my_companyBis:\n url: http://my_company.org\n type: maven",
repositoriesExport);
// add a new artifact with an already existing repository, should not duplicate the repository
DeploymentArtifact deploymentArtifact4 = createArtifact();
deploymentArtifact4.setArtifactRef("aaa/ddd.zip");
deploymentArtifact4.setArtifactType("tosca.artifacts.File");
deploymentArtifact4.setRepositoryName("my_company");
deploymentArtifact4.setRepositoryURL("http://my_company.org");
deploymentArtifact4.setArtifactRepository("http");
node.getArtifacts().put("http_war3", deploymentArtifact4);
Assert.assertTrue(ToscaSerializerUtils.hasRepositories("test", "1.0", topology));
repositoriesExport = ToscaSerializerUtils.formatRepositories("test", "1.0", topology);
Assert.assertEquals(
" my_company:\n url: http://my_company.org\n type: http\n credential:\n token: <PASSWORD> user: my_user\n my_companyBis:\n url: http://my_company.org\n type: maven",
repositoriesExport);
}
}
| 18,834 | 0.717821 | 0.710387 | 336 | 55.047619 | 35.935177 | 208 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.092262 | false | false | 9 |
4ffa3e333aa931fd90baf785c2860543dbe51889 | 13,125,420,089,852 | b7456c5132c8dbd317250d11f4329f7e7a49b4c7 | /code/api/api/src/test/java/com/decathlon/ara/util/factory/CycleDefinitionFactory.java | b607d490fef0fef80cc631b5d75893b7ad61ad1e | [
"Apache-2.0",
"CC-BY-NC-SA-4.0"
] | permissive | Decathlon/ara | https://github.com/Decathlon/ara | f6a20d07c27d1244f0b25fddb409559a6b2c0958 | 0d7e3cb991fb813cf4fd04fa579fbf4216defd19 | refs/heads/main | 2023-08-21T15:59:29.189000 | 2023-06-09T15:51:19 | 2023-06-09T15:51:19 | 179,502,880 | 92 | 28 | Apache-2.0 | false | 2023-08-16T10:47:15 | 2019-04-04T13:27:58 | 2023-03-31T08:51:30 | 2023-08-16T10:47:10 | 25,289 | 76 | 17 | 199 | Java | false | false | package com.decathlon.ara.util.factory;
import com.decathlon.ara.domain.CycleDefinition;
import com.decathlon.ara.util.TestUtil;
public class CycleDefinitionFactory {
public static CycleDefinition get(long projectId) {
return get(null, projectId, null, null, 0);
}
public static CycleDefinition get(Long id, long projectId) {
return get(id, projectId, null, null, 0);
}
public static CycleDefinition get(Long id, long projectId, String branch, String name, int branchPosition) {
CycleDefinition cycleDefinition = new CycleDefinition();
TestUtil.setField(cycleDefinition, "id", id);
cycleDefinition.setProjectId(projectId);
TestUtil.setField(cycleDefinition, "branch", branch);
TestUtil.setField(cycleDefinition, "name", name);
cycleDefinition.setBranchPosition(branchPosition);
return cycleDefinition;
}
}
| UTF-8 | Java | 908 | java | CycleDefinitionFactory.java | Java | [] | null | [] | package com.decathlon.ara.util.factory;
import com.decathlon.ara.domain.CycleDefinition;
import com.decathlon.ara.util.TestUtil;
public class CycleDefinitionFactory {
public static CycleDefinition get(long projectId) {
return get(null, projectId, null, null, 0);
}
public static CycleDefinition get(Long id, long projectId) {
return get(id, projectId, null, null, 0);
}
public static CycleDefinition get(Long id, long projectId, String branch, String name, int branchPosition) {
CycleDefinition cycleDefinition = new CycleDefinition();
TestUtil.setField(cycleDefinition, "id", id);
cycleDefinition.setProjectId(projectId);
TestUtil.setField(cycleDefinition, "branch", branch);
TestUtil.setField(cycleDefinition, "name", name);
cycleDefinition.setBranchPosition(branchPosition);
return cycleDefinition;
}
}
| 908 | 0.714758 | 0.712555 | 26 | 33.923077 | 29.116375 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.192308 | false | false | 9 |
e857ad593094746afd2d68dc0a0b6f33fe75cb82 | 11,269,994,208,164 | eb0398be0362c9450132b5d425f89983540b7a29 | /client/Chat.java | 84df854b2287af5f119a338f94f9da1a15aeff54 | [] | no_license | SanketShetye/TestChat | https://github.com/SanketShetye/TestChat | b3e22b53b71afa67ee04e24b7993b1afff10d490 | 3936682088841728cf10f82120c7cce4521b27c2 | refs/heads/master | 2020-03-24T00:00:56.888000 | 2018-07-25T11:46:59 | 2018-07-25T11:46:59 | 142,268,515 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Chat {
public static final String QUIT_COMMAND = ".q";
public static final String CHANGE_USER_COMMAND = ".chrec";
public static final int REFRESH_RATE_FOR_RECIEVE_THREAD = 300;//in ms
public static String username = "undefined";
public static String password = "";
public static String accessToken = null;
public static String recipientUsername;
public static Scanner sc = new Scanner(System.in);
public static void main(String args[]){
//Query the server for authenticating the user
do{
System.out.print("Enter Your Username: ");
username = sc.next();
System.out.print("Enter Your Password: ");
password = sc.next();
}while(LoginAuth.loginUser() != true);
sc.nextLine();//Garbage
System.out.println("\nYour username is "+username);
System.out.print("Enter recipient: ");
recipientUsername = sc.next();
sc.nextLine();//consume the garbage character;
//Message write thread
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.print("Enter Message: ");
String message = sc.nextLine();
//System.out.printf("Message - '%s' == %c!..\n",message,message.charAt(0));
if(message.length()==0){
System.out.println("\tEmpty message not sent");
continue;
}
if(message.equals(QUIT_COMMAND))
System.exit(0);
if(message.length()>CHANGE_USER_COMMAND.length() && message.substring(0,CHANGE_USER_COMMAND.length()).equals(CHANGE_USER_COMMAND)){
recipientUsername = message.substring(CHANGE_USER_COMMAND.length()+1);
System.out.println("Recipient changed to "+recipientUsername);
continue;
}
Send.sendMessage(recipientUsername,message);
}
}
}).start();
//Message recieve thread
new Thread(new Runnable() {
@Override
public void run() {
while(true){
Recieve.recieveMessage();
//System.out.println("Recieve Message Running");
try {
Thread.sleep(REFRESH_RATE_FOR_RECIEVE_THREAD);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
| UTF-8 | Java | 2,271 | java | Chat.java | Java | [
{
"context": "= 300;//in ms\n\t\n\tpublic static String username = \"undefined\";\n\tpublic static String password = \"\";\n\tpublic st",
"end": 325,
"score": 0.998994767665863,
"start": 316,
"tag": "USERNAME",
"value": "undefined"
},
{
"context": ".out.print(\"Enter Your Password: \... | null | [] | import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Chat {
public static final String QUIT_COMMAND = ".q";
public static final String CHANGE_USER_COMMAND = ".chrec";
public static final int REFRESH_RATE_FOR_RECIEVE_THREAD = 300;//in ms
public static String username = "undefined";
public static String password = "";
public static String accessToken = null;
public static String recipientUsername;
public static Scanner sc = new Scanner(System.in);
public static void main(String args[]){
//Query the server for authenticating the user
do{
System.out.print("Enter Your Username: ");
username = sc.next();
System.out.print("Enter Your Password: ");
password = <PASSWORD>();
}while(LoginAuth.loginUser() != true);
sc.nextLine();//Garbage
System.out.println("\nYour username is "+username);
System.out.print("Enter recipient: ");
recipientUsername = sc.next();
sc.nextLine();//consume the garbage character;
//Message write thread
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.print("Enter Message: ");
String message = sc.nextLine();
//System.out.printf("Message - '%s' == %c!..\n",message,message.charAt(0));
if(message.length()==0){
System.out.println("\tEmpty message not sent");
continue;
}
if(message.equals(QUIT_COMMAND))
System.exit(0);
if(message.length()>CHANGE_USER_COMMAND.length() && message.substring(0,CHANGE_USER_COMMAND.length()).equals(CHANGE_USER_COMMAND)){
recipientUsername = message.substring(CHANGE_USER_COMMAND.length()+1);
System.out.println("Recipient changed to "+recipientUsername);
continue;
}
Send.sendMessage(recipientUsername,message);
}
}
}).start();
//Message recieve thread
new Thread(new Runnable() {
@Override
public void run() {
while(true){
Recieve.recieveMessage();
//System.out.println("Recieve Message Running");
try {
Thread.sleep(REFRESH_RATE_FOR_RECIEVE_THREAD);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
| 2,274 | 0.648613 | 0.64509 | 90 | 24.233334 | 23.756191 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.322222 | false | false | 9 |
8d7676b1a19e3dc0b1d24c59bc6301c8395353ee | 15,144,054,697,907 | d38ca0b9791a30885928764b8713dbe4e121eda4 | /de/thexxturboxx/blockhelper/PacketInfo.java | 3fb560a615e252d13055b34cbbeed9a1927b5e8c | [
"MIT"
] | permissive | NoraTheGamer/BlockHelper | https://github.com/NoraTheGamer/BlockHelper | f1f1eab60e081b79af099dc4828fdccedddfaa2f | 6f818ad7a9e9ba64f754457c461a8b61f7f63bd9 | refs/heads/master | 2022-04-20T09:01:25.511000 | 2020-04-18T14:21:48 | 2020-04-18T14:21:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.thexxturboxx.blockhelper;
import net.minecraft.util.MovingObjectPosition;
class PacketInfo {
MovingObjectPosition mop;
int dimId;
MopType mt;
public int entityId;
PacketInfo(int dimId, MovingObjectPosition mop, MopType mt) {
this(dimId, mop, mt, -1);
}
PacketInfo(int dimId, MovingObjectPosition mop, MopType mt, int entityId) {
this.dimId = dimId;
this.mop = mop;
this.mt = mt;
this.entityId = entityId;
}
}
| UTF-8 | Java | 444 | java | PacketInfo.java | Java | [] | null | [] | package de.thexxturboxx.blockhelper;
import net.minecraft.util.MovingObjectPosition;
class PacketInfo {
MovingObjectPosition mop;
int dimId;
MopType mt;
public int entityId;
PacketInfo(int dimId, MovingObjectPosition mop, MopType mt) {
this(dimId, mop, mt, -1);
}
PacketInfo(int dimId, MovingObjectPosition mop, MopType mt, int entityId) {
this.dimId = dimId;
this.mop = mop;
this.mt = mt;
this.entityId = entityId;
}
}
| 444 | 0.72973 | 0.727477 | 23 | 18.304348 | 20.373545 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.608696 | false | false | 9 |
ad7d4882b68b63be834528d9ae3fd725ecd0bc93 | 32,547,262,192,459 | 31280b32ac8e886c0fbd0239b890bbb02726af3b | /activitidemo-common/src/main/java/com/nihilent/activitidemo/common/domain/AbstractEntity.java | b706702b30abbc1169d0c151a8b52bb8a268ac36 | [] | no_license | sharadchandra/ActivitiDemo | https://github.com/sharadchandra/ActivitiDemo | 9958cdf957e6af8df777e95d68cabc2febd54676 | ef8e76c3152741f27caf393fada087053c7b65fb | refs/heads/master | 2019-06-02T09:16:51.144000 | 2015-08-26T14:45:21 | 2015-08-26T14:45:21 | 41,421,356 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nihilent.activitidemo.common.domain;
import javax.persistence.*;
@MappedSuperclass
public class AbstractEntity {
protected Long id;
protected Integer version;
protected String modifiedBy;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id",unique=true, nullable=false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setVersion(Integer version) {
this.version = version;
}
@Version
public Integer getVersion() {
return version;
}
@Column(name = "modified_by")
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
} | UTF-8 | Java | 805 | java | AbstractEntity.java | Java | [] | null | [] | package com.nihilent.activitidemo.common.domain;
import javax.persistence.*;
@MappedSuperclass
public class AbstractEntity {
protected Long id;
protected Integer version;
protected String modifiedBy;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id",unique=true, nullable=false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setVersion(Integer version) {
this.version = version;
}
@Version
public Integer getVersion() {
return version;
}
@Column(name = "modified_by")
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
} | 805 | 0.640994 | 0.640994 | 41 | 18.658537 | 16.837255 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.317073 | false | false | 9 |
9f1126efae18e64236b2de142274547942e5abe1 | 8,942,121,928,037 | ede7a26f5f46d39d083e29eefc3e8cec39cca892 | /cms/cms-utils/src/main/java/com/i3tv/cms/utils/constants/SiteConstants.java | 8859378d450afe690c637ebf849ccb70465b4584 | [] | no_license | juanminet/cms-atres | https://github.com/juanminet/cms-atres | d3d9b55f23e85b4dd78e4d886a80cd1ed18e5bd3 | 9178cf11d29bd83ae2d89e43932a8a96269f9123 | refs/heads/master | 2015-08-21T00:59:15.735000 | 2015-02-27T15:58:31 | 2015-02-27T15:58:31 | 31,426,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.i3tv.cms.utils.constants;
/**
* IDs de Sites
*
*/
public class SiteConstants {
public static final Long ID_NEOXKIDZ = 1L;
public static final Long ID_ONDACERO = 2L;
public static final Long ID_EUROPAFM = 3L;
}
| UTF-8 | Java | 230 | java | SiteConstants.java | Java | [] | null | [] | package com.i3tv.cms.utils.constants;
/**
* IDs de Sites
*
*/
public class SiteConstants {
public static final Long ID_NEOXKIDZ = 1L;
public static final Long ID_ONDACERO = 2L;
public static final Long ID_EUROPAFM = 3L;
}
| 230 | 0.713043 | 0.695652 | 12 | 18.166666 | 18.22925 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 9 |
9c2f07bfd2493ffab9a43158c0a5948baf37bf1a | 8,942,121,927,987 | 1339f33a43d2523e188b5e12e5d56e08a993656e | /HealthySLife_android/app/src/main/java/com/example/admin/healthyslife_android/fragment/HeartRateMonitorFragment.java | e5070379dfec789bb04d5ec9669364202e6dcf87 | [] | no_license | nienyoung/HealthySLife | https://github.com/nienyoung/HealthySLife | ea421cc6b84b0d058d9e27f9bbbf6fefbb6d8901 | 74b3ff53d53a5122b0c13fac086c335ee6f2bc00 | refs/heads/master | 2020-03-22T03:01:50.160000 | 2018-09-09T16:01:56 | 2018-09-09T16:01:56 | 139,409,114 | 2 | 0 | null | false | 2018-07-18T09:08:23 | 2018-07-02T07:48:37 | 2018-07-10T01:18:59 | 2018-07-18T09:08:22 | 1,966 | 2 | 0 | 0 | Java | false | null | package com.example.admin.healthyslife_android.fragment;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.healthyslife_android.R;
import java.util.Collections;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.example.admin.healthyslife_android.utils.ImageUtil.decodeYUV420SPtoRedAvg;
/**
* @author wu jingji
*/
public class HeartRateMonitorFragment extends Fragment implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
/**
* Tag for the {@link Log}.
*/
private static final String TAG = "HRMonitorFragment";
private static final int IMAGE_WIDTH = 320;
private static final int IMAGE_HEIGHT = 180;
private static final int ACQUIRE_CAMERA_TIMEOUT = 2500;
public static final int STATE_STOP = 0;
public static final int STATE_START = 2;
/**
* Heart rate refresh rate
*/
public static final int REFRESH_RATE = 5;
private int mState;
private static final AtomicBoolean PROCESSING = new AtomicBoolean(false);
private static int AVERAGE_INDEX = 0;
private static final int AVERAGE_ARRAY_SIZE = 4;
private static final int[] AVERAGE_ARRAY = new int[AVERAGE_ARRAY_SIZE];
public static enum TYPE {
GREEN, RED
}
private static TYPE currentType = TYPE.GREEN;
private static int BEATS_INDEX = 0;
private static final int BEATS_ARRAY_SIZE = 3;
private static final int[] BEATS_ARRAY = new int[BEATS_ARRAY_SIZE];
private static double beats = 0;
private static long startTime = 0;
private TextView mHeartRateTextView;
private TextView mTipsTextView;
/**
* ID of the current {@link CameraDevice}.
*/
private String mCameraId;
/**
* A {@link CameraCaptureSession } for camera preview.
*/
private CameraCaptureSession mCaptureSession;
/**
* A reference to the opened {@link CameraDevice}.
*/
private CameraDevice mCameraDevice;
/**
* {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
// This method is called when the camera is opened. We start camera preview here.
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
}
};
/**
* An additional thread for running tasks that shouldn't block the UI.
*/
private HandlerThread mBackgroundThread;
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler mBackgroundHandler;
/**
* An {@link ImageReader} that handles still image capture.
*/
private ImageReader mImageReader;
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* still image is ready to be saved.
*/
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
if (!PROCESSING.compareAndSet(false, true)) {
return;
}
try (Image image = reader.acquireNextImage()) {
int imgAvg = decodeYUV420SPtoRedAvg(image);
if (imgAvg == 0 || imgAvg == 255) {
PROCESSING.set(false);
return;
}
int averageArrayAvg = 0;
int averageArrayCnt = 0;
for (int i = 0; i < AVERAGE_ARRAY.length; i++) {
if (AVERAGE_ARRAY[i] > 0) {
averageArrayAvg += AVERAGE_ARRAY[i];
averageArrayCnt++;
}
}
int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
TYPE newType = currentType;
if (imgAvg < rollingAverage) {
newType = TYPE.RED;
if (newType != currentType) {
beats++;
}
} else if (imgAvg > rollingAverage) {
newType = TYPE.GREEN;
}
if (AVERAGE_INDEX == AVERAGE_ARRAY_SIZE) {
AVERAGE_INDEX = 0;
}
AVERAGE_ARRAY[AVERAGE_INDEX] = imgAvg;
AVERAGE_INDEX++;
// Transitioned from one state to another to the same
if (newType != currentType) {
currentType = newType;
}
long endTime = System.currentTimeMillis();
double totalTimeInSecs = (endTime - startTime) / 1000d;
if (totalTimeInSecs >= REFRESH_RATE) {
double bps = (beats / totalTimeInSecs);
int dpm = (int) (bps * 60d);
if (dpm < 30 || dpm > 180) {
startTime = System.currentTimeMillis();
beats = 0;
PROCESSING.set(false);
return;
}
if (BEATS_INDEX == BEATS_ARRAY_SIZE) {
BEATS_INDEX = 0;
}
BEATS_ARRAY[BEATS_INDEX] = dpm;
BEATS_INDEX++;
int beatsArrayAvg = 0;
int beatsArrayCnt = 0;
for (int i = 0; i < BEATS_ARRAY.length; i++) {
if (BEATS_ARRAY[i] > 0) {
beatsArrayAvg += BEATS_ARRAY[i];
beatsArrayCnt++;
}
}
final int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
updateHeartRate(beatsAvg);
Log.i(TAG, "onImageAvailable: heart rate:" + String.valueOf(beatsAvg));
startTime = System.currentTimeMillis();
beats = 0;
}
} catch (Exception e) {
Log.e(TAG, "onImageAvailable", e);
}
PROCESSING.set(false);
}
};
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
private CaptureRequest.Builder mPreviewRequestBuilder;
/**
* {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
*/
private CaptureRequest mPreviewRequest;
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
/**
* Whether the current camera device supports Flash or not.
*/
private boolean mFlashSupported;
public static HeartRateMonitorFragment newInstance() {
return new HeartRateMonitorFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_heart_rate_monitor, container, false);
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
view.findViewById(R.id.btn_heartRateMonitor_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mState == STATE_STOP) {
mState = STATE_START;
resetHeartRateMonitor();
mTipsTextView.setVisibility(View.VISIBLE);
openCamera();
} else {
mState = STATE_STOP;
mTipsTextView.setVisibility(View.INVISIBLE);
closeCamera();
}
}
});
mHeartRateTextView = view.findViewById(R.id.tv_heartRateMonitor_heartRate);
mTipsTextView = view.findViewById(R.id.tv_heartRateMonitor_tips);
mTipsTextView.setVisibility(View.INVISIBLE);
}
@Override
public void onResume() {
super.onResume();
startBackgroundThread();
Log.i(TAG, "onStart: monitor started: " + (mState == STATE_START));
if (mState == STATE_START) {
openCamera();
}
}
@Override
public void onPause() {
Log.i(TAG, "onPause");
if (mState == STATE_START) {
closeCamera();
}
stopBackgroundThread();
super.onPause();
}
private void resetHeartRateMonitor() {
AVERAGE_INDEX = 0;
for (int i = 0; i < AVERAGE_ARRAY.length; i++) {
AVERAGE_ARRAY[i] = 0;
}
currentType = TYPE.GREEN;
BEATS_INDEX = 0;
for (int i = 0; i < BEATS_ARRAY.length; i++) {
BEATS_ARRAY[i] = 0;
}
beats = 0;
startTime = 0;
}
private void requestCameraPermission() {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
} else {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
ErrorDialog.newInstance(getString(R.string.request_permission))
.show(getChildFragmentManager(), FRAGMENT_DIALOG);
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
/**
* Sets up member variables related to camera.
*/
private void setUpCameraOutputs() {
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
ImageFormat.YUV_420_888, 2);
mImageReader.setOnImageAvailableListener(
mOnImageAvailableListener, mBackgroundHandler);
Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
// Check if the flash is supported.
Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
mFlashSupported = available == null ? false : available;
mCameraId = cameraId;
return;
}
} catch (CameraAccessException e) {
Log.e(TAG, "setUpCameraOutputs: ", e);
e.printStackTrace();
} catch (NullPointerException e) {
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
ErrorDialog.newInstance(getString(R.string.camera_error))
.show(getChildFragmentManager(), FRAGMENT_DIALOG);
}
}
/**
* Opens the camera specified by {@link HeartRateMonitorFragment#mCameraId}.
*/
private void openCamera() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
return;
}
setUpCameraOutputs();
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
if (!mCameraOpenCloseLock.tryAcquire(ACQUIRE_CAMERA_TIMEOUT, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e(TAG, "openCamera: cannot access camera", e);
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
/**
* Closes the current {@link CameraDevice}.
*/
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
if (null != mCaptureSession) {
mCaptureSession.close();
mCaptureSession = null;
}
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mImageReader) {
mImageReader.close();
mImageReader = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
mCameraOpenCloseLock.release();
}
}
/**
* Starts a background thread and its {@link Handler}.
*/
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
/**
* Stops the background thread and its {@link Handler}.
*/
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/
private void createCameraPreviewSession() {
try {
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice.createCaptureSession(Collections.singletonList(mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (null == mCameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
mCaptureSession = cameraCaptureSession;
try {
// Auto focus should be continuous for camera preview.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// Flash is automatically enabled when necessary.
setFlash(mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
mPreviewRequest = mPreviewRequestBuilder.build();
mCaptureSession.setRepeatingRequest(mPreviewRequest,
null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(
@NonNull CameraCaptureSession cameraCaptureSession) {
showToast("Failed");
}
}, null
);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void setFlash(CaptureRequest.Builder requestBuilder) {
if (mFlashSupported) {
requestBuilder.set(CaptureRequest.FLASH_MODE,
CaptureRequest.FLASH_MODE_TORCH);
}
}
/**
* Shows an error message dialog.
*/
public static class ErrorDialog extends DialogFragment {
private static final String ARG_MESSAGE = "message";
public static ErrorDialog newInstance(String message) {
ErrorDialog dialog = new ErrorDialog();
Bundle args = new Bundle();
args.putString(ARG_MESSAGE, message);
dialog.setArguments(args);
return dialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Activity activity = getActivity();
return new AlertDialog.Builder(activity)
.setMessage(getArguments().getString(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.create();
}
}
/**
* Shows OK/Cancel confirmation dialog about camera permission.
*/
public static class ConfirmationDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Fragment parent = getParentFragment();
return new AlertDialog.Builder(getActivity())
.setMessage(R.string.request_permission)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
parent.requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
})
.create();
}
}
/**
* Shows a {@link Toast} on the UI thread.
*
* @param text The message to show
*/
private void showToast(final String text) {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
}
});
}
}
private void updateHeartRate(final int heartRate) {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mHeartRateTextView.setText(getString(R.string.main_healthy_heartRateFormat, heartRate));
}
});
}
}
}
| UTF-8 | Java | 22,483 | java | HeartRateMonitorFragment.java | Java | [
{
"context": ".ImageUtil.decodeYUV420SPtoRedAvg;\n\n/**\n * @author wu jingji\n */\npublic class HeartRateMonitorFragment extends",
"end": 1599,
"score": 0.9994476437568665,
"start": 1590,
"tag": "NAME",
"value": "wu jingji"
}
] | null | [] | package com.example.admin.healthyslife_android.fragment;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.healthyslife_android.R;
import java.util.Collections;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.example.admin.healthyslife_android.utils.ImageUtil.decodeYUV420SPtoRedAvg;
/**
* @author <NAME>
*/
public class HeartRateMonitorFragment extends Fragment implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
/**
* Tag for the {@link Log}.
*/
private static final String TAG = "HRMonitorFragment";
private static final int IMAGE_WIDTH = 320;
private static final int IMAGE_HEIGHT = 180;
private static final int ACQUIRE_CAMERA_TIMEOUT = 2500;
public static final int STATE_STOP = 0;
public static final int STATE_START = 2;
/**
* Heart rate refresh rate
*/
public static final int REFRESH_RATE = 5;
private int mState;
private static final AtomicBoolean PROCESSING = new AtomicBoolean(false);
private static int AVERAGE_INDEX = 0;
private static final int AVERAGE_ARRAY_SIZE = 4;
private static final int[] AVERAGE_ARRAY = new int[AVERAGE_ARRAY_SIZE];
public static enum TYPE {
GREEN, RED
}
private static TYPE currentType = TYPE.GREEN;
private static int BEATS_INDEX = 0;
private static final int BEATS_ARRAY_SIZE = 3;
private static final int[] BEATS_ARRAY = new int[BEATS_ARRAY_SIZE];
private static double beats = 0;
private static long startTime = 0;
private TextView mHeartRateTextView;
private TextView mTipsTextView;
/**
* ID of the current {@link CameraDevice}.
*/
private String mCameraId;
/**
* A {@link CameraCaptureSession } for camera preview.
*/
private CameraCaptureSession mCaptureSession;
/**
* A reference to the opened {@link CameraDevice}.
*/
private CameraDevice mCameraDevice;
/**
* {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
// This method is called when the camera is opened. We start camera preview here.
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
}
};
/**
* An additional thread for running tasks that shouldn't block the UI.
*/
private HandlerThread mBackgroundThread;
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler mBackgroundHandler;
/**
* An {@link ImageReader} that handles still image capture.
*/
private ImageReader mImageReader;
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* still image is ready to be saved.
*/
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
if (!PROCESSING.compareAndSet(false, true)) {
return;
}
try (Image image = reader.acquireNextImage()) {
int imgAvg = decodeYUV420SPtoRedAvg(image);
if (imgAvg == 0 || imgAvg == 255) {
PROCESSING.set(false);
return;
}
int averageArrayAvg = 0;
int averageArrayCnt = 0;
for (int i = 0; i < AVERAGE_ARRAY.length; i++) {
if (AVERAGE_ARRAY[i] > 0) {
averageArrayAvg += AVERAGE_ARRAY[i];
averageArrayCnt++;
}
}
int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
TYPE newType = currentType;
if (imgAvg < rollingAverage) {
newType = TYPE.RED;
if (newType != currentType) {
beats++;
}
} else if (imgAvg > rollingAverage) {
newType = TYPE.GREEN;
}
if (AVERAGE_INDEX == AVERAGE_ARRAY_SIZE) {
AVERAGE_INDEX = 0;
}
AVERAGE_ARRAY[AVERAGE_INDEX] = imgAvg;
AVERAGE_INDEX++;
// Transitioned from one state to another to the same
if (newType != currentType) {
currentType = newType;
}
long endTime = System.currentTimeMillis();
double totalTimeInSecs = (endTime - startTime) / 1000d;
if (totalTimeInSecs >= REFRESH_RATE) {
double bps = (beats / totalTimeInSecs);
int dpm = (int) (bps * 60d);
if (dpm < 30 || dpm > 180) {
startTime = System.currentTimeMillis();
beats = 0;
PROCESSING.set(false);
return;
}
if (BEATS_INDEX == BEATS_ARRAY_SIZE) {
BEATS_INDEX = 0;
}
BEATS_ARRAY[BEATS_INDEX] = dpm;
BEATS_INDEX++;
int beatsArrayAvg = 0;
int beatsArrayCnt = 0;
for (int i = 0; i < BEATS_ARRAY.length; i++) {
if (BEATS_ARRAY[i] > 0) {
beatsArrayAvg += BEATS_ARRAY[i];
beatsArrayCnt++;
}
}
final int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
updateHeartRate(beatsAvg);
Log.i(TAG, "onImageAvailable: heart rate:" + String.valueOf(beatsAvg));
startTime = System.currentTimeMillis();
beats = 0;
}
} catch (Exception e) {
Log.e(TAG, "onImageAvailable", e);
}
PROCESSING.set(false);
}
};
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
private CaptureRequest.Builder mPreviewRequestBuilder;
/**
* {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
*/
private CaptureRequest mPreviewRequest;
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
/**
* Whether the current camera device supports Flash or not.
*/
private boolean mFlashSupported;
public static HeartRateMonitorFragment newInstance() {
return new HeartRateMonitorFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_heart_rate_monitor, container, false);
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
view.findViewById(R.id.btn_heartRateMonitor_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mState == STATE_STOP) {
mState = STATE_START;
resetHeartRateMonitor();
mTipsTextView.setVisibility(View.VISIBLE);
openCamera();
} else {
mState = STATE_STOP;
mTipsTextView.setVisibility(View.INVISIBLE);
closeCamera();
}
}
});
mHeartRateTextView = view.findViewById(R.id.tv_heartRateMonitor_heartRate);
mTipsTextView = view.findViewById(R.id.tv_heartRateMonitor_tips);
mTipsTextView.setVisibility(View.INVISIBLE);
}
@Override
public void onResume() {
super.onResume();
startBackgroundThread();
Log.i(TAG, "onStart: monitor started: " + (mState == STATE_START));
if (mState == STATE_START) {
openCamera();
}
}
@Override
public void onPause() {
Log.i(TAG, "onPause");
if (mState == STATE_START) {
closeCamera();
}
stopBackgroundThread();
super.onPause();
}
private void resetHeartRateMonitor() {
AVERAGE_INDEX = 0;
for (int i = 0; i < AVERAGE_ARRAY.length; i++) {
AVERAGE_ARRAY[i] = 0;
}
currentType = TYPE.GREEN;
BEATS_INDEX = 0;
for (int i = 0; i < BEATS_ARRAY.length; i++) {
BEATS_ARRAY[i] = 0;
}
beats = 0;
startTime = 0;
}
private void requestCameraPermission() {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
} else {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
ErrorDialog.newInstance(getString(R.string.request_permission))
.show(getChildFragmentManager(), FRAGMENT_DIALOG);
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
/**
* Sets up member variables related to camera.
*/
private void setUpCameraOutputs() {
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
ImageFormat.YUV_420_888, 2);
mImageReader.setOnImageAvailableListener(
mOnImageAvailableListener, mBackgroundHandler);
Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
// Check if the flash is supported.
Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
mFlashSupported = available == null ? false : available;
mCameraId = cameraId;
return;
}
} catch (CameraAccessException e) {
Log.e(TAG, "setUpCameraOutputs: ", e);
e.printStackTrace();
} catch (NullPointerException e) {
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
ErrorDialog.newInstance(getString(R.string.camera_error))
.show(getChildFragmentManager(), FRAGMENT_DIALOG);
}
}
/**
* Opens the camera specified by {@link HeartRateMonitorFragment#mCameraId}.
*/
private void openCamera() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
return;
}
setUpCameraOutputs();
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
if (!mCameraOpenCloseLock.tryAcquire(ACQUIRE_CAMERA_TIMEOUT, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e(TAG, "openCamera: cannot access camera", e);
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
/**
* Closes the current {@link CameraDevice}.
*/
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
if (null != mCaptureSession) {
mCaptureSession.close();
mCaptureSession = null;
}
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mImageReader) {
mImageReader.close();
mImageReader = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
mCameraOpenCloseLock.release();
}
}
/**
* Starts a background thread and its {@link Handler}.
*/
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
/**
* Stops the background thread and its {@link Handler}.
*/
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/
private void createCameraPreviewSession() {
try {
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice.createCaptureSession(Collections.singletonList(mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (null == mCameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
mCaptureSession = cameraCaptureSession;
try {
// Auto focus should be continuous for camera preview.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// Flash is automatically enabled when necessary.
setFlash(mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
mPreviewRequest = mPreviewRequestBuilder.build();
mCaptureSession.setRepeatingRequest(mPreviewRequest,
null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(
@NonNull CameraCaptureSession cameraCaptureSession) {
showToast("Failed");
}
}, null
);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void setFlash(CaptureRequest.Builder requestBuilder) {
if (mFlashSupported) {
requestBuilder.set(CaptureRequest.FLASH_MODE,
CaptureRequest.FLASH_MODE_TORCH);
}
}
/**
* Shows an error message dialog.
*/
public static class ErrorDialog extends DialogFragment {
private static final String ARG_MESSAGE = "message";
public static ErrorDialog newInstance(String message) {
ErrorDialog dialog = new ErrorDialog();
Bundle args = new Bundle();
args.putString(ARG_MESSAGE, message);
dialog.setArguments(args);
return dialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Activity activity = getActivity();
return new AlertDialog.Builder(activity)
.setMessage(getArguments().getString(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.create();
}
}
/**
* Shows OK/Cancel confirmation dialog about camera permission.
*/
public static class ConfirmationDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Fragment parent = getParentFragment();
return new AlertDialog.Builder(getActivity())
.setMessage(R.string.request_permission)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
parent.requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
})
.create();
}
}
/**
* Shows a {@link Toast} on the UI thread.
*
* @param text The message to show
*/
private void showToast(final String text) {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
}
});
}
}
private void updateHeartRate(final int heartRate) {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mHeartRateTextView.setText(getString(R.string.main_healthy_heartRateFormat, heartRate));
}
});
}
}
}
| 22,480 | 0.567451 | 0.56367 | 619 | 35.321487 | 27.606543 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483037 | false | false | 9 |
d69985a31be96656be36ec749add1b9fbff4efb8 | 24,257,975,305,353 | 562972b34fc8f6a6ae66d229cba6d53eafd9a6f5 | /app/src/main/java/com/china/cibn/bangtvmobile/bangtv/module/home/history/HistoryFragment.java | 59413b5950dfbbc579af245ea1e2622a48162088 | [
"Apache-2.0"
] | permissive | gongzaijing/Mobile_NiHaoTV_Android | https://github.com/gongzaijing/Mobile_NiHaoTV_Android | df5de32daa402937a1f86496dd9726734e7e754a | 8a287558700a01830ab7f245ccb484e1575e8776 | refs/heads/master | 2022-10-17T17:04:02.522000 | 2020-06-17T08:14:29 | 2020-06-17T08:14:29 | 258,475,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.china.cibn.bangtvmobile.bangtv.module.home.history;
import butterknife.BindView;
import com.china.cibn.bangtvmobile.bangtv.apapter.HistoryListAdapter;
import com.china.cibn.bangtvmobile.bangtv.base.RxLazyFragment;
import com.china.cibn.bangtvmobile.bangtv.dal.PlayRecordHelpler;
import com.china.cibn.bangtvmobile.bangtv.entity.HistoryListInfo;
import com.china.cibn.bangtvmobile.bangtv.module.common.BangTVMainActivity;
import com.china.cibn.bangtvmobile.R;
import com.china.cibn.bangtvmobile.bangtv.widget.CustomEmptyView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* bix by gz 2018/04/24 14:12
*
* <p/>
* 历史记录
*/
public class HistoryFragment extends RxLazyFragment {
@BindView(R.id.empty_view)
CustomEmptyView mCustomEmptyView;
@BindView(R.id.toolbar)
Toolbar mToolbar;
//fix by gz 2018/04/20 横向滑动控件
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout mSwipeRefreshLayout;
//fix by gz 2018/04/20 横向滑动控件
@BindView(R.id.recycle)
RecyclerView mRecyclerView;
private HistoryListAdapter mAdapter;
private List<HistoryListInfo.HistoryListBean> historyListBeanList ;
private String mId;
private HistoryDataHandle historyDataHandle; //fix by gz 2018/04/19 database
private PlayRecordHelpler mPlayRecordOpt; //fix by gz 2018/04/19 database
public static HistoryFragment newInstance() {
return new HistoryFragment();
}
@Override
public int getLayoutResId() {
return R.layout.activity_history_bangtv;
}
@Override
public void finishCreateView(Bundle state) {
initCustomEmptyView();
initRefreshLayout();
initRecyclerView();
initToolBar();
}
public void initCustomEmptyView() {
historyListBeanList= new ArrayList<>();
mCustomEmptyView.setEmptyImage(R.drawable.ic_movie_pay_order_error03);
mCustomEmptyView.setEmptyText("您还没有观看记录,赶紧观看视频吧");
}
@Override
protected void initRefreshLayout() {
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
mSwipeRefreshLayout.post(() -> {
mSwipeRefreshLayout.setRefreshing(true);
loadData();
});
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadData();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
protected void initRecyclerView(){
mSwipeRefreshLayout.setRefreshing(false);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setNestedScrollingEnabled(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new HistoryListAdapter(getActivity(), mRecyclerView, historyListBeanList);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void finishTask() {
mSwipeRefreshLayout.setRefreshing(false);
mAdapter.notifyDataSetChanged();
}
public void initToolBar() {
mToolbar.setTitle("");
mToolbar.setNavigationIcon(R.drawable.ic_navigation_drawer);
mToolbar.setNavigationOnClickListener(v -> {
Activity activity1 = getActivity();
if (activity1 instanceof BangTVMainActivity) {
((BangTVMainActivity) activity1).toggleDrawer();
}
});
}
@Override
protected void loadData() {
mPlayRecordOpt = new PlayRecordHelpler(getActivity());
historyDataHandle = new HistoryDataHandle();
if(historyListBeanList!=null){
historyListBeanList.clear();
}
historyListBeanList.addAll( historyDataHandle.getHistorydata(mPlayRecordOpt));
if (0 == historyListBeanList.size()) {
historyempty();
}
else {
historyfull();
}
finishTask();
}
public void historyempty()
{
mToolbar.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.GONE);//View.VISIBLE
mRecyclerView.setVisibility(View.GONE);
mCustomEmptyView.setVisibility(View.VISIBLE);
}
public void historyfull() {
mToolbar.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.VISIBLE);//View.VISIBLE
mRecyclerView.setVisibility(View.VISIBLE);
mCustomEmptyView.setVisibility(View.GONE);
}
@Override
public void onResume() {
super.onResume();
loadData();
}
} | UTF-8 | Java | 4,804 | java | HistoryFragment.java | Java | [] | null | [] | package com.china.cibn.bangtvmobile.bangtv.module.home.history;
import butterknife.BindView;
import com.china.cibn.bangtvmobile.bangtv.apapter.HistoryListAdapter;
import com.china.cibn.bangtvmobile.bangtv.base.RxLazyFragment;
import com.china.cibn.bangtvmobile.bangtv.dal.PlayRecordHelpler;
import com.china.cibn.bangtvmobile.bangtv.entity.HistoryListInfo;
import com.china.cibn.bangtvmobile.bangtv.module.common.BangTVMainActivity;
import com.china.cibn.bangtvmobile.R;
import com.china.cibn.bangtvmobile.bangtv.widget.CustomEmptyView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* bix by gz 2018/04/24 14:12
*
* <p/>
* 历史记录
*/
public class HistoryFragment extends RxLazyFragment {
@BindView(R.id.empty_view)
CustomEmptyView mCustomEmptyView;
@BindView(R.id.toolbar)
Toolbar mToolbar;
//fix by gz 2018/04/20 横向滑动控件
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout mSwipeRefreshLayout;
//fix by gz 2018/04/20 横向滑动控件
@BindView(R.id.recycle)
RecyclerView mRecyclerView;
private HistoryListAdapter mAdapter;
private List<HistoryListInfo.HistoryListBean> historyListBeanList ;
private String mId;
private HistoryDataHandle historyDataHandle; //fix by gz 2018/04/19 database
private PlayRecordHelpler mPlayRecordOpt; //fix by gz 2018/04/19 database
public static HistoryFragment newInstance() {
return new HistoryFragment();
}
@Override
public int getLayoutResId() {
return R.layout.activity_history_bangtv;
}
@Override
public void finishCreateView(Bundle state) {
initCustomEmptyView();
initRefreshLayout();
initRecyclerView();
initToolBar();
}
public void initCustomEmptyView() {
historyListBeanList= new ArrayList<>();
mCustomEmptyView.setEmptyImage(R.drawable.ic_movie_pay_order_error03);
mCustomEmptyView.setEmptyText("您还没有观看记录,赶紧观看视频吧");
}
@Override
protected void initRefreshLayout() {
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
mSwipeRefreshLayout.post(() -> {
mSwipeRefreshLayout.setRefreshing(true);
loadData();
});
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadData();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
protected void initRecyclerView(){
mSwipeRefreshLayout.setRefreshing(false);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setNestedScrollingEnabled(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new HistoryListAdapter(getActivity(), mRecyclerView, historyListBeanList);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void finishTask() {
mSwipeRefreshLayout.setRefreshing(false);
mAdapter.notifyDataSetChanged();
}
public void initToolBar() {
mToolbar.setTitle("");
mToolbar.setNavigationIcon(R.drawable.ic_navigation_drawer);
mToolbar.setNavigationOnClickListener(v -> {
Activity activity1 = getActivity();
if (activity1 instanceof BangTVMainActivity) {
((BangTVMainActivity) activity1).toggleDrawer();
}
});
}
@Override
protected void loadData() {
mPlayRecordOpt = new PlayRecordHelpler(getActivity());
historyDataHandle = new HistoryDataHandle();
if(historyListBeanList!=null){
historyListBeanList.clear();
}
historyListBeanList.addAll( historyDataHandle.getHistorydata(mPlayRecordOpt));
if (0 == historyListBeanList.size()) {
historyempty();
}
else {
historyfull();
}
finishTask();
}
public void historyempty()
{
mToolbar.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.GONE);//View.VISIBLE
mRecyclerView.setVisibility(View.GONE);
mCustomEmptyView.setVisibility(View.VISIBLE);
}
public void historyfull() {
mToolbar.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.VISIBLE);//View.VISIBLE
mRecyclerView.setVisibility(View.VISIBLE);
mCustomEmptyView.setVisibility(View.GONE);
}
@Override
public void onResume() {
super.onResume();
loadData();
}
} | 4,804 | 0.743249 | 0.731435 | 175 | 26.091429 | 23.556684 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.474286 | false | false | 9 |
fe169ba48a3848301476269b087b2b1c661c69ce | 919,123,034,411 | afd3c3b3e216d7e73cbf0b52e36ab2d742b28225 | /app/src/main/java/com/silence/account/activity/BaseActivity.java | e82764f1a903f6665e8857cb29906b8dc85493f2 | [] | no_license | YuanHongGitHub/Account | https://github.com/YuanHongGitHub/Account | 500f5d3404d9e941e326e829de36cf6ef93677fa | dfb3ff0aa056dc49b5037d6221f92a7502837423 | refs/heads/master | 2018-03-04T18:45:06.839000 | 2016-03-30T07:47:16 | 2016-03-30T07:47:16 | 55,210,463 | 1 | 0 | null | true | 2016-04-01T06:55:16 | 2016-04-01T06:55:15 | 2016-03-30T07:36:31 | 2016-03-30T07:47:17 | 5,619 | 0 | 0 | 0 | null | null | null | package com.silence.account.activity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Silence on 2015/8/27 0027.
*/
public abstract class BaseActivity extends AppCompatActivity {
public ActionBar mActionBar;
public abstract void initView();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// RefWatcher refWatcher = AppApplication.getRefWatcher(this);
// refWatcher.watch(this);
mActionBar = getSupportActionBar();
initView();
}
public void disPlayBack(boolean visible) {
if (visible) {
if (mActionBar != null) {
mActionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
public void setActionTitle(String title) {
if (mActionBar != null) {
mActionBar.setTitle(title);
}
}
}
| UTF-8 | Java | 969 | java | BaseActivity.java | Java | [
{
"context": "pport.v7.app.AppCompatActivity;\n\n/**\n * Created by Silence on 2015/8/27 0027.\n */\npublic abstract class Base",
"end": 181,
"score": 0.9904332160949707,
"start": 174,
"tag": "USERNAME",
"value": "Silence"
}
] | null | [] | package com.silence.account.activity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Silence on 2015/8/27 0027.
*/
public abstract class BaseActivity extends AppCompatActivity {
public ActionBar mActionBar;
public abstract void initView();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// RefWatcher refWatcher = AppApplication.getRefWatcher(this);
// refWatcher.watch(this);
mActionBar = getSupportActionBar();
initView();
}
public void disPlayBack(boolean visible) {
if (visible) {
if (mActionBar != null) {
mActionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
public void setActionTitle(String title) {
if (mActionBar != null) {
mActionBar.setTitle(title);
}
}
}
| 969 | 0.648091 | 0.634675 | 38 | 24.5 | 20.943218 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342105 | false | false | 9 |
c380ef12e117043917a5d925bf35881f6c775820 | 17,987,323,090,919 | 8b825ccad0f843c9fdeee2bc965aea4c50ac4fed | /src/ba/unsa/etf/rpr/Main.java | 145271416007b46a884a0fb985ece23deb618004 | [] | no_license | pozde/rpr-t1-z2 | https://github.com/pozde/rpr-t1-z2 | 842272b22bb1549ab0dee92ce8f43c7f571d0789 | 237b143965c4a8139e2948ed4dee899ccfe51444 | refs/heads/master | 2023-01-03T19:32:28.125000 | 2020-10-27T15:31:30 | 2020-10-27T15:31:30 | 307,745,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ba.unsa.etf.rpr;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
System.out.println("Unesite n: ");
n=in.nextInt();
System.out.println("Brojevi izmedju 1 i n koji su djeljivi sa sumom svojih cifara su: ");
for(int i=1;i<=n;i++){
if(i%sumaCifara(i)==0){
System.out.println(i + " ");
}
}
}
private static int sumaCifara(int n){
int s = 0;
while(n > 0){
s = s + (n%10);
n = n/10;
}
return s;
}
}
| UTF-8 | Java | 652 | java | Main.java | Java | [] | null | [] | package ba.unsa.etf.rpr;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
System.out.println("Unesite n: ");
n=in.nextInt();
System.out.println("Brojevi izmedju 1 i n koji su djeljivi sa sumom svojih cifara su: ");
for(int i=1;i<=n;i++){
if(i%sumaCifara(i)==0){
System.out.println(i + " ");
}
}
}
private static int sumaCifara(int n){
int s = 0;
while(n > 0){
s = s + (n%10);
n = n/10;
}
return s;
}
}
| 652 | 0.489264 | 0.47546 | 30 | 20.733334 | 20.374712 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.